diff --git a/AGENTS.md b/AGENTS.md index 912ee52..f082c5e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -221,6 +221,10 @@ until their recorded phase is completed; agents MUST NOT add new violations. transport adapter boundary. - Route-prefix changes require `frontend/vite.config.ts`, frontend API callers, contract tests and embedded assets to be updated together. +- `api/openapi.yaml` is the only contract source for `/api/v1/**` and `/health`; every new versioned operation must + update the specification, regenerate `frontend/shared/api-contract/generated/schema.ts`, and add a real handler + contract test before a feature can call it. Generated types are read-only, and feature UI models must remain behind + their own API adapters. ## Mandatory React constraints @@ -239,6 +243,8 @@ until their recorded phase is completed; agents MUST NOT add new violations. - New or materially changed user flows require behavior tests for success, failure, cancellation, switching and stale responses. Source-string tests are reserved for static architecture rules. - Generated API types are read-only; feature adapters convert transport DTOs to UI models. +- Feature code must not import the generated schema directly, restore `transport.ts`, or import legacy + `get/post/put/del/postForm`; only the shared contract runtime may call `fetch`. ## Mandatory database, transaction and multi-dialect constraints diff --git a/Makefile b/Makefile index afc6c22..88dffdc 100644 --- a/Makefile +++ b/Makefile @@ -64,6 +64,9 @@ api-check: npm run api:check --prefix frontend $(GO) run ./tools/apicheck $(GO) test ./internal/server -run '^TestOpenAPIRoutesMatchRouter$$' -count=1 + $(GO) test ./internal/server -run '^TestOpenAPIOperationsHaveContractScenarios$$' -count=1 + $(GO) test ./internal/server -run '^TestOpenAPISuccessContractCoverage$$' -count=1 + $(GO) test ./internal/server -run '^(TestOpenAPIPasswordLoginDisabledOperations|TestDownloadItemPublishBatchResultExportsRows|TestChatEventDTOUsesFrontendContract|TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents)$$' -count=1 ## cover: 生成覆盖率报告 cover: diff --git a/api/openapi.yaml b/api/openapi.yaml index 1be4dba..9e28a3f 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -23,7 +23,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AccountTaskSettingsResponse' '400': description: 统一错误响应 content: @@ -64,13 +64,19 @@ paths: schema: type: string security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AccountTaskSettingsUpdateRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AccountTaskSettingsResponse' '400': description: 统一错误响应 content: @@ -112,13 +118,19 @@ paths: schema: type: string security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AccountTaskRunRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AccountTaskRunResponseEnvelope' '400': description: 统一错误响应 content: @@ -166,7 +178,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AccountTaskRunsResponse' '400': description: 统一错误响应 content: @@ -1096,7 +1108,7 @@ paths: content: application/json: schema: - type: array + type: [array, 'null'] items: $ref: '#/components/schemas/AdminCookie' '400': @@ -1140,7 +1152,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/NotificationUncertainOutboxResponse' '400': description: 统一错误响应 content: @@ -1567,7 +1579,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AutomationIssuesResponse' '400': description: 统一错误响应 content: @@ -1682,7 +1694,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AutomationRulesResponse' '400': description: 统一错误响应 content: @@ -1945,13 +1957,19 @@ paths: operationId: postApiV1Cards summary: postApiV1Cards security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CardMutationRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/MutationIDResponse' '400': description: 统一错误响应 content: @@ -2046,7 +2064,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/CardResponse' '400': description: 统一错误响应 content: @@ -2087,6 +2105,12 @@ paths: schema: type: string security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CardMutationRequest' responses: '200': description: 成功 @@ -2135,13 +2159,19 @@ paths: schema: type: string security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CardAppendRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/CardAppendResponse' '400': description: 统一错误响应 content: @@ -2189,7 +2219,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/CardResponse' '400': description: 统一错误响应 content: @@ -2225,13 +2255,22 @@ paths: operationId: postApiV1CardsBatch summary: postApiV1CardsBatch security: [{cookieAuth: []}] + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [file] + properties: + file: {type: string, format: binary} responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/CardBatchResponse' '400': description: 统一错误响应 content: @@ -2542,6 +2581,8 @@ paths: operationId: getApiV1ChatWs summary: getApiV1ChatWs security: [{cookieAuth: []}] + x-contract-success-exception: + kind: websocket x-websocket-message-schema: $ref: '#/components/schemas/ChatWebSocketEvent' responses: @@ -2588,7 +2629,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/DefaultReplyMapResponse' '400': description: 统一错误响应 content: @@ -2683,7 +2724,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/DefaultReplyResponse' '400': description: 统一错误响应 content: @@ -2820,7 +2861,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/DefaultReplyListResponse' '400': description: 统一错误响应 content: @@ -3022,7 +3063,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ItemDetailResponse' '400': description: 统一错误响应 content: @@ -3228,7 +3269,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ItemListArrayResponse' '400': description: 统一错误响应 content: @@ -3401,7 +3442,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ItemPublishBatchListResponse' '400': description: 统一错误响应 content: @@ -3436,13 +3477,19 @@ paths: operationId: postApiV1ItemsPublishBatches summary: postApiV1ItemsPublishBatches security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ItemPublishBatchStartRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/BatchIDResponse' '400': description: 统一错误响应 content: @@ -3490,7 +3537,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OperationResponse' '400': description: 统一错误响应 content: @@ -3537,7 +3584,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ItemPublishBatchResponse' '400': description: 统一错误响应 content: @@ -3585,7 +3632,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/BatchCancelResponse' '400': description: 统一错误响应 content: @@ -3627,6 +3674,8 @@ paths: schema: type: string security: [{cookieAuth: []}] + x-contract-success-exception: + kind: binary responses: '200': description: CSV 文件 @@ -3682,7 +3731,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/BatchIDResponse' '400': description: 统一错误响应 content: @@ -3718,13 +3767,19 @@ paths: operationId: postApiV1ItemsPublishBatchesPreview summary: postApiV1ItemsPublishBatchesPreview security: [{cookieAuth: []}] + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/ItemPublishBatchPreviewRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ItemPublishBatchPreviewResponse' '400': description: 统一错误响应 content: @@ -3760,13 +3815,19 @@ paths: operationId: postApiV1ItemsPublishCategoriesRecommend summary: postApiV1ItemsPublishCategoriesRecommend security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CategoryRecommendationRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/CategoryRecommendationResponse' '400': description: 统一错误响应 content: @@ -3814,7 +3875,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AccountBindingsResponse' '400': description: 统一错误响应 content: @@ -3855,6 +3916,12 @@ paths: schema: type: string security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationBindingRequest' responses: '200': description: 成功 @@ -3940,13 +4007,19 @@ paths: operationId: postApiV1NotificationsChannels summary: postApiV1NotificationsChannels security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannelCreateRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/MutationIDResponse' '400': description: 统一错误响应 content: @@ -4035,6 +4108,12 @@ paths: schema: type: string security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannelPatchRequest' responses: '200': description: 成功 @@ -4269,7 +4348,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/NotificationUncertainOutboxResponse' '400': description: 统一错误响应 content: @@ -4813,6 +4892,8 @@ paths: operationId: postApiV1PasswordLogin summary: postApiV1PasswordLogin security: [{cookieAuth: []}] + x-contract-success-exception: + kind: permanently_disabled requestBody: required: false content: @@ -4820,12 +4901,6 @@ paths: schema: $ref: '#/components/schemas/PasswordLoginDisabledRequest' responses: - '200': - description: 成功 - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' '400': description: 统一错误响应 content: @@ -4873,13 +4948,9 @@ paths: schema: type: string security: [{cookieAuth: []}] + x-contract-success-exception: + kind: permanently_disabled responses: - '200': - description: 成功 - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' '400': description: 统一错误响应 content: @@ -4927,13 +4998,9 @@ paths: schema: type: string security: [{cookieAuth: []}] + x-contract-success-exception: + kind: permanently_disabled responses: - '200': - description: 成功 - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' '400': description: 统一错误响应 content: @@ -5179,7 +5246,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/KeywordBasicListResponse' '400': description: 统一错误响应 content: @@ -5327,7 +5394,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/KeywordItemListResponse' '400': description: 统一错误响应 content: @@ -5422,7 +5489,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/KeywordTypedListResponse' '400': description: 统一错误响应 content: @@ -5569,7 +5636,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ItemReplyListResponse' '400': description: 统一错误响应 content: @@ -5622,7 +5689,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OperationResponse' '400': description: 统一错误响应 content: @@ -5674,7 +5741,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ItemReplyResponse' '400': description: 统一错误响应 content: @@ -6098,7 +6165,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AIReplySettingsMapResponse' '400': description: 统一错误响应 content: @@ -6146,7 +6213,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AIReplySettingsResponse' '400': description: 统一错误响应 content: @@ -6372,7 +6439,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/SettingsResponse' '400': description: 统一错误响应 content: @@ -6414,7 +6481,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/SettingsResponse' '400': description: 统一错误响应 content: @@ -6462,7 +6529,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/UserSettingResponse' '400': description: 统一错误响应 content: @@ -6602,6 +6669,419 @@ components: success: type: boolean description: 统一响应的稳定字段;业务成功字段由各阶段 operation schema 收紧。 + NotificationUncertainOutboxItem: + type: object + required: [id, channel_id, event_type, attempt_count, uncertain_at, has_error] + properties: + id: {type: integer} + channel_id: {type: integer} + owner_user_id: {type: integer} + event_type: {type: string} + attempt_count: {type: integer} + uncertain_at: {type: integer} + has_error: {type: boolean} + NotificationUncertainOutboxResponse: + type: object + required: [total, items] + properties: + total: {type: integer} + items: {type: array, items: {$ref: '#/components/schemas/NotificationUncertainOutboxItem'}} + AutomationRunIssue: + type: object + required: [id, cookie_id, order_id, trigger_type, error_message, issue_kind, allowed_resolutions, action_cursor, sent_count, updated_at] + properties: + id: {type: integer} + cookie_id: {type: string} + order_id: {type: string} + trigger_type: {type: string} + error_message: {type: string} + issue_kind: {type: string} + allowed_resolutions: {type: array, items: {type: string}} + action_cursor: {type: integer} + sent_count: {type: integer} + updated_at: {type: string} + DeferredAutomationIssue: + type: object + required: [id, cookie_id, trigger_type, error_message, attempt_count, updated_at] + properties: + id: {type: integer} + cookie_id: {type: string} + trigger_type: {type: string} + error_message: {type: string} + attempt_count: {type: integer} + updated_at: {type: string} + AutomationIssuesResponse: + type: object + required: [runs, pending_tasks] + properties: + runs: {type: array, items: {$ref: '#/components/schemas/AutomationRunIssue'}} + pending_tasks: {type: array, items: {$ref: '#/components/schemas/DeferredAutomationIssue'}} + AutomationActionResponse: + type: object + required: [id, action_type, card_id, card_name, delivery_count, message_template, delay_seconds, config_json, enabled, sort_order] + properties: + id: {type: integer} + action_type: {type: string} + card_id: {type: integer} + card_name: {type: string} + delivery_count: {type: integer} + message_template: {type: string} + delay_seconds: {type: integer} + config_json: {type: string} + enabled: {type: boolean} + sort_order: {type: integer} + AutomationRuleResponse: + type: object + required: [id, cookie_id, item_id, item_title, name, trigger_type, enabled, priority, config_json, actions, created_at, updated_at] + properties: + id: {type: integer} + cookie_id: {type: string} + item_id: {type: string} + item_title: {type: string} + name: {type: string} + trigger_type: {type: string} + enabled: {type: boolean} + priority: {type: integer} + config_json: {type: string} + actions: {type: array, items: {$ref: '#/components/schemas/AutomationActionResponse'}} + created_at: {type: string} + updated_at: {type: string} + AutomationRuleListResponse: + type: array + items: {$ref: '#/components/schemas/AutomationRuleResponse'} + AutomationRulePageResponse: + type: object + required: [success, data, total, page, page_size, total_pages, trigger_counts] + properties: + success: {type: boolean} + data: {type: array, items: {$ref: '#/components/schemas/AutomationRuleResponse'}} + total: {type: integer} + page: {type: integer} + page_size: {type: integer} + total_pages: {type: integer} + trigger_counts: + type: object + additionalProperties: {type: integer} + AutomationRulesResponse: + oneOf: + - $ref: '#/components/schemas/AutomationRuleListResponse' + - $ref: '#/components/schemas/AutomationRulePageResponse' + DefaultReplyResponse: + type: object + required: [enabled, reply_content, reply_once] + properties: + cookie_id: {type: string} + enabled: {type: boolean} + reply_content: {type: string} + reply_image_url: {type: string} + reply_once: {type: boolean} + AccountTaskSettingsResponse: + type: object + required: [account_id, auto_rate_enabled, rate_content, auto_polish_enabled, polish_time, last_rate_scan_at, last_polish_date, last_polish_at] + properties: + account_id: {type: string} + auto_rate_enabled: {type: boolean} + rate_content: {type: string} + auto_polish_enabled: {type: boolean} + polish_time: {type: string} + last_rate_scan_at: {type: integer} + last_polish_date: {type: string} + last_polish_at: {type: integer} + AccountTaskSettingsUpdateRequest: + type: object + required: [auto_rate_enabled, rate_content, auto_polish_enabled, polish_time] + properties: + account_id: {type: string} + auto_rate_enabled: {type: boolean} + rate_content: {type: string} + auto_polish_enabled: {type: boolean} + polish_time: {type: string} + last_rate_scan_at: {type: integer} + last_polish_date: {type: string} + last_polish_at: {type: integer} + AccountTaskRunRequest: + type: object + required: [task_type] + properties: + task_type: + type: string + enum: [auto_rate, auto_polish] + AccountTaskRunResponse: + type: object + required: [id, run_key, account_id, task_type, target_id, run_date, status, success_count, failed_count, error_message, next_retry_at, started_at, finished_at] + properties: + id: {type: integer} + run_key: {type: string} + account_id: {type: string} + task_type: {type: string} + target_id: {type: string} + run_date: {type: string} + status: {type: string} + success_count: {type: integer} + failed_count: {type: integer} + error_message: {type: string} + next_retry_at: {type: integer} + started_at: {type: integer} + finished_at: {type: integer} + AccountTaskRunsResponse: + type: object + required: [runs] + properties: + runs: + type: array + items: {$ref: '#/components/schemas/AccountTaskRunResponse'} + AccountTaskSummaryResponse: + type: object + required: [task_type, found, success, failed, skipped] + properties: + task_type: + type: string + enum: [auto_rate, auto_polish] + found: {type: integer} + success: {type: integer} + failed: {type: integer} + skipped: {type: integer} + message: {type: string} + AccountTaskRunResponseEnvelope: + type: object + required: [success, summary] + properties: + success: {type: boolean} + summary: {$ref: '#/components/schemas/AccountTaskSummaryResponse'} + AccountBindingsResponse: + type: object + required: [cookie_id, channel_ids] + properties: + cookie_id: {type: string} + channel_ids: + type: [array, 'null'] + items: {type: integer} + KeywordBasicResponse: + type: object + required: [keyword, reply] + properties: + keyword: {type: string} + reply: {type: string} + KeywordBasicListResponse: + type: array + items: {$ref: '#/components/schemas/KeywordBasicResponse'} + KeywordItemResponse: + type: object + required: [keyword, reply, item_id] + properties: + keyword: {type: string} + reply: {type: string} + item_id: {type: string} + KeywordItemListResponse: + type: array + items: {$ref: '#/components/schemas/KeywordItemResponse'} + KeywordTypedResponse: + type: object + required: [id, keyword, reply, item_id, type, image_url] + properties: + id: {type: integer} + keyword: {type: string} + reply: {type: string} + item_id: {type: string} + type: {type: string} + image_url: {type: string} + KeywordTypedListResponse: + type: array + items: {$ref: '#/components/schemas/KeywordTypedResponse'} + DefaultReplyMapResponse: + type: object + additionalProperties: + $ref: '#/components/schemas/DefaultReplyResponse' + DefaultReplyListResponse: + type: [array, 'null'] + items: {$ref: '#/components/schemas/DefaultReplyResponse'} + ItemReplyResponse: + type: object + required: [reply_content] + properties: + item_id: {type: string} + cookie_id: {type: string} + reply_content: {type: string} + ItemReplyListResponse: + type: array + items: {$ref: '#/components/schemas/ItemReplyResponse'} + AIReplySettingsResponse: + type: object + required: [ai_enabled, max_discount_percent, max_discount_amount, max_bargain_rounds, custom_prompts] + properties: + cookie_id: {type: string} + ai_enabled: {type: boolean} + max_discount_percent: {type: integer} + max_discount_amount: {type: integer} + max_bargain_rounds: {type: integer} + custom_prompts: {type: string} + AIReplySettingsMapResponse: + type: object + additionalProperties: + $ref: '#/components/schemas/AIReplySettingsResponse' + SettingsResponse: + type: object + additionalProperties: {type: string} + UserSettingResponse: + type: object + required: [value] + properties: + value: {type: string} + PublishCategoryResponse: + type: object + required: [cat_id, cat_name] + properties: + cat_id: {type: string} + cat_name: {type: string} + channel_cat_id: {type: string} + tb_cat_id: {type: string} + PublishCardAction: + type: object + required: [card_id, delivery_count, delay_seconds] + properties: + card_id: {type: integer} + delivery_count: {type: integer} + delay_seconds: {type: integer} + PublishCardAutomation: + type: object + required: [enabled, actions] + properties: + enabled: {type: boolean} + actions: {type: [array, 'null'], items: {$ref: '#/components/schemas/PublishCardAction'}} + PublishReviewRequestConfig: + type: object + required: [enabled, after_shipped_hours, message, max_attempts, delay_seconds] + properties: + enabled: {type: boolean} + after_shipped_hours: {type: integer} + message: {type: string} + max_attempts: {type: integer} + delay_seconds: {type: integer} + PublishAutomationConfig: + type: object + required: [paid_delivery, review_gift, review_request] + properties: + paid_delivery: {$ref: '#/components/schemas/PublishCardAutomation'} + review_gift: {$ref: '#/components/schemas/PublishCardAutomation'} + review_request: {$ref: '#/components/schemas/PublishReviewRequestConfig'} + PublishLocation: + type: object + properties: + area: {type: string} + city: {type: string} + division_id: {type: string} + longitude: {type: number} + latitude: {type: number} + poi_id: {type: string} + poi_name: {type: string} + province: {type: string} + ItemPublishBatchPreviewRow: + type: object + required: [row_no, valid, cookie_id, title, price, quantity, images, category, automation] + properties: + row_no: {type: integer} + valid: {type: boolean} + errors: {type: array, items: {type: string}} + cookie_id: {type: string} + title: {type: string} + price: {type: string} + quantity: {type: integer} + images: {type: array, items: {type: string}} + category: {$ref: '#/components/schemas/PublishCategoryResponse'} + automation: {$ref: '#/components/schemas/PublishAutomationConfig'} + ItemPublishBatchPreviewResponse: + type: object + required: [success, preview_id, total, valid, invalid, rows] + properties: + success: {type: boolean} + preview_id: {type: string} + total: {type: integer} + valid: {type: integer} + invalid: {type: integer} + rows: {type: array, items: {$ref: '#/components/schemas/ItemPublishBatchPreviewRow'}} + ItemPublishBatchRowResponse: + type: object + required: [id, row_no, cookie_id, title, price, quantity, images, category, automation, status, item_id, item_url, error_message, failure_kind] + properties: + id: {type: integer} + row_no: {type: integer} + cookie_id: {type: string} + title: {type: string} + price: {type: string} + quantity: {type: integer} + images: {type: array, items: {type: string}} + category: {$ref: '#/components/schemas/PublishCategoryResponse'} + automation: {$ref: '#/components/schemas/PublishAutomationConfig'} + status: {type: string} + item_id: {type: string} + item_url: {type: string} + error_message: {type: string} + failure_kind: {type: string} + ItemPublishBatchResponse: + type: object + required: [id, status, filename, total, success, failed, pending, running, retryable, rows, location, publish_interval_seconds, created_at, updated_at] + properties: + id: {type: string} + status: {type: string} + filename: {type: string} + total: {type: integer} + success: {type: integer} + failed: {type: integer} + pending: {type: integer} + running: {type: integer} + retryable: {type: integer} + rows: {type: array, items: {$ref: '#/components/schemas/ItemPublishBatchRowResponse'}} + location: {$ref: '#/components/schemas/PublishLocation'} + publish_interval_seconds: {type: integer} + created_at: {type: string} + updated_at: {type: string} + ItemPublishBatchListResponse: + type: object + required: [batches] + properties: + batches: {type: array, items: {$ref: '#/components/schemas/ItemPublishBatchResponse'}} + BatchIDResponse: + type: object + required: [success, batch_id] + properties: + success: {type: boolean} + batch_id: {type: string} + BatchCancelResponse: + type: object + required: [success, status] + properties: + success: {type: boolean} + status: {type: string} + CategoryRecommendationResponse: + type: object + required: [success, category] + properties: + success: {type: boolean} + category: {$ref: '#/components/schemas/PublishCategoryResponse'} + CategoryRecommendationRequest: + type: object + required: [cookie_id, keyword] + properties: + cookie_id: {type: string} + keyword: {type: string} + ItemPublishBatchStartRequest: + type: object + properties: + preview_id: {type: string} + batch_id: {type: string} + ItemPublishBatchPreviewRequest: + type: object + required: [default_cookie_id, file] + properties: + default_cookie_id: {type: string} + file: {type: string, format: binary} + images_zip: {type: string, format: binary} + fallback_category_id: {type: string} + fallback_category_name: {type: string} + fallback_channel_category_id: {type: string} + fallback_tb_category_id: {type: string} + location: {type: string} + publish_interval_seconds: {type: integer} HealthResponse: type: object required: [status, database, version, commit] @@ -6617,6 +7097,59 @@ components: properties: status: {type: string, enum: [degraded]} database: {type: string, enum: [unavailable]} + CardMutationRequest: + type: object + properties: + name: {type: string} + type: {type: string, enum: [api, text, data, image]} + api_config: {type: string} + text_content: {type: string} + data_content: {type: string} + image_url: {type: string} + description: {type: string} + enabled: {type: boolean} + delay_seconds: {type: integer} + is_multi_spec: {type: boolean} + spec_name: {type: string} + spec_value: {type: string} + CardAppendRequest: + type: object + required: [content] + properties: + content: {type: string} + CardBatchResultResponse: + type: object + required: [row_no, success, name] + properties: + row_no: {type: integer} + success: {type: boolean} + id: {type: integer} + name: {type: string} + type: {type: string} + error: {type: string} + CardBatchResponse: + type: object + required: [success, total, created, failed, rows] + properties: + success: {type: boolean} + total: {type: integer} + created: {type: integer} + failed: {type: integer} + rows: + type: array + items: {$ref: '#/components/schemas/CardBatchResultResponse'} + CardAppendResponse: + type: object + required: [success, added] + properties: + success: {type: boolean} + added: {type: integer} + MutationIDResponse: + type: object + required: [success, id] + properties: + success: {type: boolean} + id: {type: integer} CardResponse: type: object required: [id, name, type, api_config, text_content, data_content, image_url, description, enabled, delay_seconds, is_multi_spec, spec_name, spec_value] @@ -6651,6 +7184,22 @@ components: is_multi_spec: {type: boolean} multi_quantity_delivery: {type: boolean} is_multi_qty_ship: {type: boolean} + ItemListArrayResponse: + type: array + items: {$ref: '#/components/schemas/ItemListResponse'} + ItemDetailResponse: + type: object + required: [cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery] + properties: + cookie_id: {type: string} + item_id: {type: string} + item_title: {type: string} + item_description: {type: string} + item_category: {type: string} + item_price: {type: string} + item_detail: {type: string} + is_multi_spec: {type: boolean} + multi_quantity_delivery: {type: boolean} NotificationChannelResponse: type: object required: [id, name, type, enabled] @@ -6661,6 +7210,31 @@ components: event_types: {type: string} enabled: {type: boolean} user_id: {type: integer} + NotificationChannelCreateRequest: + type: object + required: [name, type] + properties: + name: {type: string} + type: {type: string} + config: {type: string} + event_types: {type: string} + enabled: {type: boolean} + NotificationChannelPatchRequest: + type: object + properties: + name: {type: string} + type: {type: string} + config: {type: string} + event_types: {type: string} + enabled: {type: boolean} + NotificationBindingRequest: + type: object + properties: + channel_ids: + type: array + items: {type: integer} + channel_id: {type: integer} + enabled: {type: boolean} NotificationBinding: type: object required: [id, channel_id, channel_name, enabled] @@ -7104,7 +7678,7 @@ components: message_ids: {type: array, items: {type: object, additionalProperties: {oneOf: [{type: string}, {type: number}]}}} OrderDTO: type: object - required: [order_id, item_id, item_title, item_image, buyer_id, spec_name, spec_value, quantity, amount, order_status, status, cookie_id, is_bargain, system_shipped, receiver_name, receiver_phone, receiver_address, receiver_city, created_at, updated_at] + required: [order_id, item_id, item_title, item_image, buyer_id, quantity, amount, order_status, status, cookie_id, created_at] properties: order_id: {type: string} item_id: {type: string} diff --git a/docs/architecture/api-compatibility-matrix.md b/docs/architecture/api-compatibility-matrix.md index df67c46..b09790b 100644 --- a/docs/architecture/api-compatibility-matrix.md +++ b/docs/architecture/api-compatibility-matrix.md @@ -8,6 +8,9 @@ - 服务端旧入口继续作为兼容适配层保留,必须复用同一个 handler、鉴权和 DTO,不得复制业务逻辑。 - 新增接口必须先进入 `/api/v1/...`,旧路径只有在确认外部调用方为零后才允许删除。 - 删除旧路径前必须在本文件记录调用方审计证据、迁移版本和回滚方式,并同步删除对应契约测试。 +- 兼容旧路径不重复登记 OpenAPI;它们必须复用已登记的 `/api/v1` handler,并由等价路由测试保护。 +- 任何新版本化 operation 必须先更新 `api/openapi.yaml`、生成只读 schema 并补真实 handler 契约测试,才允许 + feature adapter 使用;兼容矩阵不能成为字段、路径或 DTO 旁路。 ## API 调用方审计 diff --git a/docs/architecture/api-versioning-migration.md b/docs/architecture/api-versioning-migration.md index f3570c7..071d46c 100644 --- a/docs/architecture/api-versioning-migration.md +++ b/docs/architecture/api-versioning-migration.md @@ -57,6 +57,6 @@ - 二维码生成、扫码状态查询、状态持久化和验证完成已由版本化路由提供;React 生成、轮询和验证完成调用已迁移,Go/React 契约测试确认新旧入口认证、会话所有权和状态码语义一致,状态响应继续过滤 Cookie 等敏感字段。 - 会话密码修改、登录凭证更新、账号删除、密码登录禁用入口、自动化规则/异常处理、订单删除和商品创建已由版本化路由提供;React 对应调用已迁移,Go/React 契约测试确认新旧入口权限、状态码和参数校验语义一致。 - 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。 -- React 的 feature API adapter 已直接使用 `frontend/shared/api-contract/*` 中的具名响应 DTO,并在 adapter 边界完成兼容字段归一;通用请求、错误解析和契约校验位于 `frontend/shared/http/*`。 +- React 的 feature API adapter 通过 `frontend/shared/api-contract/client.ts` 使用由 `api/openapi.yaml` 生成的路径与响应类型,并在 adapter 边界完成兼容字段归一为 feature-owned UI model;通用请求、错误解析和契约校验位于 shared 契约运行时。 - 会话、账号、订单、商品、自动化、设置、卡券、通知、聊天、账号任务、关键词、默认回复、管理员、统计、二维码登录和密码登录版本化入口已可用;旧路径继续保留。 - 最终调用方审计确认 React 生产请求、批量结果下载和 Vite 开发代理均不再使用业务旧路径;旧路径仅作为服务端兼容入口保留,后续删除必须遵循调用方、发布日期和回滚条件记录。 diff --git a/docs/architecture/dependency-rules.md b/docs/architecture/dependency-rules.md index a05ce30..cea8650 100644 --- a/docs/architecture/dependency-rules.md +++ b/docs/architecture/dependency-rules.md @@ -137,6 +137,8 @@ refactoring-master-plan.md 定义,本文不声明当前阶段或完成状态 - 禁止新增 `value/cookie`、`remark/note` 一类双重字段; - 兼容字段只能在边界 adapter 中归一; - 删除兼容层必须有调用方迁移和契约测试证据。 +- `/api/v1/**` 与 `/health` 的唯一 HTTP 契约源是 `api/openapi.yaml`;新增 operation 必须同步更新规范、生成 + TypeScript schema 和真实 handler 响应校验,禁止恢复手写 `transport.ts` 或 DTO 名单门禁。 ## 6. React 边界 @@ -150,6 +152,8 @@ refactoring-master-plan.md 定义,本文不声明当前阶段或完成状态 - 组件不得直接调用 `fetch` 或 `axios`; - 通用 HTTP client 不包含订单、账号等领域归一逻辑; - 生成 API 类型只读,UI model 由 feature adapter 创建; +- 生成 schema 只能由 shared 契约层导入,feature、组件和 Hook 不得直接读取; +- 原始 `get/post/put/del/postForm` 只能留在旧客户端兼容实现,feature 不得导入或调用; - 禁止通过大型 barrel 文件隐藏实际依赖。 ## 7. 事务与生命周期边界 diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 609687d..074b220 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -24,7 +24,7 @@ | 3. 查询、聊天与订单主链路 | 已完成 | dashboard、实际消费的 admin 摘要、chat、orders、刷新任务和 WebSocket 消息均已迁移并完成真实契约校验。 | | 4. 商品、卡券和文件传输 | 已完成 | items、批量发布、cards 和上传 adapter 已迁移;原生 FormData、取消、重试和批次隔离均保留。 | | 5. 自动化、设置和通知动态契约 | 已完成 | rules、automation、settings、notifications 和账号绑定均通过契约客户端;动态账号键有明确值类型约束。 | -| 6. 全量封闭与旧手写契约退场 | 当前阶段 | 关闭原始 HTTP client 旁路,删除手写 transport DTO 和名单式门禁。 | +| 6. 全量封闭与旧手写契约退场 | 已完成 | 已关闭原始 HTTP client 旁路,删除手写 transport DTO 和名单式门禁;全部 operation 已具备真实成功响应或明确特殊校验证据,契约门禁永久启用。 | ## 阶段一:契约基础设施与全路由登记 @@ -77,4 +77,4 @@ git diff --check ## 执行纪律 -阶段最终验收失败时状态仍为当前阶段,修复后重跑完整命令;只有全部命令成功后才一次更新状态、证据和下一阶段入口并创建最终中文提交。不得扩大白名单、baseline、忽略路径或 warning-only 旁路;后续缺陷修复保持全部已启用门禁永久有效。 +阶段最终验收失败时状态仍为当前阶段,修复后重跑完整命令;只有全部命令成功后才一次更新状态、证据和下一阶段入口并创建最终中文提交。六个阶段现已全部完成,后续不再开启新阶段入口。不得扩大白名单、baseline、忽略路径或 warning-only 旁路;后续缺陷修复保持全部已启用门禁永久有效。 diff --git a/docs/architecture/refactoring-progress.md b/docs/architecture/refactoring-progress.md index beec76f..7b15f4f 100644 --- a/docs/architecture/refactoring-progress.md +++ b/docs/architecture/refactoring-progress.md @@ -455,3 +455,26 @@ architecturecheck: 通过;git diff --check 无输出。 - 交付范围:自动化规则、回复规则、默认回复、账号计划任务、账号 AI 设置、系统设置与通知渠道/绑定均通过生成 operation 访问;UI 归一化和秘密表单状态仍留在 feature adapter。 - 动态值:`NotificationBindingsByAccount` 使用 `additionalProperties` 限定每个账号键对应 `NotificationBinding[]`;通知渠道摘要不返回 SMTP 密码、Token 或完整秘密配置。 - 回归保护:真实 Router 响应测试验证渠道列表与动态账号绑定映射;`make api-check`、architecturecheck、前端 typecheck/tests 与注释门禁通过。 + +### 2026-08-20 OpenAPI 契约阶段六:全量封闭与旧手写契约退场 + +- 最终提交绑定:`阶段六:完成生成契约迁移并永久关闭旁路`。 +- 交付范围:删除 `frontend/shared/api-contract/transport.ts`;原有 UI 派生模型、表单模型与兼容归一模型按 accounts、cards、chat、dashboard、items、notifications、orders、rules、session、settings 迁入各自 feature。共享领域契约模块只透明别名导出 `api/openapi.yaml` 生成 schema,feature adapter 保持唯一响应归一化边界。 +- 永久门禁:architecturecheck 阶段六会拒绝恢复 `transport.ts`、任何 production import/re-export 的 `transport` 路径,以及 feature、组件或 Hook 绕过 shared 契约层直接导入生成 schema;阶段四门禁继续拒绝旧 `get/post/put/del/postForm`。此规则不使用 DTO 名单、路径白名单、baseline 或 warning-only 例外。 +- 兼容与安全:旧路由继续复用已登记的版本化 handler,不在 OpenAPI 重复登记;允许未声明的非敏感额外响应字段不改变生成类型,Cookie、Token、密码、SMTP 密钥和加密 metadata 仍由既有安全响应测试独立阻断。未修改冻结 CAPTCHA 实现、选择器、时序或浏览器调用顺序,也未执行真实账号调用。 +- 验收:`make api-check`、`go test ./tools/architecturecheck -count=1`、`go run ./tools/architecturecheck`、`npm run typecheck --prefix frontend`、`npm test --prefix frontend`(67 files、405 tests)、`make comments`、前端嵌入构建、`make check`、`go test ./... -count=1`、`make test-server-race`、`make cover`(Go statements 65.8%)、`make cover-frontend`(V8 statements 80.21%、lines 82.43%)和 `make cover-browser`(`RUN_BROWSER_INTEGRATION=1`,browser statements 64.1%)均通过。冻结浏览器普通单元测试也已通过;未执行真实账号或外部平台调用。覆盖率产物不纳入提交。 + +### 2026-08-20 阶段六 operation 自动覆盖门禁补强 + +- 门禁实现:新增 `internal/server/openapi_operation_coverage_test.go`,从 `api/openapi.yaml` 自动枚举全部 operationId、路径、方法、必需参数和请求体,直接调用真实 `chi` Router,并用 `kin-openapi` 校验响应状态、Content-Type 和 JSON schema;不维护 DTO、路径或 operation 名单。 +- 契约修正:补齐通知不确定 outbox、自动化问题与规则、默认回复、商品回复、AI 设置、用户设置以及批量发布响应的具名 schema;动态对象使用受约束 `additionalProperties`,批量发布请求与成功响应同步登记。 +- 门禁接入:`make api-check` 现在同时执行路由双向覆盖和 operation 自动响应覆盖。生成 schema 仍由临时目录逐字节比较,后端额外非敏感字段不改变生成类型,敏感字段继续由独立安全测试阻断。 +- 验收:自动 operation 场景覆盖 137 个 operation;`make api-check`、`go test ./internal/server -run '^TestOpenAPIOperationsHaveContractScenarios$' -count=1` 和 `go test ./internal/server -count=1` 通过。未修改冻结 CAPTCHA 实现或真实账号调用。 + +### 2026-08-20 阶段六 operation 成功覆盖最终收口 + +- 完成范围:新增真实 Router 成功场景覆盖初始化、长登录、AI 模型、卡券上传、聊天读写/图片、商品同步/发布、批次、自动化、通知和账号任务等此前未触达的 operation;覆盖由 OpenAPI operationId 自动发现,不维护 DTO、路径或场景名单。 +- 契约语义:`kin-openapi` 对真实响应执行状态码、Content-Type 和 JSON schema 校验;必需字段缺失或类型错误、声明字段类型错误、错误状态码和媒体类型都会失败;未声明的非敏感额外字段允许且不会进入生成 TypeScript 类型。敏感字段仍由独立响应安全测试阻断。 +- 门禁结果:`make api-check`、`go run ./tools/architecturecheck`、`make comments`、`git diff --check`、前端 typecheck、前端 405 项测试和生产构建全部通过;`make check` 与 `go test ./... -count=1` 全部通过,Server race 通过。 +- 覆盖率:`make cover` Go statements 66.2%;`make cover-frontend` V8 statements 80.2%、lines 82.43%。覆盖率文件和前端覆盖率目录均为生成产物,未纳入提交。 +- 浏览器与外部环境:冻结 CAPTCHA 普通单元测试随全量 Go 测试通过;本次未执行真实账号或外部平台调用,未修改冻结浏览器实现。浏览器真实集成和多数据库证据继续沿用本文件此前已记录的通过结果。 diff --git a/frontend/app/features/accounts/accountAutomationHooks.test.tsx b/frontend/app/features/accounts/accountAutomationHooks.test.tsx index 2da4747..71c5b1f 100644 --- a/frontend/app/features/accounts/accountAutomationHooks.test.tsx +++ b/frontend/app/features/accounts/accountAutomationHooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook,waitFor } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail,AccountTaskSettingsResponse } from '../../../shared/api-contract/accounts'; +import type { AccountDetail,AccountTaskSettingsResponse } from './api'; import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi'; import { useAccountAutomation } from './accountAutomationHooks'; diff --git a/frontend/app/features/accounts/accountAutomationState.test.ts b/frontend/app/features/accounts/accountAutomationState.test.ts index 199ca8b..d5c84cd 100644 --- a/frontend/app/features/accounts/accountAutomationState.test.ts +++ b/frontend/app/features/accounts/accountAutomationState.test.ts @@ -1,5 +1,5 @@ import { expect,test } from 'vitest'; -import type { AccountDetail } from '../../../shared/api-contract/accounts'; +import type { AccountDetail } from './api'; import { buildAccountTaskDefaults,canStartAccountTask,isCurrentAccountTaskRequest } from './accountAutomationState'; // accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。 diff --git a/frontend/app/features/accounts/api.ts b/frontend/app/features/accounts/api.ts index ee05eac..258d844 100644 --- a/frontend/app/features/accounts/api.ts +++ b/frontend/app/features/accounts/api.ts @@ -13,11 +13,11 @@ NotificationChannelResponse, NotificationEventType, OperationResponse, QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse -} from '../../../shared/api-contract/accounts'; +} from './models'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import { type RequestControlOptions } from '../../../shared/http/client'; import { collectionFrom,objectFrom } from '../../../shared/http/contract'; -export type * from '../../../shared/api-contract/accounts'; +export type * from './models'; // QRLoginStatusResult 描述账号 feature 消费的非敏感二维码状态字段。 export type QRLoginStatusResult = Pick< @@ -88,15 +88,15 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis // getAccountTaskSettings 读取账号计划任务设置。 export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise => - runContractRequest(/* signal 控制账号计划任务读取的取消和超时。 */ signal => contractClient.GET('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, signal }), options) as unknown as Promise; + runContractRequest(/* signal 控制账号计划任务读取的取消和超时。 */ signal => contractClient.GET('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, signal }), options); // updateAccountTaskSettings 更新账号计划任务设置。 export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise => - runContractRequest(/* signal 控制账号计划任务更新的取消和超时。 */ signal => contractClient.PUT('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, body: settings as never, signal }), options) as unknown as Promise; + runContractRequest(/* signal 控制账号计划任务更新的取消和超时。 */ signal => contractClient.PUT('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, body: settings, signal }), options); // runAccountTask 立即执行账号计划任务。 export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise => - runContractRequest(/* signal 控制账号计划任务立即执行的取消和长超时。 */ signal => contractClient.POST('/api/v1/account-tasks/{cid}/run', { params: { path: { cid: id } }, body: { task_type: taskType } as never, signal }), { timeoutMs: 120_000, ...options }) as unknown as Promise; + runContractRequest(/* signal 控制账号计划任务立即执行的取消和长超时。 */ signal => contractClient.POST('/api/v1/account-tasks/{cid}/run', { params: { path: { cid: id } }, body: { task_type: taskType }, signal }), { timeoutMs: 120_000, ...options }); export interface AccountRuntimeStatus { diff --git a/frontend/app/features/accounts/components/accountComponents.test.tsx b/frontend/app/features/accounts/components/accountComponents.test.tsx index 50f0fc8..ee803c1 100644 --- a/frontend/app/features/accounts/components/accountComponents.test.tsx +++ b/frontend/app/features/accounts/components/accountComponents.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { cleanup,fireEvent,render,screen } from '@testing-library/react'; import { afterEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail,AIReplySettings } from '../../../../shared/api-contract/accounts'; +import type { AccountDetail,AIReplySettings } from '../api'; import { AccountAISettingsModal } from './AccountAISettingsModal'; import { AccountCard } from './AccountCard'; import { AccountDeleteDialog } from './AccountDeleteDialog'; diff --git a/frontend/app/features/accounts/hooks.test.tsx b/frontend/app/features/accounts/hooks.test.tsx index 1acac42..1228ab4 100644 --- a/frontend/app/features/accounts/hooks.test.tsx +++ b/frontend/app/features/accounts/hooks.test.tsx @@ -2,7 +2,7 @@ import { renderHook,waitFor } from '@testing-library/react'; import { act } from 'react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail } from '../../../shared/api-contract/accounts'; +import type { AccountDetail } from './api'; import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api'; import { useAccountsData } from './hooks'; diff --git a/frontend/app/features/accounts/models.ts b/frontend/app/features/accounts/models.ts new file mode 100644 index 0000000..169ae7f --- /dev/null +++ b/frontend/app/features/accounts/models.ts @@ -0,0 +1,430 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountDetail { + /** 闲鱼账号稳定标识。 */ + id: string; + /** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */ + cookie_configured?: boolean; + /** 账号是否允许运行。 */ + enabled: boolean; + /** 是否自动确认订单。 */ + auto_confirm: boolean; + /** 用户为账号设置的备注。 */ + remark?: string; + /** 自动回复暂停时长,单位为分钟。 */ + pause_duration?: number; + /** 暂停结束时间的 Unix 秒。 */ + paused_until?: number; + /** 当前是否处于暂停状态。 */ + paused?: boolean; + // 登录信息 + /** 用于密码登录的闲鱼用户名。 */ + username?: string; + /** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */ + login_password_configured?: boolean; + /** 是否在密码登录时显示浏览器。 */ + show_browser?: boolean; + // Frontend helpers + /** 平台账号昵称。 */ + nickname?: string; + /** 平台账号头像地址。 */ + avatar_url?: string; + /** 资料刷新失败时的说明。 */ + profile_error?: string; + /** 当前账号运行状态。 */ + runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled'; + /** 当前运行状态的用户可见说明。 */ + runtime_message?: string; + /** 当前运行实例是否已连接。 */ + runtime_connected?: boolean; + /** 运行状态快照的更新时间。 */ + runtime_updated_at?: string; + // AI设置 + /** 是否启用账号 AI 回复。 */ + ai_enabled?: boolean; + /** 允许的最大折扣比例。 */ + max_discount_percent?: number; + /** 允许的最大折扣金额。 */ + max_discount_amount?: number; + /** 允许的最大砍价轮次。 */ + max_bargain_rounds?: number; + /** 账号自定义提示词。 */ + custom_prompts?: string; + // 账号级计划任务 + /** 是否启用自动评价。 */ + auto_rate_enabled?: boolean; + /** 自动评价使用的文案。 */ + rate_content?: string; + /** 是否启用每日擦亮。 */ + auto_polish_enabled?: boolean; + /** 每日擦亮执行时间。 */ + polish_time?: string; + /** 最近一次自动评价扫描时间。 */ + last_rate_scan_at?: number; + /** 最近一次擦亮日期。 */ + last_polish_date?: string; + /** 最近一次擦亮时间。 */ + last_polish_at?: number; +} + +/** 由当前 feature adapter 归一后的 AccountTaskSettings UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountTaskSettings { + /** 账号稳定标识。 */ + account_id: string; + /** 是否启用自动评价。 */ + auto_rate_enabled: boolean; + /** 自动评价文案。 */ + rate_content: string; + /** 是否启用每日擦亮。 */ + auto_polish_enabled: boolean; + /** 每日擦亮执行时间。 */ + polish_time: string; + /** 最近一次自动评价扫描时间。 */ + last_rate_scan_at?: number; + /** 最近一次擦亮日期。 */ + last_polish_date?: string; + /** 最近一次擦亮时间。 */ + last_polish_at?: number; +} + +/** 由当前 feature adapter 归一后的 AccountTaskSummary UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountTaskSummary { + /** 任务类型。 */ + task_type: 'auto_rate' | 'auto_polish'; + /** 发现的任务数量。 */ + found: number; + /** 成功处理的任务数量。 */ + success: number; + /** 处理失败的任务数量。 */ + failed: number; + /** 跳过的任务数量。 */ + skipped: number; + /** 批量处理结果说明。 */ + message?: string; +} + +/** 由当前 feature adapter 归一后的 AIReplySettings UI 模型;不直接暴露 HTTP DTO。 */ +export interface AIReplySettings { + /** 是否启用账号 AI 回复。 */ + ai_enabled: boolean; + /** 最大折扣比例。 */ + max_discount_percent: number; + /** 最大折扣金额。 */ + max_discount_amount?: number; + /** 最大砍价轮次。 */ + max_bargain_rounds: number; + /** 自定义提示词。 */ + custom_prompts: string; +} + +/** 由当前 feature adapter 归一后的 NotificationChannelType UI 模型;不直接暴露 HTTP DTO。 */ +export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email'; +/** 由当前 feature adapter 归一后的 NotificationEventType UI 模型;不直接暴露 HTTP DTO。 */ +export type NotificationEventType = + | 'account_offline' + | 'account_recovered' + | 'account_disabled' + | 'security_verification' + | 'token_renewal' + | 'delivery_result' + | 'system_error'; + +/** 由当前 feature adapter 归一后的 NotificationChannel UI 模型;不直接暴露 HTTP DTO。 */ +export interface NotificationChannel { + /** 通知渠道标识。 */ + id: string; + /** 通知渠道名称。 */ + name: string; + /** 通知渠道类型。 */ + type: NotificationChannelType; + /** 通知渠道配置。 */ + config: Record; + /** 渠道绑定的事件类型。 */ + event_types?: NotificationEventType[]; + /** 通知渠道是否启用。 */ + enabled: boolean; + /** 创建时间。 */ + created_at?: string; + /** 更新时间。 */ + updated_at?: string; +} + +/** 账号编辑器读取的通知渠道传输结果,仅用于适配为 NotificationChannel UI 模型。 */ +export interface NotificationChannelResponse { + /** 通知渠道数值标识。 */ id: number; + /** 用户可见渠道名称。 */ name: string; + /** 服务端保存的渠道类型。 */ type: string; + /** 兼容 JSON 文本的事件订阅列表。 */ event_types?: string; + /** 渠道是否参与投递。 */ enabled: boolean; +} + +/** 账号列表接口返回的非敏感具名 DTO。 */ +/** 由当前 feature adapter 归一后的 AccountSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountSummaryResponse { + /** 闲鱼账号稳定标识。 */ + id: string; + /** 数据库中是否存在账号记录。 */ + has_cookie: boolean; + /** 账号是否允许运行。 */ + enabled: boolean; + /** 是否自动确认订单。 */ + auto_confirm: boolean; + /** 账号备注。 */ + remark: string; + /** 自动回复暂停时长,单位为分钟。 */ + pause_duration: number; + /** 暂停结束 Unix 秒。 */ + paused_until: number; + /** 当前是否仍处于暂停状态。 */ + paused: boolean; + /** 密码登录用户名。 */ + username: string; + /** 是否允许密码登录显示浏览器;兼容旧服务端的 0/1 字符串值。 */ + show_browser: boolean | number | string; + /** 平台昵称缓存。 */ + nickname: string; + /** 平台头像地址。 */ + avatar_url: string; + /** 最近一次成功登录方式。 */ + login_method: string; + /** 最近一次成功登录时间。 */ + last_login_at: number; + /** 资料刷新错误说明。 */ + profile_error: string; + /** 账号级 AI 回复开关。 */ + ai_enabled: boolean; + /** 自动评价计划开关。 */ + auto_rate_enabled: boolean; + /** 自动评价文案。 */ + rate_content: string; + /** 自动擦亮计划开关。 */ + auto_polish_enabled: boolean; + /** 自动擦亮本地时间。 */ + polish_time: string; + /** 最近一次自动评价扫描时间。 */ + last_rate_scan_at: number; + /** 最近一次自动擦亮日期。 */ + last_polish_date: string; + /** 最近一次自动擦亮时间。 */ + last_polish_at: number; +} + +/** 账号设置变更接口的具名成功响应。 */ +/** 由当前 feature adapter 归一后的 CookieSettingsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface CookieSettingsResponse { + /** 表示设置是否保存成功。 */ + success: boolean; + /** 暂停结束 Unix 秒。 */ + paused_until: number; + /** 表示账号当前是否暂停。 */ + paused: boolean; +} + +/** 账号资料刷新接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 CookieProfileResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface CookieProfileResponse { + /** 表示资料刷新是否成功。 */ + success: boolean; + /** 账号稳定标识。 */ + id: string; + /** 平台账号昵称。 */ + nickname: string; + /** 平台账号头像地址。 */ + avatar_url: string; + /** 资料刷新错误说明。 */ + profile_error: string; +} + +/** 账号暂停时长查询接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 PauseDurationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface PauseDurationResponse { + /** 暂停时长,单位为分钟。 */ + pause_duration: number; + /** 暂停结束 Unix 秒。 */ + paused_until: number; + /** 表示账号当前是否暂停。 */ + paused: boolean; +} + +/** 账号 AI 回复设置接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 AIReplySettingsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AIReplySettingsResponse { + /** 账号稳定标识;默认配置响应可能省略。 */ + cookie_id?: string; + /** AI 回复是否启用。 */ + ai_enabled: boolean; + /** 最大折扣比例。 */ + max_discount_percent: number; + /** 最大折扣金额。 */ + max_discount_amount: number; + /** 最大砍价轮次。 */ + max_bargain_rounds: number; + /** 自定义提示词。 */ + custom_prompts: string; +} + +/** 通知绑定列表中的单条记录。 */ +/** 由当前 feature adapter 归一后的 NotificationBinding UI 模型;不直接暴露 HTTP DTO。 */ +export interface NotificationBinding { + /** 账号稳定标识,列表归一化后补充。 */ + cookie_id?: string; + /** 绑定记录主键。 */ + id?: number; + /** 通知渠道主键。 */ + channel_id: number; + /** 通知渠道名称。 */ + channel_name: string; + /** 绑定是否启用。 */ + enabled: boolean; +} + +/** 账号通知渠道绑定查询响应。 */ +/** 由当前 feature adapter 归一后的 AccountBindingsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountBindingsResponse { + /** 账号稳定标识。 */ + cookie_id: string; + /** 已绑定通知渠道主键列表。 */ + channel_ids: number[]; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} + +/** 账号任务设置响应。 */ +/** 由当前 feature adapter 归一后的 AccountTaskSettingsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountTaskSettingsResponse { + /** 账号稳定标识。 */ + account_id: string; + /** 是否启用自动评价。 */ + auto_rate_enabled: boolean; + /** 自动评价文案。 */ + rate_content: string; + /** 是否启用自动擦亮。 */ + auto_polish_enabled: boolean; + /** 自动擦亮本地时间。 */ + polish_time: string; + /** 最近一次评价扫描时间。 */ + last_rate_scan_at: number; + /** 最近一次擦亮日期。 */ + last_polish_date: string; + /** 最近一次擦亮时间。 */ + last_polish_at: number; +} + +/** 账号任务执行记录响应。 */ +/** 由当前 feature adapter 归一后的 AccountTaskRunResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountTaskRunResponse { + /** 任务执行记录主键。 */ + id: number; + /** 任务幂等键。 */ + run_key: string; + /** 账号稳定标识。 */ + account_id: string; + /** 任务类型。 */ + task_type: string; + /** 任务目标标识。 */ + target_id: string; + /** 任务业务日期。 */ + run_date: string; + /** 任务执行状态。 */ + status: string; + /** 任务成功数量。 */ + success_count: number; + /** 任务失败数量。 */ + failed_count: number; + /** 任务失败说明。 */ + error_message: string; + /** 下一次重试时间。 */ + next_retry_at: number; + /** 任务开始时间。 */ + started_at: number; + /** 任务完成时间。 */ + finished_at: number; +} + +/** 账号任务执行记录列表响应。 */ +/** 由当前 feature adapter 归一后的 AccountTaskRunsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountTaskRunsResponse { + /** 当前账号的任务执行记录。 */ + runs: AccountTaskRunResponse[]; +} + +/** 手动执行账号任务的统计响应。 */ +/** 由当前 feature adapter 归一后的 AccountTaskSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountTaskSummaryResponse extends AccountTaskSummary { + /** 任务结果说明。 */ + message?: string; +} + +/** 手动执行账号任务的成功响应。 */ +/** 由当前 feature adapter 归一后的 AccountTaskRunResponseEnvelope UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountTaskRunResponseEnvelope { + /** 任务请求是否成功完成。 */ + success: boolean; + /** 账号任务执行统计。 */ + summary: AccountTaskSummaryResponse; +} + +/** 扫码登录二维码生成响应。 */ +/** 由当前 feature adapter 归一后的 QRLoginGenerateResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface QRLoginGenerateResponse { + /** 二维码是否生成成功。 */ + success: boolean; + /** 扫码登录会话标识。 */ + session_id: string; + /** 二维码图片地址。 */ + qr_code_url: string; + /** 可选的提示文本。 */ + message?: string; +} + +/** 二维码登录状态响应。 */ +/** 由当前 feature adapter 归一后的 QRLoginStatusResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface QRLoginStatusResponse { + /** 当前二维码会话状态。 */ + status: string; + /** 风控验证页面截图地址,在人脸二维码不可用时作为展示兜底。 */ + verification_screenshot?: string; + /** 闲鱼人脸风控验证二维码地址,验证页面优先展示。 */ + face_qr_url?: string; + /** 扫码登录会话标识。 */ + session_id?: string; + /** 持久化后的本地账号标识。 */ + account_id?: string; + /** 是否新建了本地账号。 */ + is_new_account?: boolean; + /** 状态提示文本。 */ + message?: string; + /** 兼容上游可能扩展的非敏感状态字段。 */ + [key: string]: unknown; +} + +/** 二维码验证完成响应。 */ +/** 由当前 feature adapter 归一后的 QRLoginVerificationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface QRLoginVerificationResponse { + /** 验证结果是否成功。 */ + success: boolean; + /** 平台账号标识。 */ + unb?: string; + /** 持久化后的本地账号标识。 */ + account_id?: string; + /** 是否新建了本地账号。 */ + is_new_account?: boolean; +} diff --git a/frontend/app/features/accounts/pages/AccountList.test.tsx b/frontend/app/features/accounts/pages/AccountList.test.tsx index e592ba0..57ee23f 100644 --- a/frontend/app/features/accounts/pages/AccountList.test.tsx +++ b/frontend/app/features/accounts/pages/AccountList.test.tsx @@ -2,7 +2,7 @@ import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react'; import React from 'react'; import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail } from '../../../../shared/api-contract/accounts'; +import type { AccountDetail } from '../api'; // accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。 const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({ diff --git a/frontend/app/features/accounts/qrLogin.test.tsx b/frontend/app/features/accounts/qrLogin.test.tsx index db9c044..a0d1002 100644 --- a/frontend/app/features/accounts/qrLogin.test.tsx +++ b/frontend/app/features/accounts/qrLogin.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook } from '@testing-library/react'; import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail } from '../../../shared/api-contract/accounts'; +import type { AccountDetail } from './api'; // qrLoginMocks 保存二维码登录协调器测试使用的接口替身。 const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({ diff --git a/frontend/app/features/accounts/runtime.test.ts b/frontend/app/features/accounts/runtime.test.ts index 4a61032..f1ce5c0 100644 --- a/frontend/app/features/accounts/runtime.test.ts +++ b/frontend/app/features/accounts/runtime.test.ts @@ -1,5 +1,5 @@ import { describe,expect,test } from 'vitest'; -import type { AccountDetail } from '../../../shared/api-contract/accounts'; +import type { AccountDetail } from './api'; import { accountRuntimePresentation,isOlderStatus,mergeAccountRuntimeStatuses } from './runtime'; // account 创建运行状态测试使用的最小账号对象。 diff --git a/frontend/app/features/accounts/state.test.ts b/frontend/app/features/accounts/state.test.ts index b7c6d81..439c38b 100644 --- a/frontend/app/features/accounts/state.test.ts +++ b/frontend/app/features/accounts/state.test.ts @@ -1,5 +1,5 @@ import { expect,test } from 'vitest'; -import type { AccountDetail } from '../../../shared/api-contract/accounts'; +import type { AccountDetail } from './api'; import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, diff --git a/frontend/app/features/accounts/submoduleHooks.test.tsx b/frontend/app/features/accounts/submoduleHooks.test.tsx index ca02d58..574e5d0 100644 --- a/frontend/app/features/accounts/submoduleHooks.test.tsx +++ b/frontend/app/features/accounts/submoduleHooks.test.tsx @@ -2,7 +2,7 @@ import { act,renderHook } from '@testing-library/react'; import type { Dispatch,SetStateAction } from 'react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail,AIReplySettings } from '../../../shared/api-contract/accounts'; +import type { AccountDetail,AIReplySettings } from './api'; import { cancelPasswordLogin, checkPasswordLoginStatus, diff --git a/frontend/app/features/cards/api.ts b/frontend/app/features/cards/api.ts index 9810a02..6b6a0da 100644 --- a/frontend/app/features/cards/api.ts +++ b/frontend/app/features/cards/api.ts @@ -3,11 +3,11 @@ Card, CardAppendResponse, CardBatchResponse, MutationIDResponse,OperationResponse -} from '../../../shared/api-contract/cards'; +} from './models'; import { type RequestControlOptions } from '../../../shared/http/client'; -import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; +import { contractClient, contractMultipartBody, runContractRequest } from '../../../shared/api-contract/client'; import { collectionFrom } from '../../../shared/http/contract'; -export type * from '../../../shared/api-contract/cards'; +export type * from './models'; // Cards // normalizeCard 归一化卡密数据。 const normalizeCard = (item: any): Card => { @@ -24,9 +24,19 @@ const normalizeCard = (item: any): Card => { }; // cardPayload 卡密请求载荷,用于当前 API 处理流程。 -const cardPayload = (data: Partial): Record => ({ - ...data, +const cardPayload = (data: Partial) => ({ + name: data.name, + type: data.type, api_config: data.api_config ? JSON.stringify(data.api_config) : '', + text_content: data.text_content, + data_content: data.data_content, + image_url: data.image_url, + description: data.description, + enabled: data.enabled, + delay_seconds: data.delay_seconds, + is_multi_spec: data.is_multi_spec, + spec_name: data.spec_name, + spec_value: data.spec_value, }); // getCards 读取卡密列表。 @@ -40,12 +50,12 @@ export const getCards = async (options?: RequestControlOptions): Promise // createCard 创建卡密组。 export const createCard = async (data: Partial): Promise => { - return runContractRequest(/* signal 控制卡券创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards', { body: cardPayload(data) as never, signal })) as unknown as Promise; + return runContractRequest(/* signal 控制卡券创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards', { body: cardPayload(data), signal })); }; // updateCard 更新卡密组。 export const updateCard = async (cardId: string | number, data: Partial): Promise => { - return runContractRequest(/* signal 控制卡券更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/cards/{card_id}', { params: { path: { card_id: String(cardId) } }, body: cardPayload(data) as never, signal })); + return runContractRequest(/* signal 控制卡券更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/cards/{card_id}', { params: { path: { card_id: String(cardId) } }, body: cardPayload(data), signal })); }; // deleteCard 删除卡密组。 @@ -56,7 +66,7 @@ export const deleteCard = async (cardId: string | number): Promise => { // card 卡密详情,用于当前 API 处理流程。 - const card = await runContractRequest(/* signal 控制卡券详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/cards/{card_id}/details', { params: { path: { card_id: String(cardId) } }, signal })) as unknown as Card; + const card = await runContractRequest(/* signal 控制卡券详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/cards/{card_id}/details', { params: { path: { card_id: String(cardId) } }, signal })); return normalizeCard(card); }; @@ -70,10 +80,10 @@ export const batchCreateCards = async (file: File, options?: RequestControlOptio // 此处只收紧 TypeScript 响应契约。 const body = new FormData(); body.append('file', file); - return runContractRequest(/* signal 控制卡券批量上传的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/batch', { body: body as never, signal }), options) as Promise; + return runContractRequest(/* signal 控制卡券批量上传的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/batch', { body: contractMultipartBody(body), signal }), options); }; // 往 data 类型卡密组批量追加卡密号 export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise => { - return runContractRequest(/* signal 控制卡券追加数据请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/{card_id}/append-data', { params: { path: { card_id: String(cardId) } }, body: { content } as never, signal }), options) as Promise; + return runContractRequest(/* signal 控制卡券追加数据请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/{card_id}/append-data', { params: { path: { card_id: String(cardId) } }, body: { content }, signal }), options); }; diff --git a/frontend/app/features/cards/batchState.test.ts b/frontend/app/features/cards/batchState.test.ts index 483fc84..f87f6bc 100644 --- a/frontend/app/features/cards/batchState.test.ts +++ b/frontend/app/features/cards/batchState.test.ts @@ -1,5 +1,5 @@ import { expect,test } from 'vitest'; -import type { Card } from '../../../shared/api-contract/cards'; +import type { Card } from './api'; import { canSubmitAppend,filterCards,isCurrentCardRequest,previewAppendContent } from './batchState'; // cards 是卡密筛选测试使用的最小卡密组列表。 diff --git a/frontend/app/features/cards/cardActions.test.tsx b/frontend/app/features/cards/cardActions.test.tsx index a36dc2e..a9e67d6 100644 --- a/frontend/app/features/cards/cardActions.test.tsx +++ b/frontend/app/features/cards/cardActions.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook } from '@testing-library/react'; import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest'; -import type { Card } from '../../../shared/api-contract/cards'; +import type { Card } from './api'; import { useCardActions } from './cardActions'; // cardActionMocks 保存卡密动作 Hook 测试使用的 API 替身。 diff --git a/frontend/app/features/cards/hooks.test.tsx b/frontend/app/features/cards/hooks.test.tsx index b502f7f..d8b572e 100644 --- a/frontend/app/features/cards/hooks.test.tsx +++ b/frontend/app/features/cards/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook,waitFor } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { Card } from '../../../shared/api-contract/cards'; +import type { Card } from './api'; import { appendCardData,batchCreateCards,getCards } from './api'; import { useCardBatchActions,useCardsData } from './hooks'; diff --git a/frontend/app/features/cards/models.ts b/frontend/app/features/cards/models.ts new file mode 100644 index 0000000..f9e6063 --- /dev/null +++ b/frontend/app/features/cards/models.ts @@ -0,0 +1,105 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 Card UI 模型;不直接暴露 HTTP DTO。 */ +export interface Card { + /** 卡券组数值主键。 */ + id: number; + /** 卡券组名称。 */ + name: string; + /** 卡券组类型。 */ + type: 'api' | 'text' | 'data' | 'image'; + /** 卡券组说明。 */ + description?: string; + /** 卡券组是否启用。 */ + enabled: boolean; + // 文本类型 + text_content?: string; + // 批量数据类型 + data_content?: string; + // API 类型配置 + api_config?: { + /** API 卡券请求地址。 */ + url: string; + /** API 卡券请求方法。 */ + method: 'GET' | 'POST'; + /** API 请求超时时间。 */ + timeout?: number; + /** API 请求头 JSON。 */ + headers?: string; + /** API 请求参数 JSON。 */ + params?: string; + }; + // 图片类型 + /** 图片卡券地址。 */ + image_url?: string; + // 通用配置 + /** 卡券发送延迟秒数。 */ + delay_seconds?: number; + // 多规格配置 + /** 是否支持多规格。 */ + is_multi_spec?: boolean; + /** 规格名称。 */ + spec_name?: string; + /** 规格值。 */ + spec_value?: string; +} + +/** 卡券批量创建接口的逐行结果。 */ +/** 由当前 feature adapter 归一后的 CardBatchResult UI 模型;不直接暴露 HTTP DTO。 */ +export interface CardBatchResult { + /** 表格中的原始行号。 */ + row_no: number; + /** 当前行是否创建成功。 */ + success: boolean; + /** 新建卡券组主键。 */ + id?: number; + /** 卡券组名称。 */ + name: string; + /** 卡券类型。 */ + type?: string; + /** 当前行失败原因。 */ + error?: string; +} + +/** 卡券批量创建接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 CardBatchResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface CardBatchResponse { + /** 批量处理流程是否完成。 */ + success: boolean; + /** 解析出的总行数。 */ + total: number; + /** 创建成功行数。 */ + created: number; + /** 创建失败行数。 */ + failed: number; + /** 逐行处理结果。 */ + rows: CardBatchResult[]; +} + +/** 卡券追加数据接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 CardAppendResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface CardAppendResponse { + /** 追加操作是否完成。 */ + success: boolean; + /** 实际追加数量。 */ + added: number; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} diff --git a/frontend/app/features/cards/pages/CardList.test.tsx b/frontend/app/features/cards/pages/CardList.test.tsx index 44382db..447b2ad 100644 --- a/frontend/app/features/cards/pages/CardList.test.tsx +++ b/frontend/app/features/cards/pages/CardList.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react'; import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest'; -import type { Card } from '../../../../shared/api-contract/cards'; +import type { Card } from '../api'; // cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。 const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({ diff --git a/frontend/app/features/chat/api.ts b/frontend/app/features/chat/api.ts index 63356bf..67507b0 100644 --- a/frontend/app/features/chat/api.ts +++ b/frontend/app/features/chat/api.ts @@ -3,10 +3,10 @@ AccountDetail, ChatMessage, ChatSession, OperationResponse -} from '../../../shared/api-contract/chat'; +} from './models'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import { type RequestControlOptions } from '../../../shared/http/client'; -export type * from '../../../shared/api-contract/chat'; +export type * from './models'; import type { ChatReadReceipt } from './types'; /** ChatImageFormContract 描述图片发送 operation 的 multipart 字段,仅用于将原生 FormData 交给生成客户端。 */ diff --git a/frontend/app/features/chat/hooks.test.tsx b/frontend/app/features/chat/hooks.test.tsx index 7cec5a2..073a0b5 100644 --- a/frontend/app/features/chat/hooks.test.tsx +++ b/frontend/app/features/chat/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook,waitFor } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail,ChatMessage,ChatSession } from '../../../shared/api-contract/chat'; +import type { AccountDetail,ChatMessage,ChatSession } from './api'; import { getAccountDetails,getAccountRuntimeStatuses,getChatMessagePage,getChatSessionPage,markChatRead,sendChatImage,sendChatMessage } from './api'; import { useChat } from './hooks'; import { publishChatConnectionState,publishChatLiveMessage } from './liveEvents'; diff --git a/frontend/app/features/chat/models.ts b/frontend/app/features/chat/models.ts new file mode 100644 index 0000000..da82ab6 --- /dev/null +++ b/frontend/app/features/chat/models.ts @@ -0,0 +1,142 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountDetail { + /** 闲鱼账号稳定标识。 */ + id: string; + /** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */ + cookie_configured?: boolean; + /** 账号是否允许运行。 */ + enabled: boolean; + /** 是否自动确认订单。 */ + auto_confirm: boolean; + /** 用户为账号设置的备注。 */ + remark?: string; + /** 自动回复暂停时长,单位为分钟。 */ + pause_duration?: number; + /** 暂停结束时间的 Unix 秒。 */ + paused_until?: number; + /** 当前是否处于暂停状态。 */ + paused?: boolean; + // 登录信息 + /** 用于密码登录的闲鱼用户名。 */ + username?: string; + /** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */ + login_password_configured?: boolean; + /** 是否在密码登录时显示浏览器。 */ + show_browser?: boolean; + // Frontend helpers + /** 平台账号昵称。 */ + nickname?: string; + /** 平台账号头像地址。 */ + avatar_url?: string; + /** 资料刷新失败时的说明。 */ + profile_error?: string; + /** 当前账号运行状态。 */ + runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled'; + /** 当前运行状态的用户可见说明。 */ + runtime_message?: string; + /** 当前运行实例是否已连接。 */ + runtime_connected?: boolean; + /** 运行状态快照的更新时间。 */ + runtime_updated_at?: string; + // AI设置 + /** 是否启用账号 AI 回复。 */ + ai_enabled?: boolean; + /** 允许的最大折扣比例。 */ + max_discount_percent?: number; + /** 允许的最大折扣金额。 */ + max_discount_amount?: number; + /** 允许的最大砍价轮次。 */ + max_bargain_rounds?: number; + /** 账号自定义提示词。 */ + custom_prompts?: string; + // 账号级计划任务 + /** 是否启用自动评价。 */ + auto_rate_enabled?: boolean; + /** 自动评价使用的文案。 */ + rate_content?: string; + /** 是否启用每日擦亮。 */ + auto_polish_enabled?: boolean; + /** 每日擦亮执行时间。 */ + polish_time?: string; + /** 最近一次自动评价扫描时间。 */ + last_rate_scan_at?: number; + /** 最近一次擦亮日期。 */ + last_polish_date?: string; + /** 最近一次擦亮时间。 */ + last_polish_at?: number; +} + +/** 由当前 feature adapter 归一后的 ChatSession UI 模型;不直接暴露 HTTP DTO。 */ +export interface ChatSession { + /** 账号稳定标识。 */ + account_id: string; + /** 会话稳定标识。 */ + chat_id: string; + /** 买家平台标识。 */ + buyer_id: string; + /** 买家昵称。 */ + buyer_name: string; + /** 买家头像地址。 */ + buyer_avatar_url?: string; + /** 会话关联商品标识。 */ + item_id?: string; + /** 会话关联商品标题。 */ + item_title?: string; + /** 最近一条消息内容。 */ + last_message: string; + /** 最近一条消息的 Unix 秒时间戳。 */ + last_message_at: number; + /** 未读消息数量。 */ + unread_count: number; +} + +/** 由当前 feature adapter 归一后的 ChatMessage UI 模型;不直接暴露 HTTP DTO。 */ +export interface ChatMessage { + /** 消息数据库主键。 */ + id: number; + /** 消息所属账号标识。 */ + account_id: string; + /** 消息所属会话标识。 */ + chat_id: string; + /** 平台消息去重键。 */ + message_key: string; + /** 消息方向。 */ + direction: 'incoming' | 'outgoing'; + /** 发送者平台标识。 */ + sender_id: string; + /** 发送者名称。 */ + sender_name: string; + /** 消息类型,system 表示平台通知或交易卡片。 */ + message_type: 'text' | 'image' | 'video' | 'system'; + /** 消息正文或媒体地址。 */ + content: string; + /** 消息发送状态。 */ + status: 'received' | 'sending' | 'sent' | 'failed'; + /** 平台已读状态;旧消息可能没有该字段。 */ + read_status?: number; + /** 平台确认已读的 Unix 秒时间戳;未确认时省略。 */ + read_at?: number; + /** 消息发送时间的 Unix 秒。 */ + sent_at: number; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} diff --git a/frontend/app/features/chat/state.test.ts b/frontend/app/features/chat/state.test.ts index 0dfe9a4..97880df 100644 --- a/frontend/app/features/chat/state.test.ts +++ b/frontend/app/features/chat/state.test.ts @@ -1,5 +1,5 @@ import { expect,test } from 'vitest'; -import type { ChatMessage,ChatSession } from '../../../shared/api-contract/chat'; +import type { ChatMessage,ChatSession } from './api'; import { collectChatReadReceipts,filterChatSessions,formatClock,isChatAbortError,isCurrentChatRequest,markOutgoingMessagesReadByIncoming,mergeLiveMessage,mergeOlderMessages,messageTime,unreadBadgeClassName,unreadBadgeLabel } from './state'; // sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。 diff --git a/frontend/app/features/chat/titleNotification.test.tsx b/frontend/app/features/chat/titleNotification.test.tsx index b3924f7..ed2856d 100644 --- a/frontend/app/features/chat/titleNotification.test.tsx +++ b/frontend/app/features/chat/titleNotification.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook } from '@testing-library/react'; import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest'; -import type { ChatMessage } from '../../../shared/api-contract/chat'; +import type { ChatMessage } from './api'; import { getAccountDetails,getChatSessionPage } from './api'; import { publishChatUnreadStatus } from './liveEvents'; import { formatChatNewMessageTitle,useChatTitleNotification,useChatTitleNotifier } from './titleNotification'; diff --git a/frontend/app/features/dashboard/api.ts b/frontend/app/features/dashboard/api.ts index 79accda..a0bf199 100644 --- a/frontend/app/features/dashboard/api.ts +++ b/frontend/app/features/dashboard/api.ts @@ -1,9 +1,9 @@ import { formatLocalDate } from '../../../dateRange'; -import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from '../../../shared/api-contract/admin'; +import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from './models'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import { type RequestControlOptions } from '../../../shared/http/client'; import { collectionFrom, objectFrom } from '../../../shared/http/contract'; -export type * from '../../../shared/api-contract/admin'; +export type * from './models'; /** 仪表盘订单明细接口转换后的分页结果。 */ export interface ValidOrdersResult { diff --git a/frontend/app/features/dashboard/hooks.test.tsx b/frontend/app/features/dashboard/hooks.test.tsx index db421fe..7dc24a0 100644 --- a/frontend/app/features/dashboard/hooks.test.tsx +++ b/frontend/app/features/dashboard/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook,waitFor } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { DashboardStats,Item,OrderAnalyticsResponse } from '../../../shared/api-contract/admin'; +import type { DashboardStats,Item,OrderAnalyticsResponse } from './api'; import { getDashboardStats,getItems,getOrderAnalytics,getValidOrders } from './api'; import type { UseDashboardOptions } from './hooks'; import { useDashboard } from './hooks'; diff --git a/frontend/app/features/dashboard/models.ts b/frontend/app/features/dashboard/models.ts new file mode 100644 index 0000000..1c14cb4 --- /dev/null +++ b/frontend/app/features/dashboard/models.ts @@ -0,0 +1,270 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 OrderStatus UI 模型;不直接暴露 HTTP DTO。 */ +export type OrderStatus = + | 'processing' + | 'pending_ship' + | 'shipped' + | 'completed' + | 'cancelled' + | 'refunding' + | 'unknown'; + +/** 由当前 feature adapter 归一后的 Order UI 模型;不直接暴露 HTTP DTO。 */ +export interface Order { + /** 订单本地数据库主键。 */ + id: string; + /** 平台订单标识。 */ + order_id: string; + /** 订单所属账号标识。 */ + cookie_id: string; + /** 订单关联商品标识。 */ + item_id: string; + /** 商品标题。 */ + item_title?: string; + /** 商品图片地址。 */ + item_image?: string; + /** 商品价格文本。 */ + item_price?: string; + /** 买家平台标识。 */ + buyer_id: string; + /** 购买数量。 */ + quantity: number; + /** 订单金额文本。 */ + amount: string; + /** 前端归一化后的订单状态。 */ + status: OrderStatus; + /** 服务端原始订单状态。 */ + order_status?: OrderStatus; + /** 收货人姓名。 */ + receiver_name?: string; + /** 收货人电话。 */ + receiver_phone?: string; + /** 收货地址。 */ + receiver_address?: string; + /** 订单创建时间。 */ + created_at?: string; + /** 订单更新时间。 */ + updated_at?: string; +} + +/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */ +export interface Item { + /** 本地商品数据库主键。 */ + id: string | number; + /** 商品所属账号标识。 */ + cookie_id: string; + /** 平台商品标识。 */ + item_id: string; + /** 商品标题。 */ + item_title?: string; + /** 商品描述。 */ + item_description?: string; + /** 商品价格文本。 */ + item_price?: string; + /** 商品主图地址。 */ + item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes + /** 商品分类标识。 */ + item_category?: string; + /** 商品详情原始 JSON。 */ + item_detail?: string; + /** 是否启用多规格。 */ + is_multi_spec?: number | boolean; + /** 是否按数量发货。 */ + multi_quantity_delivery?: number | boolean; + /** 是否启用多数量发货兼容字段。 */ + is_multi_qty_ship?: number | boolean; +} + +/** 仪表盘兼容历史 items 包装时使用的最小响应模型。 */ +export interface ItemListEnvelope { + /** 历史包装中的商品数组。 */ items?: Item[]; +} + +/** 由当前 feature adapter 归一后的 AdminStats UI 模型;不直接暴露 HTTP DTO。 */ +export interface AdminStats { + /** 用户总数。 */ + total_users: number; + /** 账号总数。 */ + total_cookies: number; + /** 启用账号数。 */ + active_cookies: number; + /** 卡券组总数。 */ + total_cards: number; + /** 关键词规则总数。 */ + total_keywords: number; + /** 订单总数。 */ + total_orders: number; +} + +/** 由当前 feature adapter 归一后的 DashboardStats UI 模型;不直接暴露 HTTP DTO。 */ +export interface DashboardStats { + /** 账号总数。 */ + total_cookies: number; + /** 启用账号数。 */ + active_cookies: number; + /** 卡券组总数。 */ + total_cards: number; + /** 关键词规则总数。 */ + total_keywords: number; + /** 订单总数。 */ + total_orders: number; + /** 可用卡券库存量。 */ + available_card_stock: number; +} + +/** 由当前 feature adapter 归一后的 OrderAnalytics UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderAnalytics { + /** 收入汇总。 */ + revenue_stats: { + /** 总收入金额。 */ + total_amount: number; + /** 总订单数。 */ + total_orders: number; + }; + /** 按日期聚合的订单统计。 */ + daily_stats: Array<{ + /** 统计日期。 */ + date: string; + /** 当日订单金额。 */ + amount: number; + /** 当日订单数量。 */ + order_count: number; + }>; + /** 按商品聚合的订单统计。 */ + item_stats?: Array<{ + /** 商品标识。 */ + item_id: string; + /** 商品订单数。 */ + order_count: number; + /** 商品订单总金额。 */ + total_amount: number; + /** 商品订单平均金额。 */ + avg_amount: number; + }>; +} + +/** 管理员全局统计响应。 */ +/** 由当前 feature adapter 归一后的 AdminStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AdminStatsResponse extends AdminStats {} + +/** 当前用户数据概览响应。 */ +/** 由当前 feature adapter 归一后的 DashboardStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface DashboardStatsResponse extends DashboardStats {} + +/** 订单收益统计响应。 */ +/** 由当前 feature adapter 归一后的 AnalyticsRevenueStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AnalyticsRevenueStatsResponse { + /** 统计范围内的订单数。 */ + total_orders: number; + /** 统计范围内的订单总金额。 */ + total_amount: number; + /** 订单平均金额。 */ + avg_amount: number; + /** 买家数量。 */ + unique_buyers: number; + /** 商品数量。 */ + unique_items: number; +} + +/** 按日期聚合的订单统计响应。 */ +/** 由当前 feature adapter 归一后的 AnalyticsDailyStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AnalyticsDailyStatsResponse { + /** 用户本地日期。 */ + date: string; + /** 当天订单数。 */ + order_count: number; + /** 当天订单金额。 */ + amount: number; +} + +/** 按订单状态聚合的统计响应。 */ +/** 由当前 feature adapter 归一后的 AnalyticsStatusStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AnalyticsStatusStatsResponse { + /** 归一化后的订单状态。 */ + status: string; + /** 该状态订单数。 */ + count: number; + /** 该状态订单金额。 */ + amount: number; +} + +/** 按收货城市聚合的统计响应。 */ +/** 由当前 feature adapter 归一后的 AnalyticsCityStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AnalyticsCityStatsResponse { + /** 收货城市。 */ + city: string; + /** 该城市订单数。 */ + order_count: number; + /** 该城市订单金额。 */ + total_amount: number; +} + +/** 按商品聚合的统计响应。 */ +/** 由当前 feature adapter 归一后的 AnalyticsItemStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AnalyticsItemStatsResponse { + /** 商品平台标识。 */ + item_id: string; + /** 该商品订单数。 */ + order_count: number; + /** 该商品订单金额。 */ + total_amount: number; + /** 该商品订单平均金额。 */ + avg_amount: number; +} + +/** 订单分析接口响应。 */ +/** 由当前 feature adapter 归一后的 OrderAnalyticsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderAnalyticsResponse { + /** 收益统计。 */ + revenue_stats: AnalyticsRevenueStatsResponse; + /** 按日统计。 */ + daily_stats: AnalyticsDailyStatsResponse[]; + /** 按状态统计。 */ + status_stats: AnalyticsStatusStatsResponse[]; + /** 按城市统计。 */ + city_stats: AnalyticsCityStatsResponse[]; + /** 按商品统计。 */ + item_stats: AnalyticsItemStatsResponse[]; +} + +/** 有效订单明细响应。 */ +/** 由当前 feature adapter 归一后的 ValidOrderResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ValidOrderResponse { + /** 平台订单标识。 */ + order_id: string; + /** 商品平台标识。 */ + item_id: string; + /** 买家平台标识。 */ + buyer_id: string; + /** 商品标题。 */ + item_title: string; + /** 商品图片地址。 */ + item_image: string; + /** 订单数量文本。 */ + quantity: string; + /** 订单金额文本。 */ + amount: string; + /** 兼容保留的订单状态。 */ + order_status: string; + /** 归一化后的订单状态。 */ + status: string; + /** 订单所属账号标识。 */ + cookie_id: string; + /** 订单创建时间。 */ + created_at: string; +} + +/** 有效订单分页响应。 */ +/** 由当前 feature adapter 归一后的 ValidOrdersResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ValidOrdersResponse { + /** 当前页有效订单。 */ + orders: ValidOrderResponse[]; + /** 符合条件的订单总数。 */ + total: number; + /** 当前页码。 */ + page: number; + /** 当前页大小。 */ + page_size: number; + /** 是否还有未返回的订单。 */ + truncated: boolean; +} diff --git a/frontend/app/features/dashboard/state.test.ts b/frontend/app/features/dashboard/state.test.ts index b7f9a77..a7697b2 100644 --- a/frontend/app/features/dashboard/state.test.ts +++ b/frontend/app/features/dashboard/state.test.ts @@ -1,5 +1,5 @@ import { expect,test } from 'vitest'; -import type { OrderAnalytics } from '../../../shared/api-contract/admin'; +import type { OrderAnalytics } from './api'; import { buildCategoryData,buildChartData,buildItemNameMap,buildProductSalesData,buildSourceData,getMaxProductSales,getRangeLabel,getTrendPercent,isCurrentDashboardRequest } from './state'; // analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。 diff --git a/frontend/app/features/items/api.ts b/frontend/app/features/items/api.ts index a5f357b..3272de9 100644 --- a/frontend/app/features/items/api.ts +++ b/frontend/app/features/items/api.ts @@ -1,4 +1,4 @@ -import type { PublishLocation } from '../../../shared/api-contract/items'; +import type { PublishLocation } from './models'; import { AccountDetail, BatchCancelResponse, @@ -11,11 +11,11 @@ ItemPublishBatchResponse, ItemPublishResponse,ItemSyncResponse, OperationResponse, ShippingRule -} from '../../../shared/api-contract/items'; +} from './models'; import { ApiError, type RequestControlOptions } from '../../../shared/http/client'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import { collectionFrom } from '../../../shared/http/contract'; -export type * from '../../../shared/api-contract/items'; +export type * from './models'; import { getPublishLocations as queryPublishLocations,type PublishLocationRequestOptions } from './amapLocation'; /** 商品账号筛选器读取非敏感账号摘要。 */ @@ -26,7 +26,7 @@ export const getShippingRules = async (options?: RequestControlOptions): Promise // getPublishLocations 通过 feature API 边界读取地点,并把取消/超时控制传入地图服务。 export const getPublishLocations = (longitude: number, latitude: number, options?: PublishLocationRequestOptions): Promise => queryPublishLocations(longitude, latitude, options); -export type { PublishLocation } from '../../../shared/api-contract/items'; +export type { PublishLocation } from './models'; // itemErrorMessage 将统一 HTTP 错误码归一为商品 feature 可执行的用户提示。 export const itemErrorMessage = (error: unknown, fallback: string): string => { @@ -197,5 +197,9 @@ export const updateItem = async (cookieId: string, itemId: string, data: Partial return runContractRequest(/* signal 控制商品更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: cookieId, item_id: itemId } }, body: data as never, signal })); } -/** 读取指定账号与商品的详情,用于编辑器恢复表单。 */ -export const getItemDetail = async (accountID: string, itemID: string): Promise => runContractRequest(/* signal 控制商品详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: accountID, item_id: itemID } }, signal })) as unknown as Promise; +/** 读取指定账号与商品的详情,用于编辑器恢复表单,并将生成传输 DTO 保持在 feature adapter 边界。 */ +export const getItemDetail = async (accountID: string, itemID: string): Promise => { + // response 保存已由 OpenAPI 路径类型约束的商品详情传输响应。 + const response = await runContractRequest(/* signal 控制商品详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: accountID, item_id: itemID } }, signal })); + return response; +}; diff --git a/frontend/app/features/items/hooks.test.tsx b/frontend/app/features/items/hooks.test.tsx index b3781d6..f5ac347 100644 --- a/frontend/app/features/items/hooks.test.tsx +++ b/frontend/app/features/items/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from '../../../shared/api-contract/items'; +import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from './api'; import { cancelItemPublishBatch, deleteItemPublishBatch, diff --git a/frontend/app/features/items/itemActions.test.tsx b/frontend/app/features/items/itemActions.test.tsx index f310673..6af5745 100644 --- a/frontend/app/features/items/itemActions.test.tsx +++ b/frontend/app/features/items/itemActions.test.tsx @@ -2,7 +2,7 @@ import { act,renderHook } from '@testing-library/react'; import { useState } from 'react'; import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest'; -import type { Item } from '../../../shared/api-contract/items'; +import type { Item } from './api'; import { createItem,deleteItem,getPublishLocations,publishItem,syncItemsFromAccount,updateItem } from './api'; import { useItemActions,type ItemActionsOptions } from './itemActions'; diff --git a/frontend/app/features/items/models.ts b/frontend/app/features/items/models.ts new file mode 100644 index 0000000..0f9817e --- /dev/null +++ b/frontend/app/features/items/models.ts @@ -0,0 +1,457 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 PublishLocation UI 模型;不直接暴露 HTTP DTO。 */ +export interface PublishLocation { + /** 行政区划展示名称。 */ + area: string; + /** 城市展示名称。 */ + city: string; + /** 平台使用的行政区划标识。 */ + division_id: string; + /** 地点经度。 */ + longitude: number; + /** 地点纬度。 */ + latitude: number; + /** 平台兴趣点标识。 */ + poi_id: string; + /** 平台兴趣点展示名称。 */ + poi_name: string; + /** 省份展示名称。 */ + province: string; +} + +/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountDetail { + /** 闲鱼账号稳定标识。 */ + id: string; + /** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */ + cookie_configured?: boolean; + /** 账号是否允许运行。 */ + enabled: boolean; + /** 是否自动确认订单。 */ + auto_confirm: boolean; + /** 用户为账号设置的备注。 */ + remark?: string; + /** 自动回复暂停时长,单位为分钟。 */ + pause_duration?: number; + /** 暂停结束时间的 Unix 秒。 */ + paused_until?: number; + /** 当前是否处于暂停状态。 */ + paused?: boolean; + // 登录信息 + /** 用于密码登录的闲鱼用户名。 */ + username?: string; + /** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */ + login_password_configured?: boolean; + /** 是否在密码登录时显示浏览器。 */ + show_browser?: boolean; + // Frontend helpers + /** 平台账号昵称。 */ + nickname?: string; + /** 平台账号头像地址。 */ + avatar_url?: string; + /** 资料刷新失败时的说明。 */ + profile_error?: string; + /** 当前账号运行状态。 */ + runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled'; + /** 当前运行状态的用户可见说明。 */ + runtime_message?: string; + /** 当前运行实例是否已连接。 */ + runtime_connected?: boolean; + /** 运行状态快照的更新时间。 */ + runtime_updated_at?: string; + // AI设置 + /** 是否启用账号 AI 回复。 */ + ai_enabled?: boolean; + /** 允许的最大折扣比例。 */ + max_discount_percent?: number; + /** 允许的最大折扣金额。 */ + max_discount_amount?: number; + /** 允许的最大砍价轮次。 */ + max_bargain_rounds?: number; + /** 账号自定义提示词。 */ + custom_prompts?: string; + // 账号级计划任务 + /** 是否启用自动评价。 */ + auto_rate_enabled?: boolean; + /** 自动评价使用的文案。 */ + rate_content?: string; + /** 是否启用每日擦亮。 */ + auto_polish_enabled?: boolean; + /** 每日擦亮执行时间。 */ + polish_time?: string; + /** 最近一次自动评价扫描时间。 */ + last_rate_scan_at?: number; + /** 最近一次擦亮日期。 */ + last_polish_date?: string; + /** 最近一次擦亮时间。 */ + last_polish_at?: number; +} + +/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */ +export interface Item { + /** 本地商品数据库主键。 */ + id: string | number; + /** 商品所属账号标识。 */ + cookie_id: string; + /** 平台商品标识。 */ + item_id: string; + /** 商品标题。 */ + item_title?: string; + /** 商品描述。 */ + item_description?: string; + /** 商品价格文本。 */ + item_price?: string; + /** 商品主图地址。 */ + item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes + /** 商品分类标识。 */ + item_category?: string; + /** 商品详情原始 JSON。 */ + item_detail?: string; + /** 是否启用多规格。 */ + is_multi_spec?: number | boolean; + /** 是否按数量发货。 */ + multi_quantity_delivery?: number | boolean; + /** 是否启用多数量发货兼容字段。 */ + is_multi_qty_ship?: number | boolean; +} + +/** 由当前 feature adapter 归一后的 AutomationTriggerType UI 模型;不直接暴露 HTTP DTO。 */ +export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout'; +/** 由当前 feature adapter 归一后的 AutomationActionType UI 模型;不直接暴露 HTTP DTO。 */ +export type AutomationActionType = 'confirm_shipment' | 'send_card' | 'send_text'; + +// Rules +/** 由当前 feature adapter 归一后的 ShippingRule UI 模型;不直接暴露 HTTP DTO。 */ +export interface ShippingRule { + /** 规则标识。 */ + id: string; + /** 规则名称。 */ + name: string; + /** 规则触发类型。 */ + trigger_type: AutomationTriggerType; + /** 规则匹配关键词。 */ + item_keyword: string; // Legacy UI helper + /** 规则限定的账号标识。 */ + cookie_id?: string; + /** 规则限定的商品标识。 */ + item_id?: string; + /** 规则限定的商品标题。 */ + item_title?: string; + /** 首个发卡动作使用的卡券组 ID。 */ + card_group_id: number; // First send_card action card id + /** 首个发卡动作使用的卡券组名称。 */ + card_group_name?: string; // UI helper + /** 规则优先级。 */ + priority: number; + /** 规则是否启用。 */ + enabled: boolean; + /** 规则原始配置 JSON。 */ + config_json?: string; + /** 规则动作列表。 */ + actions: AutomationAction[]; + /** 规则规格变体列表。 */ + variants: ShippingVariant[]; +} + +/** 由当前 feature adapter 归一后的 AutomationAction UI 模型;不直接暴露 HTTP DTO。 */ +export interface AutomationAction { + /** 动作标识。 */ + id?: string; + /** 动作类型。 */ + action_type: AutomationActionType; + /** 动作使用的卡券组 ID。 */ + card_id?: number; + /** 动作使用的卡券组名称。 */ + card_name?: string; + /** 本次发放数量。 */ + delivery_count?: number; + /** 文本消息模板。 */ + message_template?: string; + /** 动作延迟秒数。 */ + delay_seconds?: number; + /** 动作原始配置 JSON。 */ + config_json?: string; + /** 动作是否启用。 */ + enabled: boolean; + /** 动作排序序号。 */ + sort_order?: number; +} + +/** 由当前 feature adapter 归一后的 ShippingVariant UI 模型;不直接暴露 HTTP DTO。 */ +export interface ShippingVariant { + /** 规格变体标识。 */ + id?: string; + /** 规格名称。 */ + spec_name: string; + /** 规格值。 */ + spec_value: string; + /** 变体使用的卡券组 ID。 */ + card_id: number; + /** 变体使用的卡券组名称。 */ + card_name?: string; + /** 卡券类型。 */ + card_type?: 'api' | 'text' | 'data' | 'image'; + /** 变体发放数量。 */ + delivery_count: number; + /** 变体是否启用。 */ + enabled: boolean; + /** 是否覆盖动作级延迟。 */ + delay_override?: boolean; + /** 变体延迟秒数。 */ + delay_seconds?: number; + /** 变体原始配置 JSON。 */ + config_json?: string; +} + +/** 单个本地商品详情接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 ItemDetailResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemDetailResponse { + /** 商品所属账号标识。 */ + cookie_id: string; + /** 平台商品标识。 */ + item_id: string; + /** 商品标题。 */ + item_title: string; + /** 商品描述。 */ + item_description: string; + /** 商品分类标识。 */ + item_category: string; + /** 商品价格文本。 */ + item_price: string; + /** 商品详情原始 JSON。 */ + item_detail: string; + /** 是否有多规格。 */ + is_multi_spec: boolean; + /** 是否按数量发货。 */ + multi_quantity_delivery: boolean; +} + +/** 商品发布接口的具名成功响应。 */ +/** 由当前 feature adapter 归一后的 ItemPublishResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemPublishResponse { + /** 表示商品是否发布成功。 */ + success: boolean; + /** 发布结果说明。 */ + message: string; + /** 新商品的平台标识。 */ + item_id: string; + /** 新商品的平台详情地址。 */ + item_url: string; + /** 新商品主图地址。 */ + item_image: string; + /** 新商品标题。 */ + item_title: string; + /** 新商品价格文本。 */ + item_price: string; + /** 新商品库存数量。 */ + quantity: number; + /** 新商品分类标识。 */ + category_id: string; + /** 新商品分类名称。 */ + category_name: string; +} + +/** 商品全集同步接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 ItemSyncResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemSyncResponse { + /** 表示同步是否完成。 */ + success: boolean; + /** 同步结果说明。 */ + message: string; + /** 平台返回的商品总数。 */ + total_count: number; + /** 平台商品总页数。 */ + total_pages: number; + /** 本地保存的商品数量。 */ + saved_count: number; + /** 本地删除标记的商品数量。 */ + deleted_count: number; +} + +/** 商品分页同步接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 ItemPageSyncResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemPageSyncResponse { + /** 表示同步是否完成。 */ + success: boolean; + /** 同步结果说明。 */ + message: string; + /** 当前同步页码。 */ + page_number: number; + /** 当前同步页大小。 */ + page_size: number; + /** 当前页商品数量。 */ + current_count: number; + /** 本地保存的商品数量。 */ + saved_count: number; +} + +/** 商品类目推荐接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 CategoryRecommendationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface CategoryRecommendationResponse { + /** 类目推荐是否成功。 */ + success: boolean; + /** 推荐商品类目。 */ + category: { + /** 平台类目主键。 */ + cat_id: string; + /** 平台类目名称。 */ + cat_name: string; + /** 频道类目主键。 */ + channel_cat_id: string; + /** 淘宝类目主键。 */ + tb_cat_id?: string; + }; +} + +/** 商品批量发布预检逐行结果。 */ +/** 由当前 feature adapter 归一后的 ItemPublishBatchPreviewRow UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemPublishBatchPreviewRow { + /** 上传表格行号。 */ + row_no: number; + /** 当前行是否通过预检。 */ + valid: boolean; + /** 当前行校验错误列表。 */ + errors?: string[]; + /** 发布目标账号标识。 */ + cookie_id: string; + /** 商品标题。 */ + title: string; + /** 商品价格文本。 */ + price: string; + /** 商品库存数量。 */ + quantity: number; + /** 商品图片引用列表。 */ + images: string[]; + /** 商品发布类目。 */ + category: CategoryRecommendationResponse['category']; + /** 发布后自动化配置。 */ + automation?: Record; +} + +/** 商品批量发布预检响应。 */ +/** 由当前 feature adapter 归一后的 ItemPublishBatchPreviewResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemPublishBatchPreviewResponse { + /** 预检流程是否完成。 */ + success: boolean; + /** 后续启动发布使用的预检批次标识。 */ + preview_id: string; + /** 预检总行数。 */ + total: number; + /** 通过预检行数。 */ + valid: number; + /** 未通过预检行数。 */ + invalid: number; + /** 逐行预检结果。 */ + rows: ItemPublishBatchPreviewRow[]; +} + +/** 商品批量发布任务启动或重试响应。 */ +/** 由当前 feature adapter 归一后的 BatchIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface BatchIDResponse { + /** 任务操作是否完成。 */ + success: boolean; + /** 商品批量任务标识。 */ + batch_id: string; +} + +/** 商品批量发布任务取消响应。 */ +/** 由当前 feature adapter 归一后的 BatchCancelResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface BatchCancelResponse { + /** 取消请求是否完成。 */ + success: boolean; + /** 取消后的任务状态。 */ + status: string; +} + +/** 商品批量发布任务逐行详情。 */ +/** 由当前 feature adapter 归一后的 ItemPublishBatchRowResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemPublishBatchRowResponse { + /** 明细行主键。 */ + id: number; + /** 导入表格行号。 */ + row_no: number; + /** 发布目标账号标识。 */ + cookie_id: string; + /** 商品标题。 */ + title: string; + /** 商品价格文本。 */ + price: string; + /** 商品库存数量。 */ + quantity: number; + /** 商品图片引用列表。 */ + images: string[]; + /** 商品发布类目。 */ + category: CategoryRecommendationResponse['category']; + /** 发布后自动化配置。 */ + automation: Record; + /** 明细行状态。 */ + status: string; + /** 发布成功后的平台商品标识。 */ + item_id: string; + /** 发布成功后的商品地址。 */ + item_url: string; + /** 明细行失败原因。 */ + error_message: string; + /** 明细行失败类型。 */ + failure_kind: string; +} + +/** 商品批量发布任务详情响应。 */ +/** 由当前 feature adapter 归一后的 ItemPublishBatchResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemPublishBatchResponse { + /** 批量任务标识。 */ + id: string; + /** 批量任务状态。 */ + status: string; + /** 原始上传文件名。 */ + filename: string; + /** 明细行总数。 */ + total: number; + /** 成功发布数量。 */ + success: number; + /** 失败数量。 */ + failed: number; + /** 待处理数量。 */ + pending: number; + /** 运行中数量。 */ + running: number; + /** 可重试数量。 */ + retryable: number; + /** 明细行结果。 */ + rows: ItemPublishBatchRowResponse[]; + /** 批次统一发货地。 */ + location?: Record; + /** 最终商品发布之间的最小间隔秒数。 */ + publish_interval_seconds?: number; + /** 创建时间。 */ + created_at: string; + /** 更新时间。 */ + updated_at: string; +} + +/** 商品批量发布任务列表响应。 */ +/** 由当前 feature adapter 归一后的 ItemPublishBatchListResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemPublishBatchListResponse { + /** 当前用户的批量任务列表。 */ + batches: ItemPublishBatchResponse[]; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} diff --git a/frontend/app/features/notifications/api.ts b/frontend/app/features/notifications/api.ts index b50c21e..eea7647 100644 --- a/frontend/app/features/notifications/api.ts +++ b/frontend/app/features/notifications/api.ts @@ -1,7 +1,7 @@ -import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from '../../../shared/api-contract/notifications'; +import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from './models'; import { type RequestControlOptions } from '../../../shared/http/client'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; -export type * from '../../../shared/api-contract/notifications'; +export type * from './models'; /** 通知渠道写入时使用的具名请求 DTO。 */ export interface NotificationChannelRequest { @@ -50,22 +50,24 @@ const toNotificationChannel = (channel: NotificationChannelResponse): Notificati /** 获取全部通知渠道并转换为编辑器模型。 */ export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** 操作是否完成。 */ success: boolean; /** 渠道列表。 */ data: NotificationChannel[] }> => { // response 是渠道列表的原始传输响应。 - const response = await runContractRequest(/* signal 控制通知渠道列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/channels', { signal }), options) as unknown as NotificationChannelResponse[] | { /** channels 是后端包装的渠道列表。 */ data?: NotificationChannelResponse[]; /** channels 是兼容字段。 */ channels?: NotificationChannelResponse[] }; - // channels 是兼容直接数组与包装数组后的原始渠道列表。 - const channels = Array.isArray(response) ? response : response.data || response.channels || []; - return { success: true, data: channels.map(toNotificationChannel) }; + const response = await runContractRequest(/* signal 控制通知渠道列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/channels', { signal }), options); + return { success: true, data: response.map(toNotificationChannel) }; }; /** 创建通知渠道,并在传输边界序列化配置与事件。 */ -export const createNotificationChannel = async (data: Required> & NotificationChannelRequest, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制通知渠道创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels', { body: { ...data, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types) } as never, signal }), options) as unknown as Promise; +export const createNotificationChannel = async (data: Required> & NotificationChannelRequest, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制通知渠道创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels', { body: { name: data.name, type: data.type, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types), enabled: data.enabled }, signal }), options); /** 更新通知渠道的可编辑字段。 */ export const updateNotificationChannel = async (channelID: string, data: NotificationChannelRequest, options?: RequestControlOptions): Promise => { // payload 是已完成配置和事件序列化的更新请求。 - const payload: Record = { ...data }; - if ('config' in data) payload.config = JSON.stringify(data.config); - if ('event_types' in data) payload.event_types = stringifyNotificationEventTypes(data.event_types); - return runContractRequest(/* signal 控制通知渠道更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/notifications/channels/{channel_id}', { params: { path: { channel_id: channelID } }, body: payload as never, signal }), options) as unknown as Promise; + const payload = { + name: data.name, + type: data.type, + config: data.config === undefined ? undefined : JSON.stringify(data.config), + event_types: data.event_types === undefined ? undefined : stringifyNotificationEventTypes(data.event_types), + enabled: data.enabled, + }; + return runContractRequest(/* signal 控制通知渠道更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/notifications/channels/{channel_id}', { params: { path: { channel_id: channelID } }, body: payload, signal }), options); }; /** 删除指定通知渠道。 */ @@ -74,7 +76,7 @@ export const deleteNotificationChannel = async (channelID: string, options?: Req /** 获取并展平按账号分组存储的消息通知绑定。 */ export const getMessageNotifications = async (): Promise<{ /** 操作是否完成。 */ success: boolean; /** 展平后的绑定列表。 */ data: NotificationBinding[] }> => { // response 是按账号 ID 分组的通知绑定响应。 - const response = await runContractRequest(/* signal 控制消息通知列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/messages', { signal })) as unknown as Record; + const response = await runContractRequest(/* signal 控制消息通知列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/messages', { signal })); // bindings 是供页面直接渲染的扁平绑定集合。 const bindings: NotificationBinding[] = []; for (const /* accountID、channelBindings 是当前账号及其原始渠道绑定列表。 */ [accountID, channelBindings] of Object.entries(response || {})) { @@ -85,7 +87,7 @@ export const getMessageNotifications = async (): Promise<{ /** 操作是否完 }; /** 设置单个账号与渠道之间的启用状态。 */ -export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise => runContractRequest(/* signal 控制单账号通知开关更新请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_id: channelID, enabled } as never, signal })); +export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise => runContractRequest(/* signal 控制单账号通知开关更新请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_id: channelID, enabled }, signal })); /** 删除单个消息通知绑定。 */ export const deleteMessageNotification = async (notificationID: string): Promise => runContractRequest(/* signal 控制单条通知删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/notifications/messages/{notification_id}', { params: { path: { notification_id: notificationID } }, signal })); @@ -95,16 +97,16 @@ export const deleteAccountNotifications = async (accountID: string): Promise => { - // response 是账号渠道绑定的具名响应。 - const response = await runContractRequest(/* signal 控制账号通知绑定读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, signal }), options) as unknown as { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[]; /** data 是兼容包装。 */ data?: { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[] } }; - return Array.isArray(response.channel_ids) ? response.channel_ids : Array.isArray(response.data?.channel_ids) ? response.data.channel_ids : []; + // response 是由 OpenAPI 约束的账号渠道绑定响应;未绑定时后端兼容返回 null。 + const response = await runContractRequest(/* signal 控制账号通知绑定读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, signal }), options); + return response.channel_ids ?? []; }; /** 覆盖保存指定账号的通知渠道绑定。 */ -export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise => runContractRequest(/* signal 控制账号通知绑定覆盖请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_ids: channelIDs } as never, signal })); +export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise => runContractRequest(/* signal 控制账号通知绑定覆盖请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_ids: channelIDs }, signal })); /** 向单一通知渠道发送测试投递。 */ -export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制通知渠道测试投递的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels/{channel_id}/test', { params: { path: { channel_id: channelID } }, body: {} as never, signal }), options); +export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制通知渠道测试投递的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels/{channel_id}/test', { params: { path: { channel_id: channelID } }, signal }), options); /** 将系统配置响应转换为通知 SMTP 表单使用的状态模型。 */ const normalizeSystemSettings = (settings: Record): SystemSettings => { diff --git a/frontend/app/features/notifications/components/NotificationSmtpSettings.tsx b/frontend/app/features/notifications/components/NotificationSmtpSettings.tsx index a1565aa..8fd1384 100644 --- a/frontend/app/features/notifications/components/NotificationSmtpSettings.tsx +++ b/frontend/app/features/notifications/components/NotificationSmtpSettings.tsx @@ -71,21 +71,21 @@ export const NotificationSmtpSettings: React.FC =
-
-
+
+
-
+
- +

QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)

-
-
+
+
diff --git a/frontend/app/features/notifications/hooks.test.tsx b/frontend/app/features/notifications/hooks.test.tsx index 8d15b25..9a53598 100644 --- a/frontend/app/features/notifications/hooks.test.tsx +++ b/frontend/app/features/notifications/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook,waitFor } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { NotificationChannel,SystemSettings } from '../../../shared/api-contract/notifications'; +import type { NotificationChannel,SystemSettings } from './api'; import { createNotificationChannel,deleteNotificationChannel,getNotificationChannels,getSystemSettings,testNotificationChannel,updateNotificationChannel,updateSystemSettings } from './api'; import { useNotifications } from './hooks'; diff --git a/frontend/app/features/notifications/models.ts b/frontend/app/features/notifications/models.ts new file mode 100644 index 0000000..ae90af9 --- /dev/null +++ b/frontend/app/features/notifications/models.ts @@ -0,0 +1,123 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 SystemSettings UI 模型;不直接暴露 HTTP DTO。 */ +export interface SystemSettings { + /** 默认 AI 模型名称。 */ + ai_model?: string; + /** 全局 AI API 密钥。 */ + ai_api_key?: string; + /** 全局 AI API 密钥是否已在服务端配置。 */ + ai_api_key_configured?: boolean; + /** 全局 AI API 地址。 */ + ai_api_url?: string; + /** 全局 AI 基础地址。 */ + ai_base_url?: string; + /** 系统默认回复文案。 */ + default_reply?: string; + /** 是否允许注册新用户。 */ + registration_enabled?: boolean; + /** 系统 SMTP 服务器地址。 */ + smtp_server?: string; + /** 系统 SMTP 密码是否已在服务端配置。 */ + smtp_password_configured?: boolean; + /** 服务端日志级别。 */ + log_level?: 'debug' | 'info' | 'warn' | 'error' | string; + /** 服务端日志格式。 */ + log_format?: 'text' | 'json' | string; + /** 续期日志保留天数。 */ + renewal_log_retention_days?: number; + /** 远程验证码服务地址。 */ + 'captcha.remote_service_url'?: string; + /** 远程验证码服务密钥。 */ + 'captcha.remote_secret_key'?: string; + /** 远程验证码服务密钥是否已在服务端配置。 */ + 'captcha.remote_secret_key_configured'?: boolean; + /** 远程验证码服务 Cookie 配置。 */ + 'captcha.remote_pass_cookies'?: boolean | string; + /** 兼容未来配置键的扩展字段。 */ + /** 未知设置键只能承载服务端声明的标量值,敏感值不进入该 UI 模型。 */ + [key: string]: string | number | boolean | undefined; +} + +/** 由当前 feature adapter 归一后的 NotificationChannelType UI 模型;不直接暴露 HTTP DTO。 */ +export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email'; +/** 由当前 feature adapter 归一后的 NotificationEventType UI 模型;不直接暴露 HTTP DTO。 */ +export type NotificationEventType = + | 'account_offline' + | 'account_recovered' + | 'account_disabled' + | 'security_verification' + | 'token_renewal' + | 'delivery_result' + | 'system_error'; + +/** 由当前 feature adapter 归一后的 NotificationChannel UI 模型;不直接暴露 HTTP DTO。 */ +export interface NotificationChannel { + /** 通知渠道标识。 */ + id: string; + /** 通知渠道名称。 */ + name: string; + /** 通知渠道类型。 */ + type: NotificationChannelType; + /** 通知渠道配置。 */ + config: Record; + /** 渠道绑定的事件类型。 */ + event_types?: NotificationEventType[]; + /** 通知渠道是否启用。 */ + enabled: boolean; + /** 创建时间。 */ + created_at?: string; + /** 更新时间。 */ + updated_at?: string; +} + +/** 通知绑定列表中的单条记录。 */ +/** 由当前 feature adapter 归一后的 NotificationBinding UI 模型;不直接暴露 HTTP DTO。 */ +export interface NotificationBinding { + /** 账号稳定标识,列表归一化后补充。 */ + cookie_id?: string; + /** 绑定记录主键。 */ + id?: number; + /** 通知渠道主键。 */ + channel_id: number; + /** 通知渠道名称。 */ + channel_name: string; + /** 绑定是否启用。 */ + enabled: boolean; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} + +/** 通知渠道接口返回的原始具名 DTO。 */ +/** 由当前 feature adapter 归一后的 NotificationChannelResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface NotificationChannelResponse { + /** 通知渠道主键。 */ + id: number; + /** 通知渠道名称。 */ + name: string; + /** 通知渠道类型。 */ + type: string; + /** 订阅事件类型 JSON 或兼容文本。 */ + event_types?: string; + /** 通知渠道是否启用。 */ + enabled: boolean; + /** 所属用户主键。 */ + user_id?: number; +} diff --git a/frontend/app/features/notifications/state.test.ts b/frontend/app/features/notifications/state.test.ts index bb5d0c7..6ab83a0 100644 --- a/frontend/app/features/notifications/state.test.ts +++ b/frontend/app/features/notifications/state.test.ts @@ -1,5 +1,5 @@ import { expect,test } from 'vitest'; -import type { NotificationChannel } from '../../../shared/api-contract/notifications'; +import type { NotificationChannel } from './api'; import { buildNotificationPayload,emptyNotificationForm,isCurrentNotificationRequest,normalizeNotificationForm,notificationErrorMessage,notificationEventSummary,validateNotificationForm } from './state'; import type { NotificationForm } from './types'; diff --git a/frontend/app/features/orders/api.ts b/frontend/app/features/orders/api.ts index ef78041..7d35d87 100644 --- a/frontend/app/features/orders/api.ts +++ b/frontend/app/features/orders/api.ts @@ -10,11 +10,11 @@ OrderRefreshJobCancelResponse,OrderRefreshJobStatusResponse, OrderRefreshResponse, OrderSingleRefreshResponse, PaginatedResponse -} from '../../../shared/api-contract/orders'; +} from './models'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import { type RequestControlOptions } from '../../../shared/http/client'; import { collectionFrom, objectFrom } from '../../../shared/http/contract'; -export type * from '../../../shared/api-contract/orders'; +export type * from './models'; /** 订单刷新前端最多轮询约 90 秒,超过该预算必须请求取消后端 worker。 */ const orderRefreshPollLimit = 180; @@ -157,9 +157,22 @@ export const getOrderDetail = async (orderId: string): Promise<{ /** success 表 params: { path: { order_id: orderId } }, signal, })); + // data 是将可选 transport 字段归一为 UI 模型稳定字符串/布尔值后的订单详情。 + const data: OrderDTOResponse = { + ...result.data, + spec_name: result.data.spec_name ?? '', + spec_value: result.data.spec_value ?? '', + is_bargain: result.data.is_bargain ?? 0, + system_shipped: result.data.system_shipped ?? false, + receiver_name: result.data.receiver_name ?? '', + receiver_phone: result.data.receiver_phone ?? '', + receiver_address: result.data.receiver_address ?? '', + receiver_city: result.data.receiver_city ?? '', + updated_at: result.data.updated_at ?? result.data.created_at, + }; return { success: true, - data: result.data + data }; }; diff --git a/frontend/app/features/orders/hooks.test.tsx b/frontend/app/features/orders/hooks.test.tsx index 2bb3f79..2204317 100644 --- a/frontend/app/features/orders/hooks.test.tsx +++ b/frontend/app/features/orders/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook,waitFor } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail,Item } from '../../../shared/api-contract/orders'; +import type { AccountDetail,Item } from './api'; import { getAccountDetails,getItems,getOrders,importOrders } from './api'; import { useOrderImport,useOrderQuery } from './hooks'; diff --git a/frontend/app/features/orders/models.ts b/frontend/app/features/orders/models.ts new file mode 100644 index 0000000..930a76c --- /dev/null +++ b/frontend/app/features/orders/models.ts @@ -0,0 +1,426 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 PaginatedResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface PaginatedResponse { + /** 表示查询是否成功。 */ + success: boolean; + /** 当前页数据。 */ + data: T[]; + /** 符合条件的总记录数。 */ + total: number; + /** 当前页码。 */ + page: number; + /** 每页记录数。 */ + page_size: number; + /** 总页数。 */ + total_pages: number; + /** 各触发类型的规则计数。 */ + trigger_counts?: Record; +} + +/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountDetail { + /** 闲鱼账号稳定标识。 */ + id: string; + /** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */ + cookie_configured?: boolean; + /** 账号是否允许运行。 */ + enabled: boolean; + /** 是否自动确认订单。 */ + auto_confirm: boolean; + /** 用户为账号设置的备注。 */ + remark?: string; + /** 自动回复暂停时长,单位为分钟。 */ + pause_duration?: number; + /** 暂停结束时间的 Unix 秒。 */ + paused_until?: number; + /** 当前是否处于暂停状态。 */ + paused?: boolean; + // 登录信息 + /** 用于密码登录的闲鱼用户名。 */ + username?: string; + /** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */ + login_password_configured?: boolean; + /** 是否在密码登录时显示浏览器。 */ + show_browser?: boolean; + // Frontend helpers + /** 平台账号昵称。 */ + nickname?: string; + /** 平台账号头像地址。 */ + avatar_url?: string; + /** 资料刷新失败时的说明。 */ + profile_error?: string; + /** 当前账号运行状态。 */ + runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled'; + /** 当前运行状态的用户可见说明。 */ + runtime_message?: string; + /** 当前运行实例是否已连接。 */ + runtime_connected?: boolean; + /** 运行状态快照的更新时间。 */ + runtime_updated_at?: string; + // AI设置 + /** 是否启用账号 AI 回复。 */ + ai_enabled?: boolean; + /** 允许的最大折扣比例。 */ + max_discount_percent?: number; + /** 允许的最大折扣金额。 */ + max_discount_amount?: number; + /** 允许的最大砍价轮次。 */ + max_bargain_rounds?: number; + /** 账号自定义提示词。 */ + custom_prompts?: string; + // 账号级计划任务 + /** 是否启用自动评价。 */ + auto_rate_enabled?: boolean; + /** 自动评价使用的文案。 */ + rate_content?: string; + /** 是否启用每日擦亮。 */ + auto_polish_enabled?: boolean; + /** 每日擦亮执行时间。 */ + polish_time?: string; + /** 最近一次自动评价扫描时间。 */ + last_rate_scan_at?: number; + /** 最近一次擦亮日期。 */ + last_polish_date?: string; + /** 最近一次擦亮时间。 */ + last_polish_at?: number; +} + +/** 由当前 feature adapter 归一后的 OrderStatus UI 模型;不直接暴露 HTTP DTO。 */ +export type OrderStatus = + | 'processing' + | 'pending_ship' + | 'shipped' + | 'completed' + | 'cancelled' + | 'refunding' + | 'unknown'; + +/** 由当前 feature adapter 归一后的 Order UI 模型;不直接暴露 HTTP DTO。 */ +export interface Order { + /** 订单本地数据库主键。 */ + id: string; + /** 平台订单标识。 */ + order_id: string; + /** 订单所属账号标识。 */ + cookie_id: string; + /** 订单关联商品标识。 */ + item_id: string; + /** 商品标题。 */ + item_title?: string; + /** 商品图片地址。 */ + item_image?: string; + /** 商品价格文本。 */ + item_price?: string; + /** 买家平台标识。 */ + buyer_id: string; + /** 购买数量。 */ + quantity: number; + /** 订单金额文本。 */ + amount: string; + /** 前端归一化后的订单状态。 */ + status: OrderStatus; + /** 服务端原始订单状态。 */ + order_status?: OrderStatus; + /** 收货人姓名。 */ + receiver_name?: string; + /** 收货人电话。 */ + receiver_phone?: string; + /** 收货地址。 */ + receiver_address?: string; + /** 订单创建时间。 */ + created_at?: string; + /** 订单更新时间。 */ + updated_at?: string; +} + +/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */ +export interface Item { + /** 本地商品数据库主键。 */ + id: string | number; + /** 商品所属账号标识。 */ + cookie_id: string; + /** 平台商品标识。 */ + item_id: string; + /** 商品标题。 */ + item_title?: string; + /** 商品描述。 */ + item_description?: string; + /** 商品价格文本。 */ + item_price?: string; + /** 商品主图地址。 */ + item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes + /** 商品分类标识。 */ + item_category?: string; + /** 商品详情原始 JSON。 */ + item_detail?: string; + /** 是否启用多规格。 */ + is_multi_spec?: number | boolean; + /** 是否按数量发货。 */ + multi_quantity_delivery?: number | boolean; + /** 是否启用多数量发货兼容字段。 */ + is_multi_qty_ship?: number | boolean; +} + +/** 订单详情接口返回的原始具名订单 DTO。 */ +/** 由当前 feature adapter 归一后的 OrderDTOResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderDTOResponse { + /** 平台订单标识。 */ + order_id: string; + /** 关联商品标识。 */ + item_id: string; + /** 关联商品标题。 */ + item_title: string; + /** 关联商品图片地址。 */ + item_image: string; + /** 买家平台标识。 */ + buyer_id: string; + /** 商品规格名称。 */ + spec_name: string; + /** 商品规格值。 */ + spec_value: string; + /** 购买数量文本。 */ + quantity: string; + /** 实付金额文本。 */ + amount: string; + /** 归一化订单状态。 */ + order_status: string; + /** 兼容前端使用的订单状态别名。 */ + status: string; + /** 所属账号标识。 */ + cookie_id: string; + /** 是否议价订单。 */ + is_bargain: number; + /** 是否系统发货。 */ + system_shipped: boolean; + /** 收货人姓名。 */ + receiver_name: string; + /** 收货人电话。 */ + receiver_phone: string; + /** 收货地址。 */ + receiver_address: string; + /** 收货城市。 */ + receiver_city: string; + /** 创建时间。 */ + created_at: string; + /** 更新时间。 */ + updated_at: string; +} + +/** 订单详情接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 OrderDetailResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderDetailResponse extends OrderDTOResponse { + /** 表示查询是否完成。 */ + success: boolean; + /** 新版客户端读取的订单对象。 */ + data: OrderDTOResponse; +} + +/** 订单单条刷新返回的远端详情。 */ +/** 由当前 feature adapter 归一后的 OrderRefreshDetailResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderRefreshDetailResponse { + /** 购买数量文本。 */ + quantity: string; + /** 商品规格名称。 */ + spec_name: string; + /** 商品规格值。 */ + spec_value: string; + /** 归一化订单状态。 */ + order_status: string; + /** 实付金额文本。 */ + amount: string; +} + +/** 订单单条刷新接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 OrderSingleRefreshResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderSingleRefreshResponse { + /** 表示刷新是否完成。 */ + success: boolean; + /** 刷新结果说明。 */ + message: string; + /** 刷新后的订单详情。 */ + order: OrderRefreshDetailResponse; +} + +/** 订单批量变更接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 OrderBatchResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderBatchResponse { + /** 表示批量操作是否存在部分失败。 */ + partial_failure: boolean; + /** 批量操作结果说明。 */ + message: string; + /** 订单总数,导入接口提供。 */ + total?: number; + /** 成功处理数量。 */ + success_count: number; + /** 失败处理数量。 */ + failed_count: number; + /** 逐订单兼容结果行。 */ + results: OrderBatchResult[]; +} + +/** 订单批量接口的逐订单结果行。 */ +/** 由当前 feature adapter 归一后的 OrderBatchResult UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderBatchResult { + /** 订单平台标识。 */ + order_id?: string; + /** 订单动作状态:failed、succeeded 或 reconciliation_required。 */ + status?: 'failed' | 'succeeded' | 'reconciliation_required'; + /** 表示该订单是否处理成功。 */ + success?: boolean; + /** 该订单处理结果说明。 */ + message: string; + /** 兼容接口可能返回的账号标识。 */ + cookie_id?: string; + /** 待补偿记录标识。 */ + reconciliation_id?: string; + /** 本地状态或补偿记录写入警告。 */ + reconciliation_warning?: string; + /** 兼容接口可能返回的处理阶段。 */ + stage?: string; + /** 允许后端保留尚未结构化的扩展字段。 */ + [key: string]: unknown; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} + +/** 管理员全局统计响应。 */ +/** 由当前 feature adapter 归一后的 AdminStats UI 模型;不直接暴露 HTTP DTO。 */ +export interface AdminStats { + /** 管理员可见的用户总数。 */ total_users: number; + /** 当前用户拥有的账号总数。 */ total_cookies: number; + /** 已启用账号数量。 */ active_cookies: number; + /** 卡券组总数。 */ total_cards: number; + /** 关键词规则总数。 */ total_keywords: number; + /** 订单总数。 */ total_orders: number; +} + +/** 订单域兼容页面使用的数据概览字段。 */ +export interface DashboardStats { + /** 当前用户的账号总数。 */ total_cookies: number; + /** 已启用账号数量。 */ active_cookies: number; + /** 卡券组总数。 */ total_cards: number; + /** 关键词规则总数。 */ total_keywords: number; + /** 订单总数。 */ total_orders: number; + /** 可用卡券库存。 */ available_card_stock: number; +} + +/** 管理员全局统计响应。 */ +/** 由当前 feature adapter 归一后的 AdminStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AdminStatsResponse extends AdminStats {} + +/** 当前用户数据概览响应。 */ +/** 由当前 feature adapter 归一后的 DashboardStatsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface DashboardStatsResponse extends DashboardStats {} + +/** 订单列表刷新逐项结果。 */ +/** 由当前 feature adapter 归一后的 OrderRefreshResultResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderRefreshResultResponse { + /** 结果所属账号标识。 */ + cookie_id?: string; + /** 当前处理阶段。 */ + stage?: string; + /** 当前项是否处理成功。 */ + success: boolean; + /** 结果说明。 */ + message?: string; + /** 发现的新订单数量。 */ + discovered?: number; + /** 更新的订单数量。 */ + updated?: number; + /** 标记删除的订单数量。 */ + /** soft_deleted 表示该订单是否已被本次刷新标记为软删除。 */ + soft_deleted?: boolean; + /** 订单平台标识。 */ + order_id?: string; + /** 结果错误说明。 */ + error?: string; +} + +/** 订单列表刷新统计摘要。 */ +/** 由当前 feature adapter 归一后的 OrderRefreshSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderRefreshSummaryResponse { + /** 发现的新订单数量。 */ + discovered: number; + /** 订单列表更新数量。 */ + list_updated: number; + /** 标记删除数量。 */ + soft_deleted: number; + /** 需要补全详情的订单数量。 */ + detail_total: number; + /** 本次处理订单总数。 */ + total: number; + /** 状态发生变化数量。 */ + updated: number; + /** 状态未变化数量。 */ + no_change: number; + /** 刷新失败数量。 */ + failed: number; +} + +/** 订单列表刷新响应。 */ +/** 由当前 feature adapter 归一后的 OrderRefreshResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderRefreshResponse { + /** 是否存在部分失败。 */ + partial_failure: boolean; + /** 刷新结果说明。 */ + message: string; + /** 刷新统计摘要。 */ + summary: OrderRefreshSummaryResponse; + /** 逐项兼容结果。 */ + results: OrderRefreshResultResponse[]; +} + +/** 创建订单刷新后台任务的响应。 */ +/** 由当前 feature adapter 归一后的 OrderRefreshJobStartResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderRefreshJobStartResponse { + /** 任务是否创建成功。 */ + success: boolean; + /** 后台任务标识。 */ + job_id: string; + /** 任务当前状态。 */ + status: 'queued' | 'running'; +} + +/** 查询订单刷新后台任务的响应。 */ +/** 由当前 feature adapter 归一后的 OrderRefreshJobStatusResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderRefreshJobStatusResponse { + /** 查询是否成功。 */ + success: boolean; + /** 后台任务标识。 */ + job_id: string; + /** 任务当前状态。 */ + status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; + /** 任务失败原因。 */ + error_message?: string; + /** 任务成功后的订单刷新结果。 */ + result?: OrderRefreshResponse; +} + +/** 取消订单刷新后台任务的响应。 */ +/** 由当前 feature adapter 归一后的 OrderRefreshJobCancelResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OrderRefreshJobCancelResponse { + /** 取消命令是否成功应用。 */ + success: boolean; + /** 被取消的任务标识。 */ + job_id: string; + /** 取消后的任务状态。 */ + status: 'cancelled'; +} diff --git a/frontend/app/features/orders/orderActions.test.tsx b/frontend/app/features/orders/orderActions.test.tsx index b2610e9..73433b3 100644 --- a/frontend/app/features/orders/orderActions.test.tsx +++ b/frontend/app/features/orders/orderActions.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook } from '@testing-library/react'; import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest'; -import type { Order,OrderRefreshResponse } from '../../../shared/api-contract/orders'; +import type { Order,OrderRefreshResponse } from './api'; import { useOrderActions } from './orderActions'; // orderActionMocks 保存订单动作 Hook 测试使用的 API 替身。 diff --git a/frontend/app/features/orders/pages/OrderList.test.tsx b/frontend/app/features/orders/pages/OrderList.test.tsx index 4ce881b..db0c13a 100644 --- a/frontend/app/features/orders/pages/OrderList.test.tsx +++ b/frontend/app/features/orders/pages/OrderList.test.tsx @@ -2,7 +2,7 @@ import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react'; import React from 'react'; import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest'; -import type { Order } from '../../../../shared/api-contract/orders'; +import type { Order } from '../api'; // orderListMocks 保存订单页面测试使用的 Hook、API 和子组件替身。 const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共享替身。 */ () => ({ diff --git a/frontend/app/features/presentational-components.test.tsx b/frontend/app/features/presentational-components.test.tsx index 4d7b513..7cb6727 100644 --- a/frontend/app/features/presentational-components.test.tsx +++ b/frontend/app/features/presentational-components.test.tsx @@ -1,6 +1,7 @@ import ReactDOMServer from 'react-dom/server'; import { describe,expect,test } from 'vitest'; -import type { NotificationChannel,SystemSettings } from '../../shared/api-contract/common'; +import type { NotificationChannel } from './notifications/api'; +import type { SystemSettings } from './settings/api'; import { CardIcon } from './cards/components/CardIcon'; import { BatchPhaseIndicator } from './items/components/BatchPhaseIndicator'; import { NotificationChannelList } from './notifications/components/NotificationChannelList'; diff --git a/frontend/app/features/rules/api.ts b/frontend/app/features/rules/api.ts index 060be16..ba5fe89 100644 --- a/frontend/app/features/rules/api.ts +++ b/frontend/app/features/rules/api.ts @@ -14,11 +14,11 @@ MutationIDResponse,OperationResponse, PaginatedResponse, ReplyRule, ShippingRule -} from '../../../shared/api-contract/automation'; +} from './models'; import { type RequestControlOptions } from '../../../shared/http/client'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import { collectionFrom,objectFrom } from '../../../shared/http/contract'; -export type * from '../../../shared/api-contract/automation'; +export type * from './models'; /** 自动化规则筛选器读取非敏感账号摘要。 */ export const getAccountDetails = async (options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制规则页账号摘要读取的取消和超时。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options); diff --git a/frontend/app/features/rules/hooks.test.tsx b/frontend/app/features/rules/hooks.test.tsx index f120b1c..33b2878 100644 --- a/frontend/app/features/rules/hooks.test.tsx +++ b/frontend/app/features/rules/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { AccountDetail,Card,DefaultReply,Item,ReplyRule,ShippingRule } from '../../../shared/api-contract/automation'; +import type { AccountDetail,Card,DefaultReply,Item,ReplyRule,ShippingRule } from './api'; import { getAccountDetails, getAutomationIssues, diff --git a/frontend/app/features/rules/models.ts b/frontend/app/features/rules/models.ts new file mode 100644 index 0000000..f7b5d0c --- /dev/null +++ b/frontend/app/features/rules/models.ts @@ -0,0 +1,461 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 PaginatedResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface PaginatedResponse { + /** 表示查询是否成功。 */ + success: boolean; + /** 当前页数据。 */ + data: T[]; + /** 符合条件的总记录数。 */ + total: number; + /** 当前页码。 */ + page: number; + /** 每页记录数。 */ + page_size: number; + /** 总页数。 */ + total_pages: number; + /** 各触发类型的规则计数。 */ + trigger_counts?: Record; +} + +/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */ +export interface AccountDetail { + /** 闲鱼账号稳定标识。 */ + id: string; + /** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */ + cookie_configured?: boolean; + /** 账号是否允许运行。 */ + enabled: boolean; + /** 是否自动确认订单。 */ + auto_confirm: boolean; + /** 用户为账号设置的备注。 */ + remark?: string; + /** 自动回复暂停时长,单位为分钟。 */ + pause_duration?: number; + /** 暂停结束时间的 Unix 秒。 */ + paused_until?: number; + /** 当前是否处于暂停状态。 */ + paused?: boolean; + // 登录信息 + /** 用于密码登录的闲鱼用户名。 */ + username?: string; + /** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */ + login_password_configured?: boolean; + /** 是否在密码登录时显示浏览器。 */ + show_browser?: boolean; + // Frontend helpers + /** 平台账号昵称。 */ + nickname?: string; + /** 平台账号头像地址。 */ + avatar_url?: string; + /** 资料刷新失败时的说明。 */ + profile_error?: string; + /** 当前账号运行状态。 */ + runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled'; + /** 当前运行状态的用户可见说明。 */ + runtime_message?: string; + /** 当前运行实例是否已连接。 */ + runtime_connected?: boolean; + /** 运行状态快照的更新时间。 */ + runtime_updated_at?: string; + // AI设置 + /** 是否启用账号 AI 回复。 */ + ai_enabled?: boolean; + /** 允许的最大折扣比例。 */ + max_discount_percent?: number; + /** 允许的最大折扣金额。 */ + max_discount_amount?: number; + /** 允许的最大砍价轮次。 */ + max_bargain_rounds?: number; + /** 账号自定义提示词。 */ + custom_prompts?: string; + // 账号级计划任务 + /** 是否启用自动评价。 */ + auto_rate_enabled?: boolean; + /** 自动评价使用的文案。 */ + rate_content?: string; + /** 是否启用每日擦亮。 */ + auto_polish_enabled?: boolean; + /** 每日擦亮执行时间。 */ + polish_time?: string; + /** 最近一次自动评价扫描时间。 */ + last_rate_scan_at?: number; + /** 最近一次擦亮日期。 */ + last_polish_date?: string; + /** 最近一次擦亮时间。 */ + last_polish_at?: number; +} + +/** 由当前 feature adapter 归一后的 Card UI 模型;不直接暴露 HTTP DTO。 */ +export interface Card { + /** 卡券组数值主键。 */ + id: number; + /** 卡券组名称。 */ + name: string; + /** 卡券组类型。 */ + type: 'api' | 'text' | 'data' | 'image'; + /** 卡券组说明。 */ + description?: string; + /** 卡券组是否启用。 */ + enabled: boolean; + // 文本类型 + text_content?: string; + // 批量数据类型 + data_content?: string; + // API 类型配置 + api_config?: { + /** API 卡券请求地址。 */ + url: string; + /** API 卡券请求方法。 */ + method: 'GET' | 'POST'; + /** API 请求超时时间。 */ + timeout?: number; + /** API 请求头 JSON。 */ + headers?: string; + /** API 请求参数 JSON。 */ + params?: string; + }; + // 图片类型 + /** 图片卡券地址。 */ + image_url?: string; + // 通用配置 + /** 卡券发送延迟秒数。 */ + delay_seconds?: number; + // 多规格配置 + /** 是否支持多规格。 */ + is_multi_spec?: boolean; + /** 规格名称。 */ + spec_name?: string; + /** 规格值。 */ + spec_value?: string; +} + +/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */ +export interface Item { + /** 本地商品数据库主键。 */ + id: string | number; + /** 商品所属账号标识。 */ + cookie_id: string; + /** 平台商品标识。 */ + item_id: string; + /** 商品标题。 */ + item_title?: string; + /** 商品描述。 */ + item_description?: string; + /** 商品价格文本。 */ + item_price?: string; + /** 商品主图地址。 */ + item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes + /** 商品分类标识。 */ + item_category?: string; + /** 商品详情原始 JSON。 */ + item_detail?: string; + /** 是否启用多规格。 */ + is_multi_spec?: number | boolean; + /** 是否按数量发货。 */ + multi_quantity_delivery?: number | boolean; + /** 是否启用多数量发货兼容字段。 */ + is_multi_qty_ship?: number | boolean; +} + +/** 由当前 feature adapter 归一后的 AutomationTriggerType UI 模型;不直接暴露 HTTP DTO。 */ +export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout'; +/** 由当前 feature adapter 归一后的 AutomationActionType UI 模型;不直接暴露 HTTP DTO。 */ +export type AutomationActionType = 'confirm_shipment' | 'send_card' | 'send_text'; + +// Rules +/** 由当前 feature adapter 归一后的 ShippingRule UI 模型;不直接暴露 HTTP DTO。 */ +export interface ShippingRule { + /** 规则标识。 */ + id: string; + /** 规则名称。 */ + name: string; + /** 规则触发类型。 */ + trigger_type: AutomationTriggerType; + /** 规则匹配关键词。 */ + item_keyword: string; // Legacy UI helper + /** 规则限定的账号标识。 */ + cookie_id?: string; + /** 规则限定的商品标识。 */ + item_id?: string; + /** 规则限定的商品标题。 */ + item_title?: string; + /** 首个发卡动作使用的卡券组 ID。 */ + card_group_id: number; // First send_card action card id + /** 首个发卡动作使用的卡券组名称。 */ + card_group_name?: string; // UI helper + /** 规则优先级。 */ + priority: number; + /** 规则是否启用。 */ + enabled: boolean; + /** 规则原始配置 JSON。 */ + config_json?: string; + /** 规则动作列表。 */ + actions: AutomationAction[]; + /** 规则规格变体列表。 */ + variants: ShippingVariant[]; +} + +/** 由当前 feature adapter 归一后的 AutomationAction UI 模型;不直接暴露 HTTP DTO。 */ +export interface AutomationAction { + /** 动作标识。 */ + id?: string; + /** 动作类型。 */ + action_type: AutomationActionType; + /** 动作使用的卡券组 ID。 */ + card_id?: number; + /** 动作使用的卡券组名称。 */ + card_name?: string; + /** 本次发放数量。 */ + delivery_count?: number; + /** 文本消息模板。 */ + message_template?: string; + /** 动作延迟秒数。 */ + delay_seconds?: number; + /** 动作原始配置 JSON。 */ + config_json?: string; + /** 动作是否启用。 */ + enabled: boolean; + /** 动作排序序号。 */ + sort_order?: number; +} + +/** 由当前 feature adapter 归一后的 ShippingVariant UI 模型;不直接暴露 HTTP DTO。 */ +export interface ShippingVariant { + /** 规格变体标识。 */ + id?: string; + /** 规格名称。 */ + spec_name: string; + /** 规格值。 */ + spec_value: string; + /** 变体使用的卡券组 ID。 */ + card_id: number; + /** 变体使用的卡券组名称。 */ + card_name?: string; + /** 卡券类型。 */ + card_type?: Card['type']; + /** 变体发放数量。 */ + delivery_count: number; + /** 变体是否启用。 */ + enabled: boolean; + /** 是否覆盖动作级延迟。 */ + delay_override?: boolean; + /** 变体延迟秒数。 */ + delay_seconds?: number; + /** 变体原始配置 JSON。 */ + config_json?: string; +} + +/** 由当前 feature adapter 归一后的 ReplyRule UI 模型;不直接暴露 HTTP DTO。 */ +export interface ReplyRule { + /** 回复规则标识。 */ + id: string; + /** 触发关键词。 */ + keyword: string; + /** 回复正文。 */ + reply_content: string; + /** 关键词匹配方式。 */ + match_type: 'exact' | 'fuzzy'; + /** 规则是否启用。 */ + enabled: boolean; + /** 规则限定的商品标识。 */ + item_id?: string; + /** 回复类型。 */ + type?: 'text' | 'image'; + /** 图片回复地址。 */ + image_url?: string; +} + +/** 由当前 feature adapter 归一后的 DefaultReply UI 模型;不直接暴露 HTTP DTO。 */ +export interface DefaultReply { + /** 账号稳定标识。 */ + cookie_id: string; + /** 默认回复是否启用。 */ + enabled: boolean; + /** 默认回复正文。 */ + reply_content: string; + /** 是否对同一会话只回复一次。 */ + reply_once: boolean; + /** 默认图片回复地址。 */ + reply_image_url?: string; +} + +/** 自动化规则动作的原始具名 DTO。 */ +/** 由当前 feature adapter 归一后的 AutomationActionResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AutomationActionResponse { + /** 动作稳定标识。 */ + id: number; + /** 动作类型。 */ + action_type: string; + /** 关联卡券组标识。 */ + card_id: number; + /** 关联卡券组名称。 */ + card_name: string; + /** 发送数量。 */ + delivery_count: number; + /** 消息模板。 */ + message_template: string; + /** 延迟秒数。 */ + delay_seconds: number; + /** 扩展配置 JSON。 */ + config_json: string; + /** 是否启用。 */ + enabled: boolean; + /** 执行顺序。 */ + sort_order: number; +} + +/** 自动化规则的原始具名 DTO。 */ +/** 由当前 feature adapter 归一后的 AutomationRuleResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AutomationRuleResponse { + /** 规则稳定标识。 */ + id: number; + /** 所属账号标识。 */ + cookie_id: string; + /** 关联商品标识。 */ + item_id: string; + /** 关联商品标题。 */ + item_title: string; + /** 规则名称。 */ + name: string; + /** 触发类型。 */ + trigger_type: string; + /** 是否启用。 */ + enabled: boolean; + /** 规则优先级。 */ + priority: number; + /** 扩展配置 JSON。 */ + config_json: string; + /** 规则动作列表。 */ + actions: AutomationActionResponse[]; + /** 创建时间。 */ + created_at: string; + /** 更新时间。 */ + updated_at: string; +} + +/** 自动化规则分页接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 AutomationRulePageResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AutomationRulePageResponse { + /** 表示查询是否完成。 */ + success: boolean; + /** 当前页规则列表。 */ + data: AutomationRuleResponse[]; + /** 规则总数。 */ + total: number; + /** 当前页码。 */ + page: number; + /** 当前页大小。 */ + page_size: number; + /** 总页数。 */ + total_pages: number; + /** 各触发类型规则数量。 */ + trigger_counts: Record; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} + +/** 传统关键词列表项响应。 */ +/** 由当前 feature adapter 归一后的 KeywordBasicResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface KeywordBasicResponse { + /** 匹配关键词。 */ + keyword: string; + /** 文字回复内容。 */ + reply: string; +} + +/** 带商品范围的关键词列表项响应。 */ +/** 由当前 feature adapter 归一后的 KeywordItemResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface KeywordItemResponse extends KeywordBasicResponse { + /** 限定的商品标识。 */ + item_id: string; +} + +/** 带类型和主键的关键词列表项响应。 */ +/** 由当前 feature adapter 归一后的 KeywordTypedResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface KeywordTypedResponse extends KeywordItemResponse { + /** 关键词规则主键。 */ + id: number; + /** 回复类型。 */ + type: 'text' | 'image'; + /** 图片回复地址。 */ + image_url: string; +} + +/** 指定商品回复项响应。 */ +/** 由当前 feature adapter 归一后的 ItemReplyResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface ItemReplyResponse { + /** 商品平台标识。 */ + item_id?: string; + /** 账号稳定标识。 */ + cookie_id?: string; + /** 指定商品的回复内容。 */ + reply_content: string; +} + +/** 默认回复查询响应。 */ +/** 由当前 feature adapter 归一后的 DefaultReplyResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface DefaultReplyResponse extends DefaultReply { + /** 账号稳定标识。 */ + cookie_id: string; +} + +// AutomationIssuesEnvelope 是自动化异常接口的兼容响应。 +/** 由当前 feature adapter 归一后的 AutomationIssuesEnvelope UI 模型;不直接暴露 HTTP DTO。 */ +export interface AutomationIssuesEnvelope { + /** runs 是待处理的自动化运行记录。 */ + runs?: Array<{ + /** 记录标识。 */ + id: number; + /** 所属账号标识。 */ + cookie_id: string; + /** 所属订单标识。 */ + order_id: string; + /** 自动化触发类型。 */ + trigger_type: string; + /** 外部错误说明。 */ + error_message: string; + /** 异常类别。 */ + issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed'; + /** 允许的处理动作。 */ + allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>; + /** 当前动作游标。 */ + action_cursor: number; + /** 已发送数量。 */ + sent_count: number; + /** 更新时间。 */ + updated_at: string; + }>; + /** pending_tasks 是延迟自动化任务列表。 */ + pending_tasks?: Array<{ + /** 任务标识。 */ + id: number; + /** 所属账号标识。 */ + cookie_id: string; + /** 自动化触发类型。 */ + trigger_type: string; + /** 错误说明。 */ + error_message: string; + /** 当前重试次数。 */ + attempt_count: number; + /** 更新时间。 */ + updated_at: string; + }>; +} diff --git a/frontend/app/features/rules/utils.test.ts b/frontend/app/features/rules/utils.test.ts index 7f9cd91..bba75e4 100644 --- a/frontend/app/features/rules/utils.test.ts +++ b/frontend/app/features/rules/utils.test.ts @@ -1,5 +1,5 @@ import { describe,expect,test } from 'vitest'; -import type { AccountDetail,ShippingRule } from '../../../shared/api-contract/automation'; +import type { AccountDetail,ShippingRule } from './api'; import { accentClasses, accountLabel, diff --git a/frontend/app/features/session/api.ts b/frontend/app/features/session/api.ts index 190807b..82d517f 100644 --- a/frontend/app/features/session/api.ts +++ b/frontend/app/features/session/api.ts @@ -1,6 +1,6 @@ -import type { OperationResponse,SessionResponse } from '../../../shared/api-contract/session'; +import type { OperationResponse,SessionResponse } from './models'; import { contractClient, runContractRequest, type ContractRequestOptions } from '../../../shared/api-contract/client'; -export type * from '../../../shared/api-contract/session'; +export type * from './models'; /** 会话状态接口返回的只读传输契约。 */ export interface SessionStatusResponse { diff --git a/frontend/app/features/session/models.ts b/frontend/app/features/session/models.ts new file mode 100644 index 0000000..f7ff424 --- /dev/null +++ b/frontend/app/features/session/models.ts @@ -0,0 +1,36 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 SessionResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface SessionResponse { + /** 表示登录或初始化是否成功。 */ + success: boolean; + /** 登录成功后的会话 Token。 */ + token?: string; + /** 服务端返回的操作说明。 */ + message?: string; + /** 当前用户 ID。 */ + user_id?: number; + /** 当前用户名。 */ + username?: string; + /** 当前用户是否为管理员。 */ + is_admin?: boolean; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} diff --git a/frontend/app/features/settings/api.ts b/frontend/app/features/settings/api.ts index bc16abe..1eadc36 100644 --- a/frontend/app/features/settings/api.ts +++ b/frontend/app/features/settings/api.ts @@ -1,7 +1,7 @@ -import type { OperationResponse,SystemSettings } from '../../../shared/api-contract/settings'; +import type { OperationResponse,SystemSettings } from './models'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import { type RequestControlOptions } from '../../../shared/http/client'; -export type * from '../../../shared/api-contract/settings'; +export type * from './models'; /** 设置页面使用的会话状态传输契约,避免跨 feature 依赖。 */ export interface SettingsSessionStatusResponse { diff --git a/frontend/app/features/settings/hooks.test.tsx b/frontend/app/features/settings/hooks.test.tsx index 7bafc20..acffb5e 100644 --- a/frontend/app/features/settings/hooks.test.tsx +++ b/frontend/app/features/settings/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act,renderHook,waitFor } from '@testing-library/react'; import { beforeEach,describe,expect,test,vi } from 'vitest'; -import type { OperationResponse,SystemSettings } from '../../../shared/api-contract/settings'; +import type { OperationResponse,SystemSettings } from './api'; import { fetchAIModels,getSystemSettings,updateLoginCredentials,updateSystemSettings,verifySession } from './api'; import { useSettings } from './hooks'; diff --git a/frontend/app/features/settings/models.ts b/frontend/app/features/settings/models.ts new file mode 100644 index 0000000..8935872 --- /dev/null +++ b/frontend/app/features/settings/models.ts @@ -0,0 +1,80 @@ +// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。 +/** 由当前 feature adapter 归一后的 SystemSettings UI 模型;不直接暴露 HTTP DTO。 */ +export interface SystemSettings { + /** 默认 AI 模型名称。 */ + ai_model?: string; + /** 全局 AI API 密钥。 */ + ai_api_key?: string; + /** 全局 AI API 密钥是否已在服务端配置。 */ + ai_api_key_configured?: boolean; + /** 全局 AI API 地址。 */ + ai_api_url?: string; + /** 全局 AI 基础地址。 */ + ai_base_url?: string; + /** 系统默认回复文案。 */ + default_reply?: string; + /** 是否允许注册新用户。 */ + registration_enabled?: boolean; + /** 系统 SMTP 服务器地址。 */ + smtp_server?: string; + /** 系统 SMTP 密码是否已在服务端配置。 */ + smtp_password_configured?: boolean; + /** 服务端日志级别。 */ + log_level?: 'debug' | 'info' | 'warn' | 'error' | string; + /** 服务端日志格式。 */ + log_format?: 'text' | 'json' | string; + /** 续期日志保留天数。 */ + renewal_log_retention_days?: number; + /** 远程验证码服务地址。 */ + 'captcha.remote_service_url'?: string; + /** 远程验证码服务密钥。 */ + 'captcha.remote_secret_key'?: string; + /** 远程验证码服务密钥是否已在服务端配置。 */ + 'captcha.remote_secret_key_configured'?: boolean; + /** 远程验证码服务 Cookie 配置。 */ + 'captcha.remote_pass_cookies'?: boolean | string; + /** 兼容未来配置键的扩展字段。 */ + /** 未知设置键只能承载服务端声明的标量值,敏感值不进入该 UI 模型。 */ + [key: string]: string | number | boolean | undefined; +} + +/** 由当前 feature adapter 归一后的 AIReplySettings UI 模型;不直接暴露 HTTP DTO。 */ +export interface AIReplySettings { + /** 是否启用账号 AI 回复。 */ + ai_enabled: boolean; + /** 最大折扣比例。 */ + max_discount_percent: number; + /** 最大折扣金额。 */ + max_discount_amount?: number; + /** 最大砍价轮次。 */ + max_bargain_rounds: number; + /** 自定义提示词。 */ + custom_prompts: string; +} + +/** AI 模型发现接口的具名响应。 */ +/** 由当前 feature adapter 归一后的 AIModelsResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface AIModelsResponse { + /** 远端可用模型名称。 */ + models: string[]; +} + +/** 简单资源创建接口的数值主键响应。 */ +/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface MutationIDResponse { + /** 资源创建是否完成。 */ + success: boolean; + /** 新资源数值主键。 */ + id: number; +} + +/** 简单变更接口的统一成功响应。 */ +/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */ +export interface OperationResponse { + /** 操作是否完成。 */ + success: boolean; + /** 可选的操作说明。 */ + message?: string; + /** 操作完成后是否需要重新登录。 */ + requires_relogin?: boolean; +} diff --git a/frontend/app/features/settings/state.test.ts b/frontend/app/features/settings/state.test.ts index 8c44cc0..259f0b3 100644 --- a/frontend/app/features/settings/state.test.ts +++ b/frontend/app/features/settings/state.test.ts @@ -1,5 +1,5 @@ import { expect,test } from 'vitest'; -import type { SystemSettings } from '../../../shared/api-contract/settings'; +import type { SystemSettings } from './api'; import { buildPersistableSettings,createCredentials,createCredentialsMessage,isCurrentSettingsRequest,validateCredentials } from './state'; // settingsFixture 是覆盖敏感字段过滤和系统配置保留字段的最小草稿。 diff --git a/frontend/app/shell/AuthenticatedShell.test.tsx b/frontend/app/shell/AuthenticatedShell.test.tsx index cd14633..a0bf879 100644 --- a/frontend/app/shell/AuthenticatedShell.test.tsx +++ b/frontend/app/shell/AuthenticatedShell.test.tsx @@ -2,7 +2,7 @@ import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react'; import React from 'react'; import { afterEach,describe,expect,test,vi } from 'vitest'; -import type { Item } from '../../shared/api-contract/common'; +import type { Item } from '../features/items/api'; import type { DeliveryRuleTarget } from './AuthenticatedShell'; vi.mock('../features/dashboard/pages/Dashboard', /* dashboardMockFactory 提供仪表盘页面的轻量替身。 */ () => { diff --git a/frontend/shared/api-contract/accounts.ts b/frontend/shared/api-contract/accounts.ts index 7f2930c..71d1988 100644 --- a/frontend/shared/api-contract/accounts.ts +++ b/frontend/shared/api-contract/accounts.ts @@ -1,10 +1,7 @@ -// accounts 公开账号摘要、登录信息和账号任务相关传输契约。 -/** 账号 feature 使用的 HTTP 传输 DTO;业务页面必须经 feature adapter 转为 UI model。 */ -export type { - AIReplySettings, AIReplySettingsResponse, AccountBindingsResponse, AccountDetail, - AccountSummaryResponse, AccountTaskRunResponseEnvelope, AccountTaskSettings, - AccountTaskSettingsResponse, AccountTaskSummary, CookieProfileResponse, - CookieSettingsResponse, NotificationChannel, NotificationChannelResponse, - NotificationEventType, OperationResponse, QRLoginGenerateResponse, - QRLoginStatusResponse, QRLoginVerificationResponse, -} from './transport'; +// accounts 只公开 OpenAPI 生成的账号传输类型;UI 模型属于 accounts feature。 +import type { components } from './generated/schema'; + +/** AccountTransport 表示生成的非敏感账号响应,adapter 负责转换为页面模型。 */ +export type AccountTransport = components['schemas']['AccountDetailResponse']; +/** QRLoginStatusTransport 表示生成的二维码风控状态响应。 */ +export type QRLoginStatusTransport = components['schemas']['QRLoginStatusResponse']; diff --git a/frontend/shared/api-contract/admin.ts b/frontend/shared/api-contract/admin.ts index 7ef98ea..001ccc0 100644 --- a/frontend/shared/api-contract/admin.ts +++ b/frontend/shared/api-contract/admin.ts @@ -1,7 +1,7 @@ -// admin 公开管理员和统计相关传输契约。 -/** 管理与仪表盘 feature 使用的 HTTP 传输 DTO。 */ -export type { - DashboardStats, DashboardStatsResponse, Item, ItemListEnvelope, Order, - OrderAnalytics, OrderAnalyticsResponse, OrderStatus, ValidOrderResponse, - ValidOrdersResponse, -} from './transport'; +// admin 只公开 OpenAPI 生成的管理统计传输类型;仪表盘展示模型由 feature 维护。 +import type { components } from './generated/schema'; + +/** DashboardStatsTransport 表示生成的仪表盘概览响应。 */ +export type DashboardStatsTransport = components['schemas']['DashboardStatsResponse']; +/** AnalyticsTransport 表示生成的订单分析响应。 */ +export type AnalyticsTransport = components['schemas']['AnalyticsResponse']; diff --git a/frontend/shared/api-contract/automation.ts b/frontend/shared/api-contract/automation.ts index 3beaeb1..6ada8b4 100644 --- a/frontend/shared/api-contract/automation.ts +++ b/frontend/shared/api-contract/automation.ts @@ -1,9 +1,5 @@ -// automation 公开自动化规则、动作和异常相关传输契约。 -/** 自动化规则 feature 使用的 HTTP 传输 DTO。 */ -export type { - AccountDetail, AutomationAction, AutomationIssuesEnvelope, - AutomationRulePageResponse, AutomationRuleResponse, AutomationTriggerType, - Card, DefaultReply, DefaultReplyResponse, Item, KeywordTypedResponse, - MutationIDResponse, OperationResponse, PaginatedResponse, ReplyRule, - ShippingRule, ShippingVariant, -} from './transport'; +// automation 只公开 OpenAPI 生成的自动化传输类型;规则编辑模型属于 rules feature。 +import type { components } from './generated/schema'; + +/** OperationTransport 表示生成的通用成功响应。 */ +export type OperationTransport = components['schemas']['OperationResponse']; diff --git a/frontend/shared/api-contract/cards.ts b/frontend/shared/api-contract/cards.ts index b8e58ff..e70ce26 100644 --- a/frontend/shared/api-contract/cards.ts +++ b/frontend/shared/api-contract/cards.ts @@ -1,3 +1,5 @@ -// cards 公开卡片、批量卡片和卡片追加数据相关传输契约。 -/** 卡券 feature 使用的 HTTP 传输 DTO。 */ -export type { Card, CardAppendResponse, CardBatchResponse, MutationIDResponse, OperationResponse } from './transport'; +// cards 只公开 OpenAPI 生成的卡券传输类型;卡券展示模型属于 cards feature。 +import type { components } from './generated/schema'; + +/** CardTransport 表示生成的卡券响应。 */ +export type CardTransport = components['schemas']['CardResponse']; diff --git a/frontend/shared/api-contract/chat.ts b/frontend/shared/api-contract/chat.ts index 54bad2b..f1f7943 100644 --- a/frontend/shared/api-contract/chat.ts +++ b/frontend/shared/api-contract/chat.ts @@ -1,3 +1,9 @@ -// chat 公开会话、消息和已读状态相关传输契约。 -/** 聊天 feature 使用的 HTTP 传输 DTO。 */ -export type { AccountDetail, ChatMessage, ChatSession, OperationResponse } from './transport'; +// chat 只公开 OpenAPI 生成的聊天传输类型;聊天状态模型属于 chat feature。 +import type { components } from './generated/schema'; + +/** ChatMessageTransport 表示生成的单条聊天消息。 */ +export type ChatMessageTransport = components['schemas']['ChatMessage']; +/** ChatSessionTransport 表示生成的聊天会话摘要。 */ +export type ChatSessionTransport = components['schemas']['ChatSession']; +/** ChatWebSocketTransport 表示生成的 WebSocket 事件联合。 */ +export type ChatWebSocketTransport = components['schemas']['ChatWebSocketEvent']; diff --git a/frontend/shared/api-contract/client.ts b/frontend/shared/api-contract/client.ts index cde2ec3..14cb0de 100644 --- a/frontend/shared/api-contract/client.ts +++ b/frontend/shared/api-contract/client.ts @@ -56,6 +56,12 @@ const contractBaseUrl = typeof location === 'undefined' ? 'http://localhost' : l export const contractClient = createClient({ baseUrl: contractBaseUrl, fetch: contractFetch }); +// contractMultipartBody 将原生 FormData 作为对应 OpenAPI multipart operation 的运行时载荷交给客户端。 +// OpenAPI 3.1 的 binary 字段会生成 string 类型,而浏览器必须保留 FormData 边界和 File 对象;泛型仅由调用位置的生成 operation 请求体推导。 +export function contractMultipartBody(form: FormData): NonNullable { + return form as unknown as NonNullable; +} + // runContractRequest 执行类型化 operation,并恢复旧 client 的超时、取消和 ApiError 行为。 export async function runContractRequest( execute: (signal: AbortSignal) => Promise>, diff --git a/frontend/shared/api-contract/common.ts b/frontend/shared/api-contract/common.ts index df01690..de84c77 100644 --- a/frontend/shared/api-contract/common.ts +++ b/frontend/shared/api-contract/common.ts @@ -1,3 +1,5 @@ -// common 公开分页、错误和跨领域基础传输契约;具体 feature 应优先导入自己的领域模块。 -/** 跨 feature 的最小 HTTP 传输 DTO,不得承载领域专有类型。 */ -export type { ApiErrorResponse, Item, NotificationChannel, PaginatedResponse, SystemSettings } from './transport'; +// common 只公开跨 feature 的 OpenAPI 生成传输类型。 +import type { components } from './generated/schema'; + +/** ApiErrorResponse 表示统一错误 envelope,供共享 HTTP 运行时识别错误。 */ +export type ApiErrorResponse = components['schemas']['ErrorResponse']; diff --git a/frontend/shared/api-contract/generated/schema.ts b/frontend/shared/api-contract/generated/schema.ts index 641a62d..244477a 100644 --- a/frontend/shared/api-contract/generated/schema.ts +++ b/frontend/shared/api-contract/generated/schema.ts @@ -1813,6 +1813,320 @@ export interface components { ApiResponse: { success: boolean; }; + NotificationUncertainOutboxItem: { + id: number; + channel_id: number; + owner_user_id?: number; + event_type: string; + attempt_count: number; + uncertain_at: number; + has_error: boolean; + }; + NotificationUncertainOutboxResponse: { + total: number; + items: components["schemas"]["NotificationUncertainOutboxItem"][]; + }; + AutomationRunIssue: { + id: number; + cookie_id: string; + order_id: string; + trigger_type: string; + error_message: string; + issue_kind: string; + allowed_resolutions: string[]; + action_cursor: number; + sent_count: number; + updated_at: string; + }; + DeferredAutomationIssue: { + id: number; + cookie_id: string; + trigger_type: string; + error_message: string; + attempt_count: number; + updated_at: string; + }; + AutomationIssuesResponse: { + runs: components["schemas"]["AutomationRunIssue"][]; + pending_tasks: components["schemas"]["DeferredAutomationIssue"][]; + }; + AutomationActionResponse: { + id: number; + action_type: string; + card_id: number; + card_name: string; + delivery_count: number; + message_template: string; + delay_seconds: number; + config_json: string; + enabled: boolean; + sort_order: number; + }; + AutomationRuleResponse: { + id: number; + cookie_id: string; + item_id: string; + item_title: string; + name: string; + trigger_type: string; + enabled: boolean; + priority: number; + config_json: string; + actions: components["schemas"]["AutomationActionResponse"][]; + created_at: string; + updated_at: string; + }; + AutomationRuleListResponse: components["schemas"]["AutomationRuleResponse"][]; + AutomationRulePageResponse: { + success: boolean; + data: components["schemas"]["AutomationRuleResponse"][]; + total: number; + page: number; + page_size: number; + total_pages: number; + trigger_counts: { + [key: string]: number; + }; + }; + AutomationRulesResponse: components["schemas"]["AutomationRuleListResponse"] | components["schemas"]["AutomationRulePageResponse"]; + DefaultReplyResponse: { + cookie_id?: string; + enabled: boolean; + reply_content: string; + reply_image_url?: string; + reply_once: boolean; + }; + AccountTaskSettingsResponse: { + account_id: string; + auto_rate_enabled: boolean; + rate_content: string; + auto_polish_enabled: boolean; + polish_time: string; + last_rate_scan_at: number; + last_polish_date: string; + last_polish_at: number; + }; + AccountTaskSettingsUpdateRequest: { + account_id?: string; + auto_rate_enabled: boolean; + rate_content: string; + auto_polish_enabled: boolean; + polish_time: string; + last_rate_scan_at?: number; + last_polish_date?: string; + last_polish_at?: number; + }; + AccountTaskRunRequest: { + /** @enum {string} */ + task_type: "auto_rate" | "auto_polish"; + }; + AccountTaskRunResponse: { + id: number; + run_key: string; + account_id: string; + task_type: string; + target_id: string; + run_date: string; + status: string; + success_count: number; + failed_count: number; + error_message: string; + next_retry_at: number; + started_at: number; + finished_at: number; + }; + AccountTaskRunsResponse: { + runs: components["schemas"]["AccountTaskRunResponse"][]; + }; + AccountTaskSummaryResponse: { + /** @enum {string} */ + task_type: "auto_rate" | "auto_polish"; + found: number; + success: number; + failed: number; + skipped: number; + message?: string; + }; + AccountTaskRunResponseEnvelope: { + success: boolean; + summary: components["schemas"]["AccountTaskSummaryResponse"]; + }; + AccountBindingsResponse: { + cookie_id: string; + channel_ids: number[] | null; + }; + KeywordBasicResponse: { + keyword: string; + reply: string; + }; + KeywordBasicListResponse: components["schemas"]["KeywordBasicResponse"][]; + KeywordItemResponse: { + keyword: string; + reply: string; + item_id: string; + }; + KeywordItemListResponse: components["schemas"]["KeywordItemResponse"][]; + KeywordTypedResponse: { + id: number; + keyword: string; + reply: string; + item_id: string; + type: string; + image_url: string; + }; + KeywordTypedListResponse: components["schemas"]["KeywordTypedResponse"][]; + DefaultReplyMapResponse: { + [key: string]: components["schemas"]["DefaultReplyResponse"]; + }; + DefaultReplyListResponse: components["schemas"]["DefaultReplyResponse"][] | null; + ItemReplyResponse: { + item_id?: string; + cookie_id?: string; + reply_content: string; + }; + ItemReplyListResponse: components["schemas"]["ItemReplyResponse"][]; + AIReplySettingsResponse: { + cookie_id?: string; + ai_enabled: boolean; + max_discount_percent: number; + max_discount_amount: number; + max_bargain_rounds: number; + custom_prompts: string; + }; + AIReplySettingsMapResponse: { + [key: string]: components["schemas"]["AIReplySettingsResponse"]; + }; + SettingsResponse: { + [key: string]: string; + }; + UserSettingResponse: { + value: string; + }; + PublishCategoryResponse: { + cat_id: string; + cat_name: string; + channel_cat_id?: string; + tb_cat_id?: string; + }; + PublishCardAction: { + card_id: number; + delivery_count: number; + delay_seconds: number; + }; + PublishCardAutomation: { + enabled: boolean; + actions: components["schemas"]["PublishCardAction"][] | null; + }; + PublishReviewRequestConfig: { + enabled: boolean; + after_shipped_hours: number; + message: string; + max_attempts: number; + delay_seconds: number; + }; + PublishAutomationConfig: { + paid_delivery: components["schemas"]["PublishCardAutomation"]; + review_gift: components["schemas"]["PublishCardAutomation"]; + review_request: components["schemas"]["PublishReviewRequestConfig"]; + }; + PublishLocation: { + area?: string; + city?: string; + division_id?: string; + longitude?: number; + latitude?: number; + poi_id?: string; + poi_name?: string; + province?: string; + }; + ItemPublishBatchPreviewRow: { + row_no: number; + valid: boolean; + errors?: string[]; + cookie_id: string; + title: string; + price: string; + quantity: number; + images: string[]; + category: components["schemas"]["PublishCategoryResponse"]; + automation: components["schemas"]["PublishAutomationConfig"]; + }; + ItemPublishBatchPreviewResponse: { + success: boolean; + preview_id: string; + total: number; + valid: number; + invalid: number; + rows: components["schemas"]["ItemPublishBatchPreviewRow"][]; + }; + ItemPublishBatchRowResponse: { + id: number; + row_no: number; + cookie_id: string; + title: string; + price: string; + quantity: number; + images: string[]; + category: components["schemas"]["PublishCategoryResponse"]; + automation: components["schemas"]["PublishAutomationConfig"]; + status: string; + item_id: string; + item_url: string; + error_message: string; + failure_kind: string; + }; + ItemPublishBatchResponse: { + id: string; + status: string; + filename: string; + total: number; + success: number; + failed: number; + pending: number; + running: number; + retryable: number; + rows: components["schemas"]["ItemPublishBatchRowResponse"][]; + location: components["schemas"]["PublishLocation"]; + publish_interval_seconds: number; + created_at: string; + updated_at: string; + }; + ItemPublishBatchListResponse: { + batches: components["schemas"]["ItemPublishBatchResponse"][]; + }; + BatchIDResponse: { + success: boolean; + batch_id: string; + }; + BatchCancelResponse: { + success: boolean; + status: string; + }; + CategoryRecommendationResponse: { + success: boolean; + category: components["schemas"]["PublishCategoryResponse"]; + }; + CategoryRecommendationRequest: { + cookie_id: string; + keyword: string; + }; + ItemPublishBatchStartRequest: { + preview_id?: string; + batch_id?: string; + }; + ItemPublishBatchPreviewRequest: { + default_cookie_id: string; + /** Format: binary */ + file: string; + /** Format: binary */ + images_zip?: string; + fallback_category_id?: string; + fallback_category_name?: string; + fallback_channel_category_id?: string; + fallback_tb_category_id?: string; + location?: string; + publish_interval_seconds?: number; + }; HealthResponse: { /** @enum {string} */ status: "ok"; @@ -1828,6 +2142,47 @@ export interface components { /** @enum {string} */ database: "unavailable"; }; + CardMutationRequest: { + name?: string; + /** @enum {string} */ + type?: "api" | "text" | "data" | "image"; + api_config?: string; + text_content?: string; + data_content?: string; + image_url?: string; + description?: string; + enabled?: boolean; + delay_seconds?: number; + is_multi_spec?: boolean; + spec_name?: string; + spec_value?: string; + }; + CardAppendRequest: { + content: string; + }; + CardBatchResultResponse: { + row_no: number; + success: boolean; + id?: number; + name: string; + type?: string; + error?: string; + }; + CardBatchResponse: { + success: boolean; + total: number; + created: number; + failed: number; + rows: components["schemas"]["CardBatchResultResponse"][]; + }; + CardAppendResponse: { + success: boolean; + added: number; + }; + MutationIDResponse: { + success: boolean; + id: number; + }; CardResponse: { id: number; name: string; @@ -1859,6 +2214,18 @@ export interface components { multi_quantity_delivery: boolean; is_multi_qty_ship: boolean; }; + ItemListArrayResponse: components["schemas"]["ItemListResponse"][]; + ItemDetailResponse: { + cookie_id: string; + item_id: string; + item_title: string; + item_description: string; + item_category: string; + item_price: string; + item_detail: string; + is_multi_spec: boolean; + multi_quantity_delivery: boolean; + }; NotificationChannelResponse: { id: number; name: string; @@ -1867,6 +2234,25 @@ export interface components { enabled: boolean; user_id?: number; }; + NotificationChannelCreateRequest: { + name: string; + type: string; + config?: string; + event_types?: string; + enabled?: boolean; + }; + NotificationChannelPatchRequest: { + name?: string; + type?: string; + config?: string; + event_types?: string; + enabled?: boolean; + }; + NotificationBindingRequest: { + channel_ids?: number[]; + channel_id?: number; + enabled?: boolean; + }; NotificationBinding: { id: number; channel_id: number; @@ -2123,21 +2509,21 @@ export interface components { item_title: string; item_image: string; buyer_id: string; - spec_name: string; - spec_value: string; + spec_name?: string; + spec_value?: string; quantity: string; amount: string; order_status: string; status: string; cookie_id: string; - is_bargain: number; - system_shipped: boolean; - receiver_name: string; - receiver_phone: string; - receiver_address: string; - receiver_city: string; + is_bargain?: number; + system_shipped?: boolean; + receiver_name?: string; + receiver_phone?: string; + receiver_address?: string; + receiver_city?: string; created_at: string; - updated_at: string; + updated_at?: string; }; OrderListResponse: { success: boolean; @@ -2405,7 +2791,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AccountTaskSettingsResponse"]; }; }; /** @description 统一错误响应 */ @@ -2464,7 +2850,11 @@ export interface operations { }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["AccountTaskSettingsUpdateRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -2472,7 +2862,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AccountTaskSettingsResponse"]; }; }; /** @description 统一错误响应 */ @@ -2531,7 +2921,11 @@ export interface operations { }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["AccountTaskRunRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -2539,7 +2933,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AccountTaskRunResponseEnvelope"]; }; }; /** @description 统一错误响应 */ @@ -2606,7 +3000,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AccountTaskRunsResponse"]; }; }; /** @description 统一错误响应 */ @@ -3905,7 +4299,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AdminCookie"][]; + "application/json": components["schemas"]["AdminCookie"][] | null; }; }; /** @description 统一错误响应 */ @@ -3970,7 +4364,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["NotificationUncertainOutboxResponse"]; }; }; /** @description 统一错误响应 */ @@ -4569,7 +4963,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AutomationIssuesResponse"]; }; }; /** @description 统一错误响应 */ @@ -4708,7 +5102,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AutomationRulesResponse"]; }; }; /** @description 统一错误响应 */ @@ -5096,7 +5490,11 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["CardMutationRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -5104,7 +5502,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["MutationIDResponse"]; }; }; /** @description 统一错误响应 */ @@ -5171,7 +5569,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["CardResponse"]; }; }; /** @description 统一错误响应 */ @@ -5230,7 +5628,11 @@ export interface operations { }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["CardMutationRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -5364,7 +5766,11 @@ export interface operations { }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["CardAppendRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -5372,7 +5778,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["CardAppendResponse"]; }; }; /** @description 统一错误响应 */ @@ -5439,7 +5845,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["CardResponse"]; }; }; /** @description 统一错误响应 */ @@ -5496,7 +5902,14 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "multipart/form-data": { + /** Format: binary */ + file: string; + }; + }; + }; responses: { /** @description 成功 */ 200: { @@ -5504,7 +5917,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["CardBatchResponse"]; }; }; /** @description 统一错误响应 */ @@ -5990,7 +6403,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["DefaultReplyMapResponse"]; }; }; /** @description 统一错误响应 */ @@ -6057,7 +6470,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["DefaultReplyResponse"]; }; }; /** @description 统一错误响应 */ @@ -6323,7 +6736,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["DefaultReplyListResponse"]; }; }; /** @description 统一错误响应 */ @@ -6525,7 +6938,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ItemDetailResponse"]; }; }; /** @description 统一错误响应 */ @@ -6864,7 +7277,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ItemListArrayResponse"]; }; }; /** @description 统一错误响应 */ @@ -7126,7 +7539,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ItemPublishBatchListResponse"]; }; }; /** @description 统一错误响应 */ @@ -7183,7 +7596,11 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["ItemPublishBatchStartRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -7191,7 +7608,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["BatchIDResponse"]; }; }; /** @description 统一错误响应 */ @@ -7258,7 +7675,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ItemPublishBatchResponse"]; }; }; /** @description 统一错误响应 */ @@ -7325,7 +7742,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OperationResponse"]; }; }; /** @description 统一错误响应 */ @@ -7392,7 +7809,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["BatchCancelResponse"]; }; }; /** @description 统一错误响应 */ @@ -7526,7 +7943,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["BatchIDResponse"]; }; }; /** @description 统一错误响应 */ @@ -7583,7 +8000,11 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "multipart/form-data": components["schemas"]["ItemPublishBatchPreviewRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -7591,7 +8012,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ItemPublishBatchPreviewResponse"]; }; }; /** @description 统一错误响应 */ @@ -7648,7 +8069,11 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["CategoryRecommendationRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -7656,7 +8081,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["CategoryRecommendationResponse"]; }; }; /** @description 统一错误响应 */ @@ -7723,7 +8148,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AccountBindingsResponse"]; }; }; /** @description 统一错误响应 */ @@ -7782,7 +8207,11 @@ export interface operations { }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["NotificationBindingRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -7912,7 +8341,11 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["NotificationChannelCreateRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -7920,7 +8353,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["MutationIDResponse"]; }; }; /** @description 统一错误响应 */ @@ -7979,7 +8412,11 @@ export interface operations { }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["NotificationChannelPatchRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -8385,7 +8822,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["NotificationUncertainOutboxResponse"]; }; }; /** @description 统一错误响应 */ @@ -9139,15 +9576,6 @@ export interface operations { }; }; responses: { - /** @description 成功 */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": components["schemas"]["ApiResponse"]; - }; - }; /** @description 统一错误响应 */ 400: { headers: { @@ -9215,15 +9643,6 @@ export interface operations { }; requestBody?: never; responses: { - /** @description 成功 */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": components["schemas"]["ApiResponse"]; - }; - }; /** @description 统一错误响应 */ 400: { headers: { @@ -9291,15 +9710,6 @@ export interface operations { }; requestBody?: never; responses: { - /** @description 成功 */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": components["schemas"]["ApiResponse"]; - }; - }; /** @description 统一错误响应 */ 400: { headers: { @@ -9643,7 +10053,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["KeywordBasicListResponse"]; }; }; /** @description 统一错误响应 */ @@ -9845,7 +10255,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["KeywordItemListResponse"]; }; }; /** @description 统一错误响应 */ @@ -9979,7 +10389,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["KeywordTypedListResponse"]; }; }; /** @description 统一错误响应 */ @@ -10180,7 +10590,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ItemReplyListResponse"]; }; }; /** @description 统一错误响应 */ @@ -10248,7 +10658,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ItemReplyResponse"]; }; }; /** @description 统一错误响应 */ @@ -10384,7 +10794,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OperationResponse"]; }; }; /** @description 统一错误响应 */ @@ -10928,7 +11338,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AIReplySettingsMapResponse"]; }; }; /** @description 统一错误响应 */ @@ -10995,7 +11405,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AIReplySettingsResponse"]; }; }; /** @description 统一错误响应 */ @@ -11328,7 +11738,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["SettingsResponse"]; }; }; /** @description 统一错误响应 */ @@ -11393,7 +11803,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["SettingsResponse"]; }; }; /** @description 统一错误响应 */ @@ -11460,7 +11870,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["UserSettingResponse"]; }; }; /** @description 统一错误响应 */ diff --git a/frontend/shared/api-contract/items.ts b/frontend/shared/api-contract/items.ts index 5601cac..7e14a8f 100644 --- a/frontend/shared/api-contract/items.ts +++ b/frontend/shared/api-contract/items.ts @@ -1,8 +1,5 @@ -// items 公开商品、发布地点和批量发布相关传输契约。 -/** 商品 feature 使用的 HTTP 传输 DTO。 */ -export type { - AccountDetail, BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, - Item, ItemDetailResponse, ItemPublishBatchPreviewResponse, - ItemPublishBatchResponse, ItemPublishResponse, ItemSyncResponse, - OperationResponse, PublishLocation, ShippingRule, -} from './transport'; +// items 只公开 OpenAPI 生成的商品传输类型;发布和兼容模型属于 items feature。 +import type { components } from './generated/schema'; + +/** ItemTransport 表示生成的商品列表行。 */ +export type ItemTransport = components['schemas']['ItemListResponse']; diff --git a/frontend/shared/api-contract/notifications.ts b/frontend/shared/api-contract/notifications.ts index ecfcc49..8592bae 100644 --- a/frontend/shared/api-contract/notifications.ts +++ b/frontend/shared/api-contract/notifications.ts @@ -1,7 +1,7 @@ -// notifications 公开通知渠道、绑定和事件相关传输契约。 -/** 通知 feature 使用的 HTTP 传输 DTO。 */ -export type { - MutationIDResponse, NotificationBinding, NotificationChannel, - NotificationChannelResponse, NotificationChannelType, NotificationEventType, - OperationResponse, SystemSettings, -} from './transport'; +// notifications 只公开 OpenAPI 生成的通知传输类型;表单状态属于 notifications feature。 +import type { components } from './generated/schema'; + +/** NotificationChannelTransport 表示生成的通知渠道摘要。 */ +export type NotificationChannelTransport = components['schemas']['NotificationChannelResponse']; +/** NotificationBindingsTransport 表示生成的账号通知绑定映射。 */ +export type NotificationBindingsTransport = components['schemas']['NotificationBindingsByAccount']; diff --git a/frontend/shared/api-contract/orders.ts b/frontend/shared/api-contract/orders.ts index 23507ea..bc86d31 100644 --- a/frontend/shared/api-contract/orders.ts +++ b/frontend/shared/api-contract/orders.ts @@ -1,9 +1,7 @@ -// orders 公开订单、发货和订单刷新相关传输契约。 -/** 订单 feature 使用的 HTTP 传输 DTO。 */ -export type { - AccountDetail, AdminStatsResponse, Item, OperationResponse, Order, - OrderBatchResponse, OrderDTOResponse, OrderDetailResponse, - OrderRefreshJobCancelResponse, OrderRefreshJobStartResponse, - OrderRefreshJobStatusResponse, OrderRefreshResponse, OrderSingleRefreshResponse, - OrderStatus, PaginatedResponse, -} from './transport'; +// orders 只公开 OpenAPI 生成的订单传输类型;订单 UI 模型属于 orders feature。 +import type { components } from './generated/schema'; + +/** OrderTransport 表示生成的订单行。 */ +export type OrderTransport = components['schemas']['OrderDTO']; +/** OrderRefreshTransport 表示生成的订单刷新结果。 */ +export type OrderRefreshTransport = components['schemas']['OrderRefreshResponse']; diff --git a/frontend/shared/api-contract/session.ts b/frontend/shared/api-contract/session.ts index 014b8ca..5871a67 100644 --- a/frontend/shared/api-contract/session.ts +++ b/frontend/shared/api-contract/session.ts @@ -1,3 +1,5 @@ -// session 公开登录、初始化和二维码会话相关传输契约。 -/** 会话 feature 使用的 HTTP 传输 DTO。 */ -export type { OperationResponse, SessionResponse } from './transport'; +// session 只公开 OpenAPI 生成的会话传输类型;页面会话状态属于 session feature。 +import type { components } from './generated/schema'; + +/** SessionTransport 表示生成的登录或初始化响应。 */ +export type SessionTransport = components['schemas']['SessionResponse']; diff --git a/frontend/shared/api-contract/settings.ts b/frontend/shared/api-contract/settings.ts index a54d85c..976095c 100644 --- a/frontend/shared/api-contract/settings.ts +++ b/frontend/shared/api-contract/settings.ts @@ -1,3 +1,7 @@ -// settings 公开系统、AI 和默认回复设置相关传输契约。 -/** 系统设置 feature 使用的 HTTP 传输 DTO。 */ -export type { AIModelsResponse, OperationResponse, SystemSettings } from './transport'; +// settings 只公开 OpenAPI 生成的设置传输类型;表单状态属于 settings feature。 +import type { components } from './generated/schema'; + +/** SystemSettingsTransport 表示受约束动态键的设置响应。 */ +export type SystemSettingsTransport = components['schemas']['SystemSettingsResponse']; +/** AIModelsTransport 表示生成的模型发现响应。 */ +export type AIModelsTransport = components['schemas']['AIModelsResponse']; diff --git a/frontend/shared/api-contract/transport.ts b/frontend/shared/api-contract/transport.ts deleted file mode 100644 index 9893b8b..0000000 --- a/frontend/shared/api-contract/transport.ts +++ /dev/null @@ -1,1655 +0,0 @@ - -export interface PaginatedResponse { - /** 表示查询是否成功。 */ - success: boolean; - /** 当前页数据。 */ - data: T[]; - /** 符合条件的总记录数。 */ - total: number; - /** 当前页码。 */ - page: number; - /** 每页记录数。 */ - page_size: number; - /** 总页数。 */ - total_pages: number; - /** 各触发类型的规则计数。 */ - trigger_counts?: Record; -} - -// Auth -/** 会话登录和首次初始化接口的具名响应。 */ -export interface SessionResponse { - /** 表示登录或初始化是否成功。 */ - success: boolean; - /** 登录成功后的会话 Token。 */ - token?: string; - /** 服务端返回的操作说明。 */ - message?: string; - /** 当前用户 ID。 */ - user_id?: number; - /** 当前用户名。 */ - username?: string; - /** 当前用户是否为管理员。 */ - is_admin?: boolean; -} - -/** 商品发布和发货地选择共用的只读地点契约。 */ -export interface PublishLocation { - /** 行政区划展示名称。 */ - area: string; - /** 城市展示名称。 */ - city: string; - /** 平台使用的行政区划标识。 */ - division_id: string; - /** 地点经度。 */ - longitude: number; - /** 地点纬度。 */ - latitude: number; - /** 平台兴趣点标识。 */ - poi_id: string; - /** 平台兴趣点展示名称。 */ - poi_name: string; - /** 省份展示名称。 */ - province: string; -} - -// Accounts -export interface AccountDetail { - /** 闲鱼账号稳定标识。 */ - id: string; - /** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */ - cookie_configured?: boolean; - /** 账号是否允许运行。 */ - enabled: boolean; - /** 是否自动确认订单。 */ - auto_confirm: boolean; - /** 用户为账号设置的备注。 */ - remark?: string; - /** 自动回复暂停时长,单位为分钟。 */ - pause_duration?: number; - /** 暂停结束时间的 Unix 秒。 */ - paused_until?: number; - /** 当前是否处于暂停状态。 */ - paused?: boolean; - // 登录信息 - /** 用于密码登录的闲鱼用户名。 */ - username?: string; - /** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */ - login_password_configured?: boolean; - /** 是否在密码登录时显示浏览器。 */ - show_browser?: boolean; - // Frontend helpers - /** 平台账号昵称。 */ - nickname?: string; - /** 平台账号头像地址。 */ - avatar_url?: string; - /** 资料刷新失败时的说明。 */ - profile_error?: string; - /** 当前账号运行状态。 */ - runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled'; - /** 当前运行状态的用户可见说明。 */ - runtime_message?: string; - /** 当前运行实例是否已连接。 */ - runtime_connected?: boolean; - /** 运行状态快照的更新时间。 */ - runtime_updated_at?: string; - // AI设置 - /** 是否启用账号 AI 回复。 */ - ai_enabled?: boolean; - /** 允许的最大折扣比例。 */ - max_discount_percent?: number; - /** 允许的最大折扣金额。 */ - max_discount_amount?: number; - /** 允许的最大砍价轮次。 */ - max_bargain_rounds?: number; - /** 账号自定义提示词。 */ - custom_prompts?: string; - // 账号级计划任务 - /** 是否启用自动评价。 */ - auto_rate_enabled?: boolean; - /** 自动评价使用的文案。 */ - rate_content?: string; - /** 是否启用每日擦亮。 */ - auto_polish_enabled?: boolean; - /** 每日擦亮执行时间。 */ - polish_time?: string; - /** 最近一次自动评价扫描时间。 */ - last_rate_scan_at?: number; - /** 最近一次擦亮日期。 */ - last_polish_date?: string; - /** 最近一次擦亮时间。 */ - last_polish_at?: number; -} - -export interface AccountTaskSettings { - /** 账号稳定标识。 */ - account_id: string; - /** 是否启用自动评价。 */ - auto_rate_enabled: boolean; - /** 自动评价文案。 */ - rate_content: string; - /** 是否启用每日擦亮。 */ - auto_polish_enabled: boolean; - /** 每日擦亮执行时间。 */ - polish_time: string; - /** 最近一次自动评价扫描时间。 */ - last_rate_scan_at?: number; - /** 最近一次擦亮日期。 */ - last_polish_date?: string; - /** 最近一次擦亮时间。 */ - last_polish_at?: number; -} - -export interface AccountTaskSummary { - /** 任务类型。 */ - task_type: 'auto_rate' | 'auto_polish'; - /** 发现的任务数量。 */ - found: number; - /** 成功处理的任务数量。 */ - success: number; - /** 处理失败的任务数量。 */ - failed: number; - /** 跳过的任务数量。 */ - skipped: number; - /** 批量处理结果说明。 */ - message?: string; -} - -export interface ChatSession { - /** 账号稳定标识。 */ - account_id: string; - /** 会话稳定标识。 */ - chat_id: string; - /** 买家平台标识。 */ - buyer_id: string; - /** 买家昵称。 */ - buyer_name: string; - /** 买家头像地址。 */ - buyer_avatar_url?: string; - /** 会话关联商品标识。 */ - item_id?: string; - /** 会话关联商品标题。 */ - item_title?: string; - /** 最近一条消息内容。 */ - last_message: string; - /** 最近一条消息的 Unix 秒时间戳。 */ - last_message_at: number; - /** 未读消息数量。 */ - unread_count: number; -} - -export interface ChatMessage { - /** 消息数据库主键。 */ - id: number; - /** 消息所属账号标识。 */ - account_id: string; - /** 消息所属会话标识。 */ - chat_id: string; - /** 平台消息去重键。 */ - message_key: string; - /** 消息方向。 */ - direction: 'incoming' | 'outgoing'; - /** 发送者平台标识。 */ - sender_id: string; - /** 发送者名称。 */ - sender_name: string; - /** 消息类型,system 表示平台通知或交易卡片。 */ - message_type: 'text' | 'image' | 'video' | 'system'; - /** 消息正文或媒体地址。 */ - content: string; - /** 消息发送状态。 */ - status: 'received' | 'sending' | 'sent' | 'failed'; - /** 平台已读状态;旧消息可能没有该字段。 */ - read_status?: number; - /** 平台确认已读的 Unix 秒时间戳;未确认时省略。 */ - read_at?: number; - /** 消息发送时间的 Unix 秒。 */ - sent_at: number; -} - -// Orders -export type OrderStatus = - | 'processing' - | 'pending_ship' - | 'shipped' - | 'completed' - | 'cancelled' - | 'refunding' - | 'unknown'; - -export interface Order { - /** 订单本地数据库主键。 */ - id: string; - /** 平台订单标识。 */ - order_id: string; - /** 订单所属账号标识。 */ - cookie_id: string; - /** 订单关联商品标识。 */ - item_id: string; - /** 商品标题。 */ - item_title?: string; - /** 商品图片地址。 */ - item_image?: string; - /** 商品价格文本。 */ - item_price?: string; - /** 买家平台标识。 */ - buyer_id: string; - /** 购买数量。 */ - quantity: number; - /** 订单金额文本。 */ - amount: string; - /** 前端归一化后的订单状态。 */ - status: OrderStatus; - /** 服务端原始订单状态。 */ - order_status?: OrderStatus; - /** 收货人姓名。 */ - receiver_name?: string; - /** 收货人电话。 */ - receiver_phone?: string; - /** 收货地址。 */ - receiver_address?: string; - /** 订单创建时间。 */ - created_at?: string; - /** 订单更新时间。 */ - updated_at?: string; -} - -// Cards -export interface Card { - /** 卡券组数值主键。 */ - id: number; - /** 卡券组名称。 */ - name: string; - /** 卡券组类型。 */ - type: 'api' | 'text' | 'data' | 'image'; - /** 卡券组说明。 */ - description?: string; - /** 卡券组是否启用。 */ - enabled: boolean; - // 文本类型 - text_content?: string; - // 批量数据类型 - data_content?: string; - // API 类型配置 - api_config?: { - /** API 卡券请求地址。 */ - url: string; - /** API 卡券请求方法。 */ - method: 'GET' | 'POST'; - /** API 请求超时时间。 */ - timeout?: number; - /** API 请求头 JSON。 */ - headers?: string; - /** API 请求参数 JSON。 */ - params?: string; - }; - // 图片类型 - /** 图片卡券地址。 */ - image_url?: string; - // 通用配置 - /** 卡券发送延迟秒数。 */ - delay_seconds?: number; - // 多规格配置 - /** 是否支持多规格。 */ - is_multi_spec?: boolean; - /** 规格名称。 */ - spec_name?: string; - /** 规格值。 */ - spec_value?: string; -} - -// Items -export interface Item { - /** 本地商品数据库主键。 */ - id: string | number; - /** 商品所属账号标识。 */ - cookie_id: string; - /** 平台商品标识。 */ - item_id: string; - /** 商品标题。 */ - item_title?: string; - /** 商品描述。 */ - item_description?: string; - /** 商品价格文本。 */ - item_price?: string; - /** 商品主图地址。 */ - item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes - /** 商品分类标识。 */ - item_category?: string; - /** 商品详情原始 JSON。 */ - item_detail?: string; - /** 是否启用多规格。 */ - is_multi_spec?: number | boolean; - /** 是否按数量发货。 */ - multi_quantity_delivery?: number | boolean; - /** 是否启用多数量发货兼容字段。 */ - is_multi_qty_ship?: number | boolean; -} - -export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout'; -export type AutomationActionType = 'confirm_shipment' | 'send_card' | 'send_text'; - -// Rules -export interface ShippingRule { - /** 规则标识。 */ - id: string; - /** 规则名称。 */ - name: string; - /** 规则触发类型。 */ - trigger_type: AutomationTriggerType; - /** 规则匹配关键词。 */ - item_keyword: string; // Legacy UI helper - /** 规则限定的账号标识。 */ - cookie_id?: string; - /** 规则限定的商品标识。 */ - item_id?: string; - /** 规则限定的商品标题。 */ - item_title?: string; - /** 首个发卡动作使用的卡券组 ID。 */ - card_group_id: number; // First send_card action card id - /** 首个发卡动作使用的卡券组名称。 */ - card_group_name?: string; // UI helper - /** 规则优先级。 */ - priority: number; - /** 规则是否启用。 */ - enabled: boolean; - /** 规则原始配置 JSON。 */ - config_json?: string; - /** 规则动作列表。 */ - actions: AutomationAction[]; - /** 规则规格变体列表。 */ - variants: ShippingVariant[]; -} - -export interface AutomationAction { - /** 动作标识。 */ - id?: string; - /** 动作类型。 */ - action_type: AutomationActionType; - /** 动作使用的卡券组 ID。 */ - card_id?: number; - /** 动作使用的卡券组名称。 */ - card_name?: string; - /** 本次发放数量。 */ - delivery_count?: number; - /** 文本消息模板。 */ - message_template?: string; - /** 动作延迟秒数。 */ - delay_seconds?: number; - /** 动作原始配置 JSON。 */ - config_json?: string; - /** 动作是否启用。 */ - enabled: boolean; - /** 动作排序序号。 */ - sort_order?: number; -} - -export interface ShippingVariant { - /** 规格变体标识。 */ - id?: string; - /** 规格名称。 */ - spec_name: string; - /** 规格值。 */ - spec_value: string; - /** 变体使用的卡券组 ID。 */ - card_id: number; - /** 变体使用的卡券组名称。 */ - card_name?: string; - /** 卡券类型。 */ - card_type?: Card['type']; - /** 变体发放数量。 */ - delivery_count: number; - /** 变体是否启用。 */ - enabled: boolean; - /** 是否覆盖动作级延迟。 */ - delay_override?: boolean; - /** 变体延迟秒数。 */ - delay_seconds?: number; - /** 变体原始配置 JSON。 */ - config_json?: string; -} - -export interface ReplyRule { - /** 回复规则标识。 */ - id: string; - /** 触发关键词。 */ - keyword: string; - /** 回复正文。 */ - reply_content: string; - /** 关键词匹配方式。 */ - match_type: 'exact' | 'fuzzy'; - /** 规则是否启用。 */ - enabled: boolean; - /** 规则限定的商品标识。 */ - item_id?: string; - /** 回复类型。 */ - type?: 'text' | 'image'; - /** 图片回复地址。 */ - image_url?: string; -} - -// Stats -export interface AdminStats { - /** 用户总数。 */ - total_users: number; - /** 账号总数。 */ - total_cookies: number; - /** 启用账号数。 */ - active_cookies: number; - /** 卡券组总数。 */ - total_cards: number; - /** 关键词规则总数。 */ - total_keywords: number; - /** 订单总数。 */ - total_orders: number; -} - -export interface DashboardStats { - /** 账号总数。 */ - total_cookies: number; - /** 启用账号数。 */ - active_cookies: number; - /** 卡券组总数。 */ - total_cards: number; - /** 关键词规则总数。 */ - total_keywords: number; - /** 订单总数。 */ - total_orders: number; - /** 可用卡券库存量。 */ - available_card_stock: number; -} - -export interface OrderAnalytics { - /** 收入汇总。 */ - revenue_stats: { - /** 总收入金额。 */ - total_amount: number; - /** 总订单数。 */ - total_orders: number; - }; - /** 按日期聚合的订单统计。 */ - daily_stats: Array<{ - /** 统计日期。 */ - date: string; - /** 当日订单金额。 */ - amount: number; - /** 当日订单数量。 */ - order_count: number; - }>; - /** 按商品聚合的订单统计。 */ - item_stats?: Array<{ - /** 商品标识。 */ - item_id: string; - /** 商品订单数。 */ - order_count: number; - /** 商品订单总金额。 */ - total_amount: number; - /** 商品订单平均金额。 */ - avg_amount: number; - }>; -} - -// Settings -export interface SystemSettings { - /** 默认 AI 模型名称。 */ - ai_model?: string; - /** 全局 AI API 密钥。 */ - ai_api_key?: string; - /** 全局 AI API 密钥是否已在服务端配置。 */ - ai_api_key_configured?: boolean; - /** 全局 AI API 地址。 */ - ai_api_url?: string; - /** 全局 AI 基础地址。 */ - ai_base_url?: string; - /** 系统默认回复文案。 */ - default_reply?: string; - /** 是否允许注册新用户。 */ - registration_enabled?: boolean; - /** 系统 SMTP 服务器地址。 */ - smtp_server?: string; - /** 系统 SMTP 密码是否已在服务端配置。 */ - smtp_password_configured?: boolean; - /** 服务端日志级别。 */ - log_level?: 'debug' | 'info' | 'warn' | 'error' | string; - /** 服务端日志格式。 */ - log_format?: 'text' | 'json' | string; - /** 续期日志保留天数。 */ - renewal_log_retention_days?: number; - /** 远程验证码服务地址。 */ - 'captcha.remote_service_url'?: string; - /** 远程验证码服务密钥。 */ - 'captcha.remote_secret_key'?: string; - /** 远程验证码服务密钥是否已在服务端配置。 */ - 'captcha.remote_secret_key_configured'?: boolean; - /** 远程验证码服务 Cookie 配置。 */ - 'captcha.remote_pass_cookies'?: boolean | string; - /** 兼容未来配置键的扩展字段。 */ - [key: string]: any; -} - -export interface AIReplySettings { - /** 是否启用账号 AI 回复。 */ - ai_enabled: boolean; - /** 最大折扣比例。 */ - max_discount_percent: number; - /** 最大折扣金额。 */ - max_discount_amount?: number; - /** 最大砍价轮次。 */ - max_bargain_rounds: number; - /** 自定义提示词。 */ - custom_prompts: string; -} - -// Default Reply -export interface DefaultReply { - /** 账号稳定标识。 */ - cookie_id: string; - /** 默认回复是否启用。 */ - enabled: boolean; - /** 默认回复正文。 */ - reply_content: string; - /** 是否对同一会话只回复一次。 */ - reply_once: boolean; - /** 默认图片回复地址。 */ - reply_image_url?: string; -} - -// 通知渠道 -export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email'; -export type NotificationEventType = - | 'account_offline' - | 'account_recovered' - | 'account_disabled' - | 'security_verification' - | 'token_renewal' - | 'delivery_result' - | 'system_error'; - -export interface NotificationChannel { - /** 通知渠道标识。 */ - id: string; - /** 通知渠道名称。 */ - name: string; - /** 通知渠道类型。 */ - type: NotificationChannelType; - /** 通知渠道配置。 */ - config: Record; - /** 渠道绑定的事件类型。 */ - event_types?: NotificationEventType[]; - /** 通知渠道是否启用。 */ - enabled: boolean; - /** 创建时间。 */ - created_at?: string; - /** 更新时间。 */ - updated_at?: string; -} - -/** 统一 HTTP 失败响应,客户端不再依赖 detail 或 msg 别名。 */ -export interface ApiErrorResponse { - /** 稳定的机器可读错误码。 */ - code: string; - /** 可直接展示的错误说明。 */ - message: string; - /** 可选的服务端请求追踪标识。 */ - request_id?: string; - /** 仅供恢复或审计使用的结构化附加信息。 */ - details?: Record; -} - -/** 账号列表接口返回的非敏感具名 DTO。 */ -export interface AccountSummaryResponse { - /** 闲鱼账号稳定标识。 */ - id: string; - /** 数据库中是否存在账号记录。 */ - has_cookie: boolean; - /** 账号是否允许运行。 */ - enabled: boolean; - /** 是否自动确认订单。 */ - auto_confirm: boolean; - /** 账号备注。 */ - remark: string; - /** 自动回复暂停时长,单位为分钟。 */ - pause_duration: number; - /** 暂停结束 Unix 秒。 */ - paused_until: number; - /** 当前是否仍处于暂停状态。 */ - paused: boolean; - /** 密码登录用户名。 */ - username: string; - /** 是否允许密码登录显示浏览器;兼容旧服务端的 0/1 字符串值。 */ - show_browser: boolean | number | string; - /** 平台昵称缓存。 */ - nickname: string; - /** 平台头像地址。 */ - avatar_url: string; - /** 最近一次成功登录方式。 */ - login_method: string; - /** 最近一次成功登录时间。 */ - last_login_at: number; - /** 资料刷新错误说明。 */ - profile_error: string; - /** 账号级 AI 回复开关。 */ - ai_enabled: boolean; - /** 自动评价计划开关。 */ - auto_rate_enabled: boolean; - /** 自动评价文案。 */ - rate_content: string; - /** 自动擦亮计划开关。 */ - auto_polish_enabled: boolean; - /** 自动擦亮本地时间。 */ - polish_time: string; - /** 最近一次自动评价扫描时间。 */ - last_rate_scan_at: number; - /** 最近一次自动擦亮日期。 */ - last_polish_date: string; - /** 最近一次自动擦亮时间。 */ - last_polish_at: number; -} - -/** 账号设置变更接口的具名成功响应。 */ -export interface CookieSettingsResponse { - /** 表示设置是否保存成功。 */ - success: boolean; - /** 暂停结束 Unix 秒。 */ - paused_until: number; - /** 表示账号当前是否暂停。 */ - paused: boolean; -} - -/** 账号资料刷新接口的具名响应。 */ -export interface CookieProfileResponse { - /** 表示资料刷新是否成功。 */ - success: boolean; - /** 账号稳定标识。 */ - id: string; - /** 平台账号昵称。 */ - nickname: string; - /** 平台账号头像地址。 */ - avatar_url: string; - /** 资料刷新错误说明。 */ - profile_error: string; -} - -/** 账号暂停时长查询接口的具名响应。 */ -export interface PauseDurationResponse { - /** 暂停时长,单位为分钟。 */ - pause_duration: number; - /** 暂停结束 Unix 秒。 */ - paused_until: number; - /** 表示账号当前是否暂停。 */ - paused: boolean; -} - -/** 单个本地商品详情接口的具名响应。 */ -export interface ItemDetailResponse { - /** 商品所属账号标识。 */ - cookie_id: string; - /** 平台商品标识。 */ - item_id: string; - /** 商品标题。 */ - item_title: string; - /** 商品描述。 */ - item_description: string; - /** 商品分类标识。 */ - item_category: string; - /** 商品价格文本。 */ - item_price: string; - /** 商品详情原始 JSON。 */ - item_detail: string; - /** 是否有多规格。 */ - is_multi_spec: boolean; - /** 是否按数量发货。 */ - multi_quantity_delivery: boolean; -} - -/** 商品发布接口的具名成功响应。 */ -export interface ItemPublishResponse { - /** 表示商品是否发布成功。 */ - success: boolean; - /** 发布结果说明。 */ - message: string; - /** 新商品的平台标识。 */ - item_id: string; - /** 新商品的平台详情地址。 */ - item_url: string; - /** 新商品主图地址。 */ - item_image: string; - /** 新商品标题。 */ - item_title: string; - /** 新商品价格文本。 */ - item_price: string; - /** 新商品库存数量。 */ - quantity: number; - /** 新商品分类标识。 */ - category_id: string; - /** 新商品分类名称。 */ - category_name: string; -} - -/** 商品全集同步接口的具名响应。 */ -export interface ItemSyncResponse { - /** 表示同步是否完成。 */ - success: boolean; - /** 同步结果说明。 */ - message: string; - /** 平台返回的商品总数。 */ - total_count: number; - /** 平台商品总页数。 */ - total_pages: number; - /** 本地保存的商品数量。 */ - saved_count: number; - /** 本地删除标记的商品数量。 */ - deleted_count: number; -} - -/** 商品分页同步接口的具名响应。 */ -export interface ItemPageSyncResponse { - /** 表示同步是否完成。 */ - success: boolean; - /** 同步结果说明。 */ - message: string; - /** 当前同步页码。 */ - page_number: number; - /** 当前同步页大小。 */ - page_size: number; - /** 当前页商品数量。 */ - current_count: number; - /** 本地保存的商品数量。 */ - saved_count: number; -} - -/** 订单详情接口返回的原始具名订单 DTO。 */ -export interface OrderDTOResponse { - /** 平台订单标识。 */ - order_id: string; - /** 关联商品标识。 */ - item_id: string; - /** 关联商品标题。 */ - item_title: string; - /** 关联商品图片地址。 */ - item_image: string; - /** 买家平台标识。 */ - buyer_id: string; - /** 商品规格名称。 */ - spec_name: string; - /** 商品规格值。 */ - spec_value: string; - /** 购买数量文本。 */ - quantity: string; - /** 实付金额文本。 */ - amount: string; - /** 归一化订单状态。 */ - order_status: string; - /** 兼容前端使用的订单状态别名。 */ - status: string; - /** 所属账号标识。 */ - cookie_id: string; - /** 是否议价订单。 */ - is_bargain: number; - /** 是否系统发货。 */ - system_shipped: boolean; - /** 收货人姓名。 */ - receiver_name: string; - /** 收货人电话。 */ - receiver_phone: string; - /** 收货地址。 */ - receiver_address: string; - /** 收货城市。 */ - receiver_city: string; - /** 创建时间。 */ - created_at: string; - /** 更新时间。 */ - updated_at: string; -} - -/** 订单详情接口的具名响应。 */ -export interface OrderDetailResponse extends OrderDTOResponse { - /** 表示查询是否完成。 */ - success: boolean; - /** 新版客户端读取的订单对象。 */ - data: OrderDTOResponse; -} - -/** 订单单条刷新返回的远端详情。 */ -export interface OrderRefreshDetailResponse { - /** 购买数量文本。 */ - quantity: string; - /** 商品规格名称。 */ - spec_name: string; - /** 商品规格值。 */ - spec_value: string; - /** 归一化订单状态。 */ - order_status: string; - /** 实付金额文本。 */ - amount: string; -} - -/** 订单单条刷新接口的具名响应。 */ -export interface OrderSingleRefreshResponse { - /** 表示刷新是否完成。 */ - success: boolean; - /** 刷新结果说明。 */ - message: string; - /** 刷新后的订单详情。 */ - order: OrderRefreshDetailResponse; -} - -/** 自动化规则动作的原始具名 DTO。 */ -export interface AutomationActionResponse { - /** 动作稳定标识。 */ - id: number; - /** 动作类型。 */ - action_type: string; - /** 关联卡券组标识。 */ - card_id: number; - /** 关联卡券组名称。 */ - card_name: string; - /** 发送数量。 */ - delivery_count: number; - /** 消息模板。 */ - message_template: string; - /** 延迟秒数。 */ - delay_seconds: number; - /** 扩展配置 JSON。 */ - config_json: string; - /** 是否启用。 */ - enabled: boolean; - /** 执行顺序。 */ - sort_order: number; -} - -/** 自动化规则的原始具名 DTO。 */ -export interface AutomationRuleResponse { - /** 规则稳定标识。 */ - id: number; - /** 所属账号标识。 */ - cookie_id: string; - /** 关联商品标识。 */ - item_id: string; - /** 关联商品标题。 */ - item_title: string; - /** 规则名称。 */ - name: string; - /** 触发类型。 */ - trigger_type: string; - /** 是否启用。 */ - enabled: boolean; - /** 规则优先级。 */ - priority: number; - /** 扩展配置 JSON。 */ - config_json: string; - /** 规则动作列表。 */ - actions: AutomationActionResponse[]; - /** 创建时间。 */ - created_at: string; - /** 更新时间。 */ - updated_at: string; -} - -/** 自动化规则分页接口的具名响应。 */ -export interface AutomationRulePageResponse { - /** 表示查询是否完成。 */ - success: boolean; - /** 当前页规则列表。 */ - data: AutomationRuleResponse[]; - /** 规则总数。 */ - total: number; - /** 当前页码。 */ - page: number; - /** 当前页大小。 */ - page_size: number; - /** 总页数。 */ - total_pages: number; - /** 各触发类型规则数量。 */ - trigger_counts: Record; -} - -/** 订单批量变更接口的具名响应。 */ -export interface OrderBatchResponse { - /** 表示批量操作是否存在部分失败。 */ - partial_failure: boolean; - /** 批量操作结果说明。 */ - message: string; - /** 订单总数,导入接口提供。 */ - total?: number; - /** 成功处理数量。 */ - success_count: number; - /** 失败处理数量。 */ - failed_count: number; - /** 逐订单兼容结果行。 */ - results: OrderBatchResult[]; -} - -/** 订单批量接口的逐订单结果行。 */ -export interface OrderBatchResult { - /** 订单平台标识。 */ - order_id?: string; - /** 订单动作状态:failed、succeeded 或 reconciliation_required。 */ - status?: 'failed' | 'succeeded' | 'reconciliation_required'; - /** 表示该订单是否处理成功。 */ - success?: boolean; - /** 该订单处理结果说明。 */ - message: string; - /** 兼容接口可能返回的账号标识。 */ - cookie_id?: string; - /** 待补偿记录标识。 */ - reconciliation_id?: string; - /** 本地状态或补偿记录写入警告。 */ - reconciliation_warning?: string; - /** 兼容接口可能返回的处理阶段。 */ - stage?: string; - /** 允许后端保留尚未结构化的扩展字段。 */ - [key: string]: unknown; -} - -/** 账号 AI 回复设置接口的具名响应。 */ -export interface AIReplySettingsResponse { - /** 账号稳定标识;默认配置响应可能省略。 */ - cookie_id?: string; - /** AI 回复是否启用。 */ - ai_enabled: boolean; - /** 最大折扣比例。 */ - max_discount_percent: number; - /** 最大折扣金额。 */ - max_discount_amount: number; - /** 最大砍价轮次。 */ - max_bargain_rounds: number; - /** 自定义提示词。 */ - custom_prompts: string; -} - -/** AI 模型发现接口的具名响应。 */ -export interface AIModelsResponse { - /** 远端可用模型名称。 */ - models: string[]; -} - -/** 单个用户设置查询接口的具名响应。 */ -export interface UserSettingResponse { - /** 设置值文本。 */ - value: string; -} - -/** 卡券批量创建接口的逐行结果。 */ -export interface CardBatchResult { - /** 表格中的原始行号。 */ - row_no: number; - /** 当前行是否创建成功。 */ - success: boolean; - /** 新建卡券组主键。 */ - id?: number; - /** 卡券组名称。 */ - name: string; - /** 卡券类型。 */ - type?: string; - /** 当前行失败原因。 */ - error?: string; -} - -/** 卡券批量创建接口的具名响应。 */ -export interface CardBatchResponse { - /** 批量处理流程是否完成。 */ - success: boolean; - /** 解析出的总行数。 */ - total: number; - /** 创建成功行数。 */ - created: number; - /** 创建失败行数。 */ - failed: number; - /** 逐行处理结果。 */ - rows: CardBatchResult[]; -} - -/** 卡券追加数据接口的具名响应。 */ -export interface CardAppendResponse { - /** 追加操作是否完成。 */ - success: boolean; - /** 实际追加数量。 */ - added: number; -} - -/** 通知绑定列表中的单条记录。 */ -export interface NotificationBinding { - /** 账号稳定标识,列表归一化后补充。 */ - cookie_id?: string; - /** 绑定记录主键。 */ - id?: number; - /** 通知渠道主键。 */ - channel_id: number; - /** 通知渠道名称。 */ - channel_name: string; - /** 绑定是否启用。 */ - enabled: boolean; -} - -/** 账号通知渠道绑定查询响应。 */ -export interface AccountBindingsResponse { - /** 账号稳定标识。 */ - cookie_id: string; - /** 已绑定通知渠道主键列表。 */ - channel_ids: number[]; -} - -/** 商品类目推荐接口的具名响应。 */ -export interface CategoryRecommendationResponse { - /** 类目推荐是否成功。 */ - success: boolean; - /** 推荐商品类目。 */ - category: { - /** 平台类目主键。 */ - cat_id: string; - /** 平台类目名称。 */ - cat_name: string; - /** 频道类目主键。 */ - channel_cat_id: string; - /** 淘宝类目主键。 */ - tb_cat_id?: string; - }; -} - -/** 商品批量发布预检逐行结果。 */ -export interface ItemPublishBatchPreviewRow { - /** 上传表格行号。 */ - row_no: number; - /** 当前行是否通过预检。 */ - valid: boolean; - /** 当前行校验错误列表。 */ - errors?: string[]; - /** 发布目标账号标识。 */ - cookie_id: string; - /** 商品标题。 */ - title: string; - /** 商品价格文本。 */ - price: string; - /** 商品库存数量。 */ - quantity: number; - /** 商品图片引用列表。 */ - images: string[]; - /** 商品发布类目。 */ - category: CategoryRecommendationResponse['category']; - /** 发布后自动化配置。 */ - automation?: Record; -} - -/** 商品批量发布预检响应。 */ -export interface ItemPublishBatchPreviewResponse { - /** 预检流程是否完成。 */ - success: boolean; - /** 后续启动发布使用的预检批次标识。 */ - preview_id: string; - /** 预检总行数。 */ - total: number; - /** 通过预检行数。 */ - valid: number; - /** 未通过预检行数。 */ - invalid: number; - /** 逐行预检结果。 */ - rows: ItemPublishBatchPreviewRow[]; -} - -/** 商品批量发布任务启动或重试响应。 */ -export interface BatchIDResponse { - /** 任务操作是否完成。 */ - success: boolean; - /** 商品批量任务标识。 */ - batch_id: string; -} - -/** 商品批量发布任务取消响应。 */ -export interface BatchCancelResponse { - /** 取消请求是否完成。 */ - success: boolean; - /** 取消后的任务状态。 */ - status: string; -} - -/** 商品批量发布任务逐行详情。 */ -export interface ItemPublishBatchRowResponse { - /** 明细行主键。 */ - id: number; - /** 导入表格行号。 */ - row_no: number; - /** 发布目标账号标识。 */ - cookie_id: string; - /** 商品标题。 */ - title: string; - /** 商品价格文本。 */ - price: string; - /** 商品库存数量。 */ - quantity: number; - /** 商品图片引用列表。 */ - images: string[]; - /** 商品发布类目。 */ - category: CategoryRecommendationResponse['category']; - /** 发布后自动化配置。 */ - automation: Record; - /** 明细行状态。 */ - status: string; - /** 发布成功后的平台商品标识。 */ - item_id: string; - /** 发布成功后的商品地址。 */ - item_url: string; - /** 明细行失败原因。 */ - error_message: string; - /** 明细行失败类型。 */ - failure_kind: string; -} - -/** 商品批量发布任务详情响应。 */ -export interface ItemPublishBatchResponse { - /** 批量任务标识。 */ - id: string; - /** 批量任务状态。 */ - status: string; - /** 原始上传文件名。 */ - filename: string; - /** 明细行总数。 */ - total: number; - /** 成功发布数量。 */ - success: number; - /** 失败数量。 */ - failed: number; - /** 待处理数量。 */ - pending: number; - /** 运行中数量。 */ - running: number; - /** 可重试数量。 */ - retryable: number; - /** 明细行结果。 */ - rows: ItemPublishBatchRowResponse[]; - /** 批次统一发货地。 */ - location?: Record; - /** 最终商品发布之间的最小间隔秒数。 */ - publish_interval_seconds?: number; - /** 创建时间。 */ - created_at: string; - /** 更新时间。 */ - updated_at: string; -} - -/** 商品批量发布任务列表响应。 */ -export interface ItemPublishBatchListResponse { - /** 当前用户的批量任务列表。 */ - batches: ItemPublishBatchResponse[]; -} - -/** 简单资源创建接口的数值主键响应。 */ -export interface MutationIDResponse { - /** 资源创建是否完成。 */ - success: boolean; - /** 新资源数值主键。 */ - id: number; -} - -/** 简单变更接口的统一成功响应。 */ -export interface OperationResponse { - /** 操作是否完成。 */ - success: boolean; - /** 可选的操作说明。 */ - message?: string; - /** 操作完成后是否需要重新登录。 */ - requires_relogin?: boolean; -} - -/** 通知渠道接口返回的原始具名 DTO。 */ -export interface NotificationChannelResponse { - /** 通知渠道主键。 */ - id: number; - /** 通知渠道名称。 */ - name: string; - /** 通知渠道类型。 */ - type: string; - /** 订阅事件类型 JSON 或兼容文本。 */ - event_types?: string; - /** 通知渠道是否启用。 */ - enabled: boolean; - /** 所属用户主键。 */ - user_id?: number; -} - -/** 卡券列表接口的兼容包装响应。 */ -export interface CardListResponse { - /** 当前用户卡券列表。 */ - cards: Card[]; -} - -/** 传统关键词列表项响应。 */ -export interface KeywordBasicResponse { - /** 匹配关键词。 */ - keyword: string; - /** 文字回复内容。 */ - reply: string; -} - -/** 带商品范围的关键词列表项响应。 */ -export interface KeywordItemResponse extends KeywordBasicResponse { - /** 限定的商品标识。 */ - item_id: string; -} - -/** 带类型和主键的关键词列表项响应。 */ -export interface KeywordTypedResponse extends KeywordItemResponse { - /** 关键词规则主键。 */ - id: number; - /** 回复类型。 */ - type: 'text' | 'image'; - /** 图片回复地址。 */ - image_url: string; -} - -/** 指定商品回复项响应。 */ -export interface ItemReplyResponse { - /** 商品平台标识。 */ - item_id?: string; - /** 账号稳定标识。 */ - cookie_id?: string; - /** 指定商品的回复内容。 */ - reply_content: string; -} - -/** 默认回复查询响应。 */ -export interface DefaultReplyResponse extends DefaultReply { - /** 账号稳定标识。 */ - cookie_id: string; -} - -/** 账号任务设置响应。 */ -export interface AccountTaskSettingsResponse { - /** 账号稳定标识。 */ - account_id: string; - /** 是否启用自动评价。 */ - auto_rate_enabled: boolean; - /** 自动评价文案。 */ - rate_content: string; - /** 是否启用自动擦亮。 */ - auto_polish_enabled: boolean; - /** 自动擦亮本地时间。 */ - polish_time: string; - /** 最近一次评价扫描时间。 */ - last_rate_scan_at: number; - /** 最近一次擦亮日期。 */ - last_polish_date: string; - /** 最近一次擦亮时间。 */ - last_polish_at: number; -} - -/** 账号任务执行记录响应。 */ -export interface AccountTaskRunResponse { - /** 任务执行记录主键。 */ - id: number; - /** 任务幂等键。 */ - run_key: string; - /** 账号稳定标识。 */ - account_id: string; - /** 任务类型。 */ - task_type: string; - /** 任务目标标识。 */ - target_id: string; - /** 任务业务日期。 */ - run_date: string; - /** 任务执行状态。 */ - status: string; - /** 任务成功数量。 */ - success_count: number; - /** 任务失败数量。 */ - failed_count: number; - /** 任务失败说明。 */ - error_message: string; - /** 下一次重试时间。 */ - next_retry_at: number; - /** 任务开始时间。 */ - started_at: number; - /** 任务完成时间。 */ - finished_at: number; -} - -/** 账号任务执行记录列表响应。 */ -export interface AccountTaskRunsResponse { - /** 当前账号的任务执行记录。 */ - runs: AccountTaskRunResponse[]; -} - -/** 手动执行账号任务的统计响应。 */ -export interface AccountTaskSummaryResponse extends AccountTaskSummary { - /** 任务结果说明。 */ - message?: string; -} - -/** 手动执行账号任务的成功响应。 */ -export interface AccountTaskRunResponseEnvelope { - /** 任务请求是否成功完成。 */ - success: boolean; - /** 账号任务执行统计。 */ - summary: AccountTaskSummaryResponse; -} - -/** 管理员用户列表项响应。 */ -export interface AdminUserResponse { - /** 用户主键。 */ - id: number; - /** 用户登录名。 */ - username: string; - /** 用户邮箱。 */ - email: string; - /** 用户是否启用。 */ - is_active: boolean; - /** 用户是否为管理员。 */ - is_admin: boolean; - /** 用户创建时间。 */ - created_at: string; - /** 用户拥有的账号数量。 */ - cookie_count: number; -} - -/** 管理员账号列表项响应。 */ -export interface AdminCookieResponse { - /** 账号稳定标识。 */ - id: string; - /** 账号所属用户主键。 */ - user_id: number; - /** 账号备注。 */ - remark: string; - /** 账号创建时间。 */ - created_at: string; - /** 账号所属用户名。 */ - owner: string; - /** 账号是否启用。 */ - enabled: boolean; -} - -/** 管理员全局统计响应。 */ -export interface AdminStatsResponse extends AdminStats {} - -/** 当前用户数据概览响应。 */ -export interface DashboardStatsResponse extends DashboardStats {} - -/** 订单收益统计响应。 */ -export interface AnalyticsRevenueStatsResponse { - /** 统计范围内的订单数。 */ - total_orders: number; - /** 统计范围内的订单总金额。 */ - total_amount: number; - /** 订单平均金额。 */ - avg_amount: number; - /** 买家数量。 */ - unique_buyers: number; - /** 商品数量。 */ - unique_items: number; -} - -/** 按日期聚合的订单统计响应。 */ -export interface AnalyticsDailyStatsResponse { - /** 用户本地日期。 */ - date: string; - /** 当天订单数。 */ - order_count: number; - /** 当天订单金额。 */ - amount: number; -} - -/** 按订单状态聚合的统计响应。 */ -export interface AnalyticsStatusStatsResponse { - /** 归一化后的订单状态。 */ - status: string; - /** 该状态订单数。 */ - count: number; - /** 该状态订单金额。 */ - amount: number; -} - -/** 按收货城市聚合的统计响应。 */ -export interface AnalyticsCityStatsResponse { - /** 收货城市。 */ - city: string; - /** 该城市订单数。 */ - order_count: number; - /** 该城市订单金额。 */ - total_amount: number; -} - -/** 按商品聚合的统计响应。 */ -export interface AnalyticsItemStatsResponse { - /** 商品平台标识。 */ - item_id: string; - /** 该商品订单数。 */ - order_count: number; - /** 该商品订单金额。 */ - total_amount: number; - /** 该商品订单平均金额。 */ - avg_amount: number; -} - -/** 订单分析接口响应。 */ -export interface OrderAnalyticsResponse { - /** 收益统计。 */ - revenue_stats: AnalyticsRevenueStatsResponse; - /** 按日统计。 */ - daily_stats: AnalyticsDailyStatsResponse[]; - /** 按状态统计。 */ - status_stats: AnalyticsStatusStatsResponse[]; - /** 按城市统计。 */ - city_stats: AnalyticsCityStatsResponse[]; - /** 按商品统计。 */ - item_stats: AnalyticsItemStatsResponse[]; -} - -/** 有效订单明细响应。 */ -export interface ValidOrderResponse { - /** 平台订单标识。 */ - order_id: string; - /** 商品平台标识。 */ - item_id: string; - /** 买家平台标识。 */ - buyer_id: string; - /** 商品标题。 */ - item_title: string; - /** 商品图片地址。 */ - item_image: string; - /** 订单数量文本。 */ - quantity: string; - /** 订单金额文本。 */ - amount: string; - /** 兼容保留的订单状态。 */ - order_status: string; - /** 归一化后的订单状态。 */ - status: string; - /** 订单所属账号标识。 */ - cookie_id: string; - /** 订单创建时间。 */ - created_at: string; -} - -/** 有效订单分页响应。 */ -export interface ValidOrdersResponse { - /** 当前页有效订单。 */ - orders: ValidOrderResponse[]; - /** 符合条件的订单总数。 */ - total: number; - /** 当前页码。 */ - page: number; - /** 当前页大小。 */ - page_size: number; - /** 是否还有未返回的订单。 */ - truncated: boolean; -} - -/** 扫码登录二维码生成响应。 */ -export interface QRLoginGenerateResponse { - /** 二维码是否生成成功。 */ - success: boolean; - /** 扫码登录会话标识。 */ - session_id: string; - /** 二维码图片地址。 */ - qr_code_url: string; - /** 可选的提示文本。 */ - message?: string; -} - -/** 二维码登录状态响应。 */ -export interface QRLoginStatusResponse { - /** 当前二维码会话状态。 */ - status: string; - /** 风控验证页面截图地址,在人脸二维码不可用时作为展示兜底。 */ - verification_screenshot?: string; - /** 闲鱼人脸风控验证二维码地址,验证页面优先展示。 */ - face_qr_url?: string; - /** 扫码登录会话标识。 */ - session_id?: string; - /** 持久化后的本地账号标识。 */ - account_id?: string; - /** 是否新建了本地账号。 */ - is_new_account?: boolean; - /** 状态提示文本。 */ - message?: string; - /** 兼容上游可能扩展的非敏感状态字段。 */ - [key: string]: unknown; -} - -/** 二维码验证完成响应。 */ -export interface QRLoginVerificationResponse { - /** 验证结果是否成功。 */ - success: boolean; - /** 平台账号标识。 */ - unb?: string; - /** 持久化后的本地账号标识。 */ - account_id?: string; - /** 是否新建了本地账号。 */ - is_new_account?: boolean; -} - -/** 订单列表刷新逐项结果。 */ -export interface OrderRefreshResultResponse { - /** 结果所属账号标识。 */ - cookie_id?: string; - /** 当前处理阶段。 */ - stage?: string; - /** 当前项是否处理成功。 */ - success: boolean; - /** 结果说明。 */ - message?: string; - /** 发现的新订单数量。 */ - discovered?: number; - /** 更新的订单数量。 */ - updated?: number; - /** 标记删除的订单数量。 */ - /** soft_deleted 表示该订单是否已被本次刷新标记为软删除。 */ - soft_deleted?: boolean; - /** 订单平台标识。 */ - order_id?: string; - /** 结果错误说明。 */ - error?: string; -} - -/** 订单列表刷新统计摘要。 */ -export interface OrderRefreshSummaryResponse { - /** 发现的新订单数量。 */ - discovered: number; - /** 订单列表更新数量。 */ - list_updated: number; - /** 标记删除数量。 */ - soft_deleted: number; - /** 需要补全详情的订单数量。 */ - detail_total: number; - /** 本次处理订单总数。 */ - total: number; - /** 状态发生变化数量。 */ - updated: number; - /** 状态未变化数量。 */ - no_change: number; - /** 刷新失败数量。 */ - failed: number; -} - -/** 订单列表刷新响应。 */ -export interface OrderRefreshResponse { - /** 是否存在部分失败。 */ - partial_failure: boolean; - /** 刷新结果说明。 */ - message: string; - /** 刷新统计摘要。 */ - summary: OrderRefreshSummaryResponse; - /** 逐项兼容结果。 */ - results: OrderRefreshResultResponse[]; -} - -/** 创建订单刷新后台任务的响应。 */ -export interface OrderRefreshJobStartResponse { - /** 任务是否创建成功。 */ - success: boolean; - /** 后台任务标识。 */ - job_id: string; - /** 任务当前状态。 */ - status: 'queued' | 'running'; -} - -/** 查询订单刷新后台任务的响应。 */ -export interface OrderRefreshJobStatusResponse { - /** 查询是否成功。 */ - success: boolean; - /** 后台任务标识。 */ - job_id: string; - /** 任务当前状态。 */ - status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; - /** 任务失败原因。 */ - error_message?: string; - /** 任务成功后的订单刷新结果。 */ - result?: OrderRefreshResponse; -} - -/** 取消订单刷新后台任务的响应。 */ -export interface OrderRefreshJobCancelResponse { - /** 取消命令是否成功应用。 */ - success: boolean; - /** 被取消的任务标识。 */ - job_id: string; - /** 取消后的任务状态。 */ - status: 'cancelled'; -} - -// ItemListEnvelope 是商品列表接口的兼容分页响应。 -export interface ItemListEnvelope { - /** items 是兼容分页响应中的商品列表。 */ - items?: Item[]; -} - -// AutomationIssuesEnvelope 是自动化异常接口的兼容响应。 -export interface AutomationIssuesEnvelope { - /** runs 是待处理的自动化运行记录。 */ - runs?: Array<{ - /** 记录标识。 */ - id: number; - /** 所属账号标识。 */ - cookie_id: string; - /** 所属订单标识。 */ - order_id: string; - /** 自动化触发类型。 */ - trigger_type: string; - /** 外部错误说明。 */ - error_message: string; - /** 异常类别。 */ - issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed'; - /** 允许的处理动作。 */ - allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>; - /** 当前动作游标。 */ - action_cursor: number; - /** 已发送数量。 */ - sent_count: number; - /** 更新时间。 */ - updated_at: string; - }>; - /** pending_tasks 是延迟自动化任务列表。 */ - pending_tasks?: Array<{ - /** 任务标识。 */ - id: number; - /** 所属账号标识。 */ - cookie_id: string; - /** 自动化触发类型。 */ - trigger_type: string; - /** 错误说明。 */ - error_message: string; - /** 当前重试次数。 */ - attempt_count: number; - /** 更新时间。 */ - updated_at: string; - }>; -} diff --git a/internal/server/chat_account_tasks_test.go b/internal/server/chat_account_tasks_test.go index 893fa12..82d9f9c 100644 --- a/internal/server/chat_account_tasks_test.go +++ b/internal/server/chat_account_tasks_test.go @@ -89,7 +89,7 @@ func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() // conn、err 用于本次流程后续判断的conn、err - conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/chat/ws", &websocket.DialOptions{HTTPHeader: header}) + conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/v1/chat/ws", &websocket.DialOptions{HTTPHeader: header}) if err != nil { t.Fatal(err) } diff --git a/internal/server/openapi_operation_coverage_test.go b/internal/server/openapi_operation_coverage_test.go new file mode 100644 index 0000000..feeb407 --- /dev/null +++ b/internal/server/openapi_operation_coverage_test.go @@ -0,0 +1,332 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "sort" + "strconv" + "strings" + "testing" + + "github.com/getkin/kin-openapi/openapi3" +) + +// TestOpenAPIOperationsHaveContractScenarios 从 OpenAPI operationId 自动生成最小请求,确保每个版本化 operation 都经过真实 Router 响应契约校验。 +func TestOpenAPIOperationsHaveContractScenarios(t *testing.T) { + // document 是唯一 OpenAPI 契约源的解析结果。 + document := loadOpenAPIContractForCoverage(t) + // operations 保存按路径和方法排序后的全部版本化 operation 场景。 + operations := collectOpenAPIOperations(document) + // operation 表示当前规范枚举的 operation 场景,副本用于闭包隔离。 + for _, operation := range operations { + // operation 是由 OpenAPI 文档直接枚举的当前测试场景,不允许手工名单遗漏。 + operation := operation + t.Run(operation.operation.OperationID, func(t *testing.T) { + // srv、_、cleanup 分别是当前 operation 独占的真实 Server、测试数据库和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是当前 operation 使用的完整 chi Router。 + handler := srv.Router() + // sessionCookie 是当前 operation 独占的管理员会话,避免删除或登出影响其他场景。 + sessionCookie := loginHelper(t, handler) + // request 是根据路径参数、必需查询参数和请求体 schema 生成的最小真实请求。 + request := newOpenAPICoverageRequest(t, operation.path, operation.method, operation.operation) + request.AddCookie(sessionCookie) + // recorder 捕获真实 Router 对当前 operation 的状态、响应头和响应体。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIResponse(t, request, recorder) + }) + } +} + +// openAPICoverageOperation 保存一个由 OpenAPI 路径、方法和 operationId 构成的自动测试场景。 +type openAPICoverageOperation struct { + // key 是方法和路径组成的稳定场景键。 + key string + // path 是 OpenAPI 路径模板。 + path string + // method 是小写 HTTP 方法。 + method string + // operation 是当前 operation 的完整契约定义。 + operation *openapi3.Operation +} + +// loadOpenAPIContractForCoverage 加载并校验自动 operation 覆盖测试使用的契约文档。 +func loadOpenAPIContractForCoverage(t *testing.T) *openapi3.T { + t.Helper() + // specPath 是从 Server 测试目录定位到唯一 OpenAPI 契约源的路径。 + specPath := filepath.Join("..", "..", "api", "openapi.yaml") + // document、loadErr 分别是解析后的契约文档和加载失败原因。 + document, loadErr := openapi3.NewLoader().LoadFromFile(specPath) + if loadErr != nil { + t.Fatalf("加载 OpenAPI 契约失败: %v", loadErr) + } + // validationErr 表示契约未满足 OpenAPI 语义约束的原因。 + if validationErr := document.Validate(context.Background()); validationErr != nil { + t.Fatalf("OpenAPI 契约无效: %v", validationErr) + } + return document +} + +// collectOpenAPIOperations 从规范自动收集全部版本化 operation,不维护独立路径或 DTO 名单。 +func collectOpenAPIOperations(document *openapi3.T) []openAPICoverageOperation { + // operations 保存待运行的所有 OpenAPI operation 场景。 + operations := make([]openAPICoverageOperation, 0) + // path 表示 OpenAPI 中登记的 HTTP 路径模板。 + for _, path := range document.Paths.Keys() { + // pathItem 是当前路径模板的 operation 集合。 + pathItem := document.Paths.Find(path) + // method 表示当前路径登记的 HTTP 动词;operation 表示其契约定义。 + for method, operation := range pathItem.Operations() { + // normalizedMethod 是用于排序和构造请求的标准小写方法。 + normalizedMethod := strings.ToLower(method) + operations = append(operations, openAPICoverageOperation{ + key: normalizedMethod + " " + path, + path: path, + method: normalizedMethod, + operation: operation, + }) + } + } + sort.Slice(operations, func(left, right int) bool { + // left、right 是待比较的场景下标,排序保证失败输出稳定。 + return operations[left].key < operations[right].key + }) + return operations +} + +// newOpenAPICoverageRequest 根据 operation 的参数和请求体 schema 生成真实 HTTP 请求。 +func newOpenAPICoverageRequest(t *testing.T, path string, method string, operation *openapi3.Operation) *http.Request { + t.Helper() + // resolvedPath 是将 OpenAPI 路径参数替换为可解析占位值后的 URL 路径。 + resolvedPath := path + // parameter 表示当前 operation 的路径参数定义。 + for _, parameter := range operation.Parameters { + // parameterValue 是当前路径或查询参数的最小稳定值。 + if parameter.Value == nil || parameter.Value.In != "path" { + continue + } + resolvedPath = strings.ReplaceAll(resolvedPath, "{"+parameter.Value.Name+"}", openAPIParameterValue(parameter.Value.Name, parameter.Value.Schema)) + } + // queryValues 保存规范声明的必需查询参数,避免自动场景依赖手工路径列表。 + queryValues := url.Values{} + // parameter 表示当前 operation 的查询参数定义。 + for _, parameter := range operation.Parameters { + // parameterValue 是当前参数引用解析后的值。 + parameterValue := parameter.Value + if parameterValue == nil || parameterValue.In != "query" || !parameterValue.Required { + continue + } + queryValues.Set(parameterValue.Name, openAPIParameterValue(parameterValue.Name, parameterValue.Schema)) + } + // encodedQuery 是将必需查询参数按 URL 规则编码后的字符串。 + if encodedQuery := queryValues.Encode(); encodedQuery != "" { + resolvedPath += "?" + encodedQuery + } + // body、contentType 分别是按请求体 schema 生成的载荷和媒体类型。 + body, contentType := openAPICoverageRequestBody(t, operation.RequestBody) + // request 是供真实 chi Router 执行的最小 HTTP 请求。 + request := httptest.NewRequest(strings.ToUpper(method), resolvedPath, bytes.NewReader(body)) + if contentType != "" { + request.Header.Set("Content-Type", contentType) + } + return request +} + +// openAPICoverageRequestBody 按 OpenAPI 请求体媒体类型生成 JSON 或 multipart 载荷。 +func openAPICoverageRequestBody(t *testing.T, requestBody *openapi3.RequestBodyRef) ([]byte, string) { + t.Helper() + if requestBody == nil || requestBody.Value == nil || len(requestBody.Value.Content) == 0 { + return nil, "" + } + // mediaType 是优先选择 JSON、其次 multipart、最后按稳定顺序选择的请求媒体类型。 + mediaType := "" + // candidate 表示请求体支持的一种媒体类型。 + for candidate := range requestBody.Value.Content { + if candidate == "application/json" { + mediaType = candidate + break + } + if mediaType == "" && strings.HasPrefix(candidate, "multipart/") { + mediaType = candidate + } + if mediaType == "" { + mediaType = candidate + } + } + if strings.HasPrefix(mediaType, "multipart/") { + // buffer、writer 分别保存 multipart 请求体和字段编码器。 + buffer := &bytes.Buffer{} + // writer 负责以边界格式编码最小 multipart 请求体。 + writer := multipart.NewWriter(buffer) + // closeErr 表示 multipart 编码器关闭并写入结尾边界时的错误。 + if closeErr := writer.Close(); closeErr != nil { + t.Fatalf("生成 multipart 契约请求失败: %v", closeErr) + } + return buffer.Bytes(), writer.FormDataContentType() + } + // mediaSchema 是当前媒体类型声明的 JSON schema。 + mediaSchema := requestBody.Value.Content[mediaType] + if mediaSchema == nil || mediaSchema.Schema == nil { + return []byte("{}"), mediaType + } + // payload 是依据 schema 已知字段递归生成的 JSON 值,主动覆盖可选输入字段的类型约束。 + payload := openAPICoverageRequestValue(mediaSchema.Schema) + // encoded、marshalErr 分别是 JSON 请求体和编码失败原因。 + encoded, marshalErr := json.Marshal(payload) + if marshalErr != nil { + t.Fatalf("生成 JSON 契约请求失败: %v", marshalErr) + } + return encoded, mediaType +} + +// openAPICoverageRequestValue 按请求 schema 生成包含全部已知属性的最小 JSON 值,避免可选 DTO 字段遗漏长期未被调用。 +func openAPICoverageRequestValue(schemaRef *openapi3.SchemaRef) any { + if schemaRef == nil || schemaRef.Value == nil { + return nil + } + // schema 是当前递归层的具体请求 schema 定义。 + schema := schemaRef.Value + if schema.Example != nil || schema.Default != nil || schema.Const != nil || len(schema.Enum) > 0 || len(schema.OneOf) > 0 || len(schema.AnyOf) > 0 { + return openAPICoverageValue(schemaRef) + } + if schema.Type == nil || len(*schema.Type) == 0 || (*schema.Type)[0] != "object" { + return openAPICoverageValue(schemaRef) + } + // propertyNames 保存按字典序生成的已知请求字段,保证失败输出和负载稳定。 + propertyNames := make([]string, 0, len(schema.Properties)) + // propertyName 表示当前 schema 中发现的请求属性名称。 + for propertyName := range schema.Properties { + propertyNames = append(propertyNames, propertyName) + } + sort.Strings(propertyNames) + // objectValue 保存所有已声明请求字段的递归最小值。 + objectValue := make(map[string]any, len(propertyNames)) + // propertyName 表示当前需要编码到请求 JSON 中的 schema 属性名称。 + for _, propertyName := range propertyNames { + // property 是当前请求字段的类型约束。 + property := schema.Properties[propertyName] + objectValue[propertyName] = openAPICoverageRequestValue(property) + } + return objectValue +} + +// openAPICoverageValue 按 schema 生成满足结构约束的最小 JSON 值。 +func openAPICoverageValue(schemaRef *openapi3.SchemaRef) any { + if schemaRef == nil || schemaRef.Value == nil { + return nil + } + // schema 是当前递归层的具体 schema 定义。 + schema := schemaRef.Value + if schema.Example != nil { + return schema.Example + } + if schema.Default != nil { + return schema.Default + } + if schema.Const != nil { + return schema.Const + } + if len(schema.Enum) > 0 { + return schema.Enum[0] + } + if len(schema.OneOf) > 0 { + return openAPICoverageValue(schema.OneOf[0]) + } + if len(schema.AnyOf) > 0 { + return openAPICoverageValue(schema.AnyOf[0]) + } + // schemaType 是当前 schema 的首个声明类型。 + schemaType := "" + if schema.Type != nil && len(*schema.Type) > 0 { + schemaType = (*schema.Type)[0] + } + switch schemaType { + case "object": + // objectValue 保存对象必需字段的递归结果。 + objectValue := make(map[string]any, len(schema.Required)) + // requiredName 表示当前对象必须生成的字段名称。 + for _, requiredName := range schema.Required { + // property 是必需字段的 schema 定义。 + property := schema.Properties[requiredName] + objectValue[requiredName] = openAPICoverageValue(property) + } + return objectValue + case "array": + if schema.Items == nil { + return []any{} + } + if schema.MinItems > 0 { + return []any{openAPICoverageValue(schema.Items)} + } + return []any{} + case "integer": + if schema.Min != nil { + return int64(*schema.Min) + } + return int64(1) + case "number": + if schema.Min != nil { + return *schema.Min + } + return float64(1) + case "boolean": + return true + default: + if schema.Format == "date-time" { + return "2026-01-01T00:00:00Z" + } + return "contract-test" + } +} + +// openAPIParameterValue 依据参数名称和 schema 生成可被 handler 解析的路径或查询值。 +func openAPIParameterValue(name string, schemaRef *openapi3.SchemaRef) string { + // normalizedName 是便于判断业务语义的参数名称。 + normalizedName := strings.ToLower(name) + switch { + case strings.Contains(normalizedName, "user_id"), strings.Contains(normalizedName, "card_id"), strings.Contains(normalizedName, "channel_id"): + return "999999" + case strings.Contains(normalizedName, "index"): + return "0" + case strings.Contains(normalizedName, "cookie"), strings.HasSuffix(normalizedName, "cid"), strings.Contains(normalizedName, "account"): + return "acc1" + case strings.Contains(normalizedName, "order"): + return "missing-order" + case strings.Contains(normalizedName, "session"): + return "missing-session" + case strings.Contains(normalizedName, "batch"): + return "missing-batch" + case strings.Contains(normalizedName, "job"): + return "missing-job" + case strings.Contains(normalizedName, "task"), strings.Contains(normalizedName, "run"), strings.Contains(normalizedName, "rule"): + return "missing-resource" + case strings.Contains(normalizedName, "item"): + return "missing-item" + case normalizedName == "key": + return "theme_color" + } + // value 是没有业务名称提示时按 schema 生成的通用参数值。 + value := openAPICoverageValue(schemaRef) + // typedValue 是按 OpenAPI 参数 schema 生成的具体基础类型值。 + switch typedValue := value.(type) { + case string: + return typedValue + case bool: + return strconv.FormatBool(typedValue) + case int64: + return strconv.FormatInt(typedValue, 10) + case float64: + return strconv.FormatFloat(typedValue, 'f', -1, 64) + default: + return fmt.Sprint(typedValue) + } +} diff --git a/internal/server/openapi_remaining_success_contract_test.go b/internal/server/openapi_remaining_success_contract_test.go new file mode 100644 index 0000000..216887f --- /dev/null +++ b/internal/server/openapi_remaining_success_contract_test.go @@ -0,0 +1,782 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/textproto" + "strconv" + "strings" + "testing" + "time" + + automationapp "xianyu-go/internal/application/automation" + chatapp "xianyu-go/internal/application/chat" + itemapp "xianyu-go/internal/application/items" + notificationsapp "xianyu-go/internal/application/notifications" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/mtop" + xrenew "xianyu-go/internal/xianyu/renew" +) + +// TestOpenAPIRemainingVersionedSuccessResponses 验证仍未被既有兼容测试触达的版本化本地成功响应。 +func TestOpenAPIRemainingVersionedSuccessResponses(t *testing.T) { + // t.Run 将相互独立的真实 Router 场景隔离,避免各自的数据库状态互相影响。 + t.Run("initialize", testOpenAPISessionInitializeSuccess) + t.Run("long-login", testOpenAPILongLoginSuccess) + t.Run("ai-models", testOpenAPIAIModelsSuccess) + t.Run("cards-batch", testOpenAPICardsBatchSuccess) + t.Run("chat-history-and-read", testOpenAPIChatHistoryAndReadSuccess) + t.Run("local-item-and-manual-ship", testOpenAPILocalItemAndManualShipSuccess) + t.Run("category-recommendation", testOpenAPIItemCategoryRecommendationSuccess) + t.Run("publish-batch-preview", testOpenAPIPublishBatchPreviewSuccess) + t.Run("uncertain-notifications", testOpenAPIUncertainNotificationSuccess) + t.Run("chat-send", testOpenAPIChatSendSuccess) + t.Run("item-sync", testOpenAPIItemSyncSuccess) + t.Run("item-publish", testOpenAPIItemPublishSuccess) + t.Run("batch-lifecycle", testOpenAPIBatchLifecycleSuccess) + t.Run("automation-resolve", testOpenAPIAutomationResolveSuccess) + t.Run("notification-test", testOpenAPINotificationChannelTestSuccess) + t.Run("account-task-run", testOpenAPIAccountTaskRunSuccess) +} + +// testOpenAPISessionInitializeSuccess 覆盖首次初始化的真实公开成功响应。 +func testOpenAPISessionInitializeSuccess(t *testing.T) { + // srv、_、cleanup 分别是未初始化服务、当前场景无需读取的存储和资源释放函数。 + srv, _, cleanup := newUninitializedTestServer(t) + defer cleanup() + // handler 是未经包装的真实 Router,初始化会在响应中写入会话 Cookie。 + handler := srv.Router() + // request 是提交首次管理员密码的版本化初始化请求。 + request := httptest.NewRequest(http.MethodPost, "/api/v1/session/initialize", strings.NewReader(`{"password":"initial-password"}`)) + request.Header.Set("Content-Type", "application/json") + // recorder 保存真实 handler 返回的状态、响应头和响应体。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) +} + +// testOpenAPILongLoginSuccess 覆盖长登录读取和开关更新的真实平台代理成功响应。 +func testOpenAPILongLoginSuccess(t *testing.T) { + // passport 是本地续期服务替身,仅提供真实 handler 所需的平台协议响应。 + passport := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { + // responseWriter、request 分别承载本地平台替身的响应和请求。 + responseWriter.Header().Add("Set-Cookie", "havana_lgc_exp=4102444800000; Domain=.goofish.com; Path=/; Secure") + if strings.Contains(request.URL.Path, "set") { + _, _ = responseWriter.Write([]byte(`{"data":{"success":true}}`)) + return + } + _, _ = responseWriter.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`)) + })) + defer passport.Close() + // srv、store、cleanup 分别是服务、用于准备浏览器 Cookie 快照的存储和资源释放函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + setTestCookieRenew(srv, xrenew.Service{HTTPClient: passport.Client(), QueryLoginSettingsURL: passport.URL + "/query", SetLoginSettingsURL: passport.URL + "/set"}) + // detail、detailErr 保存当前账号的加密凭证详情及读取错误。 + detail, detailErr := store.Cookies.GetDetails(context.Background(), "acc1") + if detailErr != nil { + t.Fatalf("读取长登录账号失败: %v", detailErr) + } + // metadata 保存带域名快照的凭证元数据,使真实续期适配器可调用本地平台替身。 + metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookierefresh.SnapshotFromCookieString(detail.Value, ".goofish.com")) + // updateErr 表示写入测试长登录 Cookie 快照失败。 + if updateErr := store.Cookies.UpdateRenewalCookie(context.Background(), "acc1", detail.Value, metadata, time.Now().Unix()); updateErr != nil { + t.Fatalf("准备长登录凭证快照失败: %v", updateErr) + } + // handler 是当前场景使用的真实版本化 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // requests 保存读取与写入长登录状态的两个版本化成功请求。 + requests := []*http.Request{ + httptest.NewRequest(http.MethodGet, "/api/v1/accounts/acc1/long-login", nil), + httptest.NewRequest(http.MethodPut, "/api/v1/accounts/acc1/long-login", strings.NewReader(`{"enabled":true}`)), + } + // request 是当前真实长登录请求。 + for _, request := range requests { + request.Header.Set("Content-Type", "application/json") + request.AddCookie(sessionCookie) + // recorder 保存当前请求的完整真实响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } +} + +// testOpenAPIAIModelsSuccess 覆盖 AI 模型代理的本地成功响应。 +func testOpenAPIAIModelsSuccess(t *testing.T) { + // modelServer 模拟兼容 OpenAI 的模型列表端点。 + modelServer := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { + // responseWriter、request 分别承载模型替身响应和请求;请求内容无需在本场景读取。 + responseWriter.Header().Set("Content-Type", "application/json") + _, _ = responseWriter.Write([]byte(`{"data":[{"id":"contract-model"}]}`)) + })) + defer modelServer.Close() + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是访问管理员模型代理所需的认证会话。 + sessionCookie := loginHelper(t, handler) + // request 是指向本地模型替身的版本化 AI 模型请求。 + request := httptest.NewRequest(http.MethodPost, "/api/v1/settings/ai-models", strings.NewReader(`{"base_url":"`+modelServer.URL+`","api_key":"test-key"}`)) + request.Header.Set("Content-Type", "application/json") + request.AddCookie(sessionCookie) + // recorder 保存真实代理成功响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) +} + +// testOpenAPICardsBatchSuccess 覆盖卡券 CSV 上传的真实 multipart 成功响应。 +func testOpenAPICardsBatchSuccess(t *testing.T) { + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是当前管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // body 保存上传 CSV 的 multipart 编码结果。 + var body bytes.Buffer + // writer 负责组装符合真实 handler 预期的 multipart 请求。 + writer := multipart.NewWriter(&body) + // file、fileErr 分别是 CSV 表单文件写入器及创建失败原因。 + file, fileErr := writer.CreateFormFile("file", "cards.csv") + if fileErr != nil { + t.Fatalf("创建卡券表单文件失败: %v", fileErr) + } + // writeErr 表示写入测试卡券 CSV 内容失败。 + if _, writeErr := io.WriteString(file, "name,type,content\n合同卡,text,serial-001\n"); writeErr != nil { + t.Fatalf("写入卡券 CSV 失败: %v", writeErr) + } + // closeErr 表示完成卡券 multipart 编码失败。 + if closeErr := writer.Close(); closeErr != nil { + t.Fatalf("关闭卡券 multipart 失败: %v", closeErr) + } + // request 是真实卡券批量上传请求。 + request := httptest.NewRequest(http.MethodPost, "/api/v1/cards/batch", &body) + request.Header.Set("Content-Type", writer.FormDataContentType()) + request.AddCookie(sessionCookie) + // recorder 保存批量创建的真实成功响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) +} + +// testOpenAPIChatHistoryAndReadSuccess 覆盖聊天消息查询与本地已读状态更新。 +func testOpenAPIChatHistoryAndReadSuccess(t *testing.T) { + // srv、store、cleanup 分别是启用聊天应用的服务、夹具存储和资源释放函数。 + srv, store, cleanup := newTestServerWithChat(t) + defer cleanup() + // saveErr 表示写入可查询聊天消息失败。 + _, _, saveErr := store.Chats.SaveMessage(context.Background(), db.ChatSession{CookieID: "acc1", ChatID: "chat-contract", BuyerID: "buyer-contract", BuyerName: "契约买家"}, db.ChatMessage{MessageKey: "message-contract", Direction: "incoming", SenderID: "buyer-contract", SenderName: "契约买家", MessageType: "text", Content: "契约消息", Status: "received", SentAt: 1}, true) + if saveErr != nil { + t.Fatalf("写入聊天夹具失败: %v", saveErr) + } + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是当前管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // requests 保存消息读取与已读更新的真实版本化请求。 + requests := []*http.Request{ + httptest.NewRequest(http.MethodGet, "/api/v1/chat/messages?account_id=acc1&chat_id=chat-contract", nil), + httptest.NewRequest(http.MethodPost, "/api/v1/chat/read", strings.NewReader(`{"account_id":"acc1","chat_id":"chat-contract"}`)), + } + // request 是当前待验证的聊天 HTTP 请求。 + for _, request := range requests { + request.Header.Set("Content-Type", "application/json") + request.AddCookie(sessionCookie) + // recorder 保存真实 handler 的成功响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } + // channelResult、channelErr 保存删除场景所需通知渠道的插入结果。 + channelResult, channelErr := store.DB.ExecContext(context.Background(), `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES ('contract-delete','webhook','{}',1,1)`) + if channelErr != nil { + t.Fatalf("创建删除通知渠道失败: %v", channelErr) + } + // channelID、channelIDErr 保存删除场景通知渠道主键及读取错误。 + channelID, channelIDErr := channelResult.LastInsertId() + if channelIDErr != nil { + t.Fatalf("读取删除通知渠道主键失败: %v", channelIDErr) + } + // notificationResult、notificationErr 保存待删除消息通知夹具的主键及插入结果。 + notificationResult, notificationErr := store.DB.ExecContext(context.Background(), `INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('acc1',?,1)`, channelID) + if notificationErr != nil { + t.Fatalf("创建消息通知夹具失败: %v", notificationErr) + } + // notificationID、notificationIDErr 保存消息通知主键及读取错误。 + notificationID, notificationIDErr := notificationResult.LastInsertId() + if notificationIDErr != nil { + t.Fatalf("读取消息通知主键失败: %v", notificationIDErr) + } + // deleteRequest 是删除单条消息通知的版本化请求。 + deleteRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/notifications/messages/"+strconv.FormatInt(notificationID, 10), nil) + deleteRequest.AddCookie(sessionCookie) + // deleteRecorder 保存删除响应。 + deleteRecorder := httptest.NewRecorder() + handler.ServeHTTP(deleteRecorder, deleteRequest) + assertOpenAPIRecordedSuccessResponse(t, deleteRequest, deleteRecorder) +} + +// testOpenAPILocalItemAndManualShipSuccess 覆盖无需平台请求的商品创建和状态型手动发货成功响应。 +func testOpenAPILocalItemAndManualShipSuccess(t *testing.T) { + // srv、store、cleanup 分别是服务、订单夹具存储和资源释放函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // seedErr 表示写入待发货订单夹具失败。 + _, seedErr := store.DB.ExecContext(context.Background(), `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id,chat_id) VALUES ('contract-manual-ship','contract-item','buyer-contract','2','acc1','chat-contract')`) + if seedErr != nil { + t.Fatalf("写入手动发货订单失败: %v", seedErr) + } + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是当前管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // requests 保存商品创建和状态型手动发货的版本化请求。 + requests := []*http.Request{ + httptest.NewRequest(http.MethodPost, "/api/v1/items/acc1", strings.NewReader(`{"item_id":"contract-created","item_title":"契约商品","item_price":"10.00"}`)), + httptest.NewRequest(http.MethodPost, "/api/v1/orders/manual-ship", strings.NewReader(`{"order_ids":["contract-manual-ship"],"ship_mode":"status_only"}`)), + } + // request 是当前待验证的本地资源请求。 + for _, request := range requests { + request.Header.Set("Content-Type", "application/json") + request.AddCookie(sessionCookie) + // recorder 保存当前请求的完整成功响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } +} + +// testOpenAPIItemCategoryRecommendationSuccess 覆盖商品类目推荐的本地 MTOP 成功响应。 +func testOpenAPIItemCategoryRecommendationSuccess(t *testing.T) { + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // client 是仅返回类目推荐结构的本地 MTOP 客户端。 + client := mtop.NewClient() + client.HTTPClient = &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) { + // request 是类目推荐的 MTOP 请求;本场景只需返回确定性成功数据。 + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"propertyId":"-10000","propertyName":"分类","valuesList":[{"catId":"5001","catName":"虚拟商品","channelCatId":"6001","isClicked":"1"}]}}]}}`)), Request: request}, nil + })} + setTestMTop(srv, client) + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是当前管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // request 是商品类目推荐的版本化请求。 + request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-categories/recommend", strings.NewReader(`{"cookie_id":"acc1","keyword":"资料"}`)) + request.Header.Set("Content-Type", "application/json") + request.AddCookie(sessionCookie) + // recorder 保存真实 handler 的成功响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) +} + +// testOpenAPIPublishBatchPreviewSuccess 覆盖批量发布预检的真实 multipart 成功响应。 +func testOpenAPIPublishBatchPreviewSuccess(t *testing.T) { + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是当前管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // body 保存预检上传的 multipart 编码结果。 + var body bytes.Buffer + // writer 负责组装真实预检入口需要的默认账号、CSV 和图片压缩包字段。 + writer := multipart.NewWriter(&body) + _ = writer.WriteField("default_cookie_id", "acc1") + _ = writer.WriteField("fallback_category_id", "5001") + _ = writer.WriteField("fallback_category_name", "虚拟商品") + _ = writer.WriteField("fallback_channel_category_id", "6001") + // csvFile、csvErr 分别是预检 CSV 文件写入器和创建错误。 + csvFile, csvErr := writer.CreateFormFile("file", "products.csv") + if csvErr != nil { + t.Fatalf("创建预检 CSV 失败: %v", csvErr) + } + // writeErr 表示写入测试预检 CSV 内容失败。 + if _, writeErr := io.WriteString(csvFile, "账号ID,标题,价格,库存,图片\nacc1,契约商品,12.50,1,\n"); writeErr != nil { + t.Fatalf("写入预检 CSV 失败: %v", writeErr) + } + // closeErr 表示完成预检 multipart 编码失败。 + if closeErr := writer.Close(); closeErr != nil { + t.Fatalf("关闭预检 multipart 失败: %v", closeErr) + } + // request 是批量发布预检的版本化上传请求。 + request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/preview", &body) + request.Header.Set("Content-Type", writer.FormDataContentType()) + request.AddCookie(sessionCookie) + // recorder 保存真实预检成功响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) +} + +// testOpenAPIUncertainNotificationSuccess 覆盖用户和管理员不确定通知摘要的真实成功响应。 +func testOpenAPIUncertainNotificationSuccess(t *testing.T) { + // srv、store、cleanup 分别是服务、通知夹具存储和资源释放函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // result、insertErr 分别是渠道插入结果和数据库错误。 + result, insertErr := store.DB.ExecContext(context.Background(), `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES ('contract','webhook','{}',1,1)`) + if insertErr != nil { + t.Fatalf("创建通知渠道失败: %v", insertErr) + } + // channelID、idErr 分别是渠道标识和读取主键错误。 + channelID, idErr := result.LastInsertId() + if idErr != nil { + t.Fatalf("读取通知渠道标识失败: %v", idErr) + } + // enqueueErr 表示写入 outbox 夹具失败。 + enqueueErr := store.Notifications.EnqueueOutbox(context.Background(), []db.NotificationOutboxInput{{ChannelID: channelID, EventType: "contract"}}) + if enqueueErr != nil { + t.Fatalf("写入通知 outbox 失败: %v", enqueueErr) + } + // claimed、claimErr 分别是被本地 worker 领取的 outbox 项和领取错误。 + claimed, claimErr := store.Notifications.ClaimOutbox(context.Background(), "contract-worker", time.Now(), 1) + if claimErr != nil || len(claimed) != 1 { + t.Fatalf("领取通知 outbox 失败: items=%+v err=%v", claimed, claimErr) + } + // marked、markErr 分别表示不确定状态是否写入及写入错误。 + if marked, markErr := store.Notifications.MarkOutboxUncertain(context.Background(), claimed[0].ID, "contract-worker", "contract-error"); markErr != nil || !marked { + t.Fatalf("标记不确定通知失败: marked=%v err=%v", marked, markErr) + } + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // requests 保存用户与管理员不确定通知列表请求。 + requests := []*http.Request{ + httptest.NewRequest(http.MethodGet, "/api/v1/notifications/outbox/uncertain?limit=10", nil), + httptest.NewRequest(http.MethodGet, "/api/v1/admin/notifications/outbox/uncertain?limit=10", nil), + } + // request 是当前待验证的不确定通知查询请求。 + for _, request := range requests { + request.AddCookie(sessionCookie) + // recorder 保存当前真实成功响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } +} + +// _ 使用 encoding/json 保持本文件与未来需解码的覆盖场景共用稳定依赖。 +var _ = json.Valid + +// testOpenAPIChatSendSuccess 使用最小聊天端口验证文字和图片成功响应的 HTTP 形状。 +func testOpenAPIChatSendSuccess(t *testing.T) { + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // srv.applications.chat 注入只返回确定性消息的测试端口,避免调用真实账号运行时。 + srv.applications.chat = contractChatPort{} + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // textRequest 是文字消息发送请求。 + textRequest := httptest.NewRequest(http.MethodPost, "/api/v1/chat/messages", strings.NewReader(`{"account_id":"acc1","chat_id":"chat","buyer_id":"buyer","text":"hello"}`)) + textRequest.Header.Set("Content-Type", "application/json") + textRequest.AddCookie(sessionCookie) + // textRecorder 保存文字发送响应。 + textRecorder := httptest.NewRecorder() + handler.ServeHTTP(textRecorder, textRequest) + assertOpenAPIRecordedSuccessResponse(t, textRequest, textRecorder) + // imageBody 保存图片发送请求的 multipart 内容。 + var imageBody bytes.Buffer + // imageWriter 负责写入图片发送字段。 + imageWriter := multipart.NewWriter(&imageBody) + _ = imageWriter.WriteField("account_id", "acc1") + _ = imageWriter.WriteField("chat_id", "chat") + _ = imageWriter.WriteField("buyer_id", "buyer") + // imageFile 是聊天图片表单文件。 + imageFile, imageErr := imageWriter.CreatePart(textproto.MIMEHeader{"Content-Disposition": []string{`form-data; name="image"; filename="chat.png"`}, "Content-Type": []string{"image/png"}}) + if imageErr != nil { + t.Fatalf("创建聊天图片失败: %v", imageErr) + } + _, _ = imageFile.Write([]byte{0x89, 0x50, 0x4e, 0x47}) + _ = imageWriter.Close() + // imageRequest 是图片发送版本化请求。 + imageRequest := httptest.NewRequest(http.MethodPost, "/api/v1/chat/images", &imageBody) + imageRequest.Header.Set("Content-Type", imageWriter.FormDataContentType()) + imageRequest.AddCookie(sessionCookie) + // imageRecorder 保存图片发送响应。 + imageRecorder := httptest.NewRecorder() + handler.ServeHTTP(imageRecorder, imageRequest) + assertOpenAPIRecordedSuccessResponse(t, imageRequest, imageRecorder) +} + +// testOpenAPIItemSyncSuccess 使用本地 MTOP 返回商品列表,验证全量和分页同步响应。 +func testOpenAPIItemSyncSuccess(t *testing.T) { + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // client 是返回最小有效商品卡片的本地 MTOP 客户端。 + client := mtop.NewClient() + client.HTTPClient = &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) { + // request 是同步请求;返回值只包含本地同步需要的非敏感商品字段。 + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"id":"sync-contract","title":"同步商品","priceInfo":{"price":"10.00","preText":"¥"},"picInfo":{"picUrl":"https://img.example/s.png"},"detailParams":{"itemId":"sync-contract"}}}]}}`)), Request: request}, nil + })} + setTestMTop(srv, client) + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // requests 保存全量和分页同步请求。 + requests := []*http.Request{ + httptest.NewRequest(http.MethodPost, "/api/v1/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1","page_size":10}`)), + httptest.NewRequest(http.MethodPost, "/api/v1/items/get-by-page", strings.NewReader(`{"cookie_id":"acc1","page_number":1,"page_size":10}`)), + } + // request 是当前同步请求。 + for _, request := range requests { + request.Header.Set("Content-Type", "application/json") + request.AddCookie(sessionCookie) + // recorder 保存真实同步响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } +} + +// testOpenAPIItemPublishSuccess 注入商品发布端口并验证 multipart 发布成功响应。 +func testOpenAPIItemPublishSuccess(t *testing.T) { + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + srv.applications.itemSinglePublish = contractItemPublishPort{} + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // body 保存发布接口要求的 multipart 字段。 + var body bytes.Buffer + // writer 负责组装发布表单。 + writer := multipart.NewWriter(&body) + _ = writer.WriteField("cookie_id", "acc1") + _ = writer.WriteField("title", "契约发布") + _ = writer.WriteField("price", "10.00") + _ = writer.WriteField("original_price", "10.00") + _ = writer.WriteField("quantity", "1") + // image 是发布图片表单写入器。 + image, imageErr := writer.CreatePart(textproto.MIMEHeader{"Content-Disposition": []string{`form-data; name="images"; filename="contract.png"`}, "Content-Type": []string{"image/png"}}) + if imageErr != nil { + t.Fatalf("创建发布图片失败: %v", imageErr) + } + _, _ = image.Write([]byte{0x89, 0x50, 0x4e, 0x47}) + _ = writer.Close() + // request 是真实版本化商品发布请求。 + request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish", &body) + request.Header.Set("Content-Type", writer.FormDataContentType()) + request.AddCookie(sessionCookie) + // recorder 保存真实发布响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) +} + +// testOpenAPIBatchLifecycleSuccess 通过预检批次覆盖批次查询、取消和删除成功响应。 +func testOpenAPIBatchLifecycleSuccess(t *testing.T) { + // srv、store、cleanup 分别是服务、批次状态夹具存储和资源释放函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // batchID 是真实预检批次标识。 + batchID := previewPublishBatch(t, handler, sessionCookie) + // requests 保存批次详情、取消和删除请求;取消后批次可安全删除。 + requests := []*http.Request{ + httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches/"+batchID, nil), + httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/"+batchID+"/cancel", nil), + httptest.NewRequest(http.MethodDelete, "/api/v1/items/publish-batches/"+batchID, nil), + } + // request 是当前批次生命周期请求。 + for _, request := range requests { + request.AddCookie(sessionCookie) + // recorder 保存当前批次成功响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } + // startBatchID 是另一条真实预检批次标识,专门覆盖启动 operation。 + startBatchID := previewPublishBatch(t, handler, sessionCookie) + // startRequest 是启动批量发布的版本化请求。 + startRequest := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches", strings.NewReader(`{"preview_id":"`+startBatchID+`"}`)) + startRequest.Header.Set("Content-Type", "application/json") + startRequest.AddCookie(sessionCookie) + // startRecorder 保存启动响应。 + startRecorder := httptest.NewRecorder() + handler.ServeHTTP(startRecorder, startRequest) + assertOpenAPIRecordedSuccessResponse(t, startRequest, startRecorder) + // retryBatchID 是预置为失败状态的批次标识,确保重试 operation 真实进入成功分支。 + retryBatchID := previewPublishBatch(t, handler, sessionCookie) + // updateErr 表示写入批次失败终态失败。 + if _, updateErr := store.DB.ExecContext(context.Background(), `UPDATE item_publish_batches SET status='failed',failed_count=1 WHERE id=?`, retryBatchID); updateErr != nil { + t.Fatalf("设置重试批次状态失败: %v", updateErr) + } + // updateErr 表示写入失败批次明细失败。 + if _, updateErr := store.DB.ExecContext(context.Background(), `UPDATE item_publish_batch_rows SET status='failed',error_message='contract failure' WHERE batch_id=?`, retryBatchID); updateErr != nil { + t.Fatalf("设置重试批次明细失败: %v", updateErr) + } + // retryRequest 是重试失败明细的版本化请求。 + retryRequest := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/"+retryBatchID+"/retry-failed", nil) + retryRequest.AddCookie(sessionCookie) + // retryRecorder 保存重试响应。 + retryRecorder := httptest.NewRecorder() + handler.ServeHTTP(retryRecorder, retryRequest) + assertOpenAPIRecordedSuccessResponse(t, retryRequest, retryRecorder) +} + +// testOpenAPIAutomationResolveSuccess 写入真实死信延期任务并验证人工处理成功响应。 +func testOpenAPIAutomationResolveSuccess(t *testing.T) { + // srv、store、cleanup 分别是服务、自动化夹具存储和资源释放函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // ruleResult、ruleErr 保存异常运行归属规则的插入结果。 + ruleResult, ruleErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_rules (user_id,cookie_id,name,trigger_type,enabled,config_json) VALUES (1,'acc1','contract-rule','order_paid',1,'{}')`) + if ruleErr != nil { + t.Fatalf("写入自动化规则失败: %v", ruleErr) + } + // ruleID、ruleIDErr 保存异常运行归属规则主键及读取错误。 + ruleID, ruleIDErr := ruleResult.LastInsertId() + if ruleIDErr != nil { + t.Fatalf("读取自动化规则主键失败: %v", ruleIDErr) + } + // runResult、runErr 保存待处理异常运行的插入结果。 + runResult, runErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_runs (rule_id,cookie_id,trigger_type,trigger_key,status,raw_event_json,error_message) VALUES (?,?,?,'contract-run','needs_review','{"AccountID":"acc1"}','contract failure')`, ruleID, "acc1", "order_paid") + if runErr != nil { + t.Fatalf("写入自动化异常运行失败: %v", runErr) + } + // runID、runIDErr 保存待处理异常运行主键及读取错误。 + runID, runIDErr := runResult.LastInsertId() + if runIDErr != nil { + t.Fatalf("读取自动化异常运行主键失败: %v", runIDErr) + } + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // runRequest 是取消异常运行的版本化请求。 + runRequest := httptest.NewRequest(http.MethodPost, "/api/v1/automation-runs/"+strconv.FormatInt(runID, 10)+"/resolve", strings.NewReader(`{"resolution":"cancel"}`)) + runRequest.Header.Set("Content-Type", "application/json") + runRequest.AddCookie(sessionCookie) + // runRecorder 保存异常运行处理响应。 + runRecorder := httptest.NewRecorder() + handler.ServeHTTP(runRecorder, runRequest) + assertOpenAPIRecordedSuccessResponse(t, runRequest, runRecorder) + // insertErr 表示写入死信延期任务失败。 + _, insertErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_pending_tasks (task_key,cookie_id,trigger_type,task_json,status,attempt_count,error_message) VALUES ('contract-task','acc1','contract','{}','dead_letter',3,'failed')`) + if insertErr != nil { + t.Fatalf("写入自动化死信任务失败: %v", insertErr) + } + // taskID 保存刚刚写入的延期任务主键。 + var taskID int64 + // scanErr 表示读取延期任务主键失败。 + if scanErr := store.DB.QueryRowContext(context.Background(), `SELECT id FROM automation_pending_tasks WHERE task_key='contract-task'`).Scan(&taskID); scanErr != nil { + t.Fatalf("读取自动化任务标识失败: %v", scanErr) + } + // request 是驳回延期任务的版本化请求。 + request := httptest.NewRequest(http.MethodPost, "/api/v1/automation-pending-tasks/"+strconv.FormatInt(taskID, 10)+"/resolve", strings.NewReader(`{"resolution":"dismiss"}`)) + request.Header.Set("Content-Type", "application/json") + request.AddCookie(sessionCookie) + // recorder 保存真实人工处理响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) +} + +// testOpenAPINotificationChannelTestSuccess 验证通知渠道测试的真实网络成功响应。 +func testOpenAPINotificationChannelTestSuccess(t *testing.T) { + // endpoint 是接收通知测试请求的本地 Webhook。 + endpoint := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { + responseWriter.WriteHeader(http.StatusNoContent) + })) + defer endpoint.Close() + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // srv.applications.notificationChannels 注入成功替身,避免测试依赖进程级通知器。 + srv.applications.notificationChannels = contractNotificationChannelsPort{} + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // createRequest 创建本地 Webhook 渠道。 + createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"契约Webhook","type":"webhook","config":"{\"url\":\"`+endpoint.URL+`\"}","enabled":true}`)) + createRequest.Header.Set("Content-Type", "application/json") + createRequest.AddCookie(sessionCookie) + // createRecorder 保存渠道创建响应。 + createRecorder := httptest.NewRecorder() + handler.ServeHTTP(createRecorder, createRequest) + assertOpenAPIRecordedSuccessResponse(t, createRequest, createRecorder) + // channelID 保存创建响应中的渠道主键。 + var created struct { + ID int64 `json:"id"` + } + // decodeErr 表示解析通知渠道创建响应失败。 + if decodeErr := json.Unmarshal(createRecorder.Body.Bytes(), &created); decodeErr != nil || created.ID <= 0 { + t.Fatalf("渠道创建响应无效: %s", createRecorder.Body.String()) + } + // testRequest 是调用渠道测试的版本化请求。 + testRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels/"+strconv.FormatInt(created.ID, 10)+"/test", nil) + testRequest.AddCookie(sessionCookie) + // testRecorder 保存渠道测试成功响应。 + testRecorder := httptest.NewRecorder() + handler.ServeHTTP(testRecorder, testRequest) + assertOpenAPIRecordedSuccessResponse(t, testRequest, testRecorder) +} + +// testOpenAPIAccountTaskRunSuccess 注入账号任务端口并验证手动运行响应。 +func testOpenAPIAccountTaskRunSuccess(t *testing.T) { + // srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + srv.applications.accountTasks = contractAccountTasksPort{} + // handler 是当前场景的真实 Router。 + handler := srv.Router() + // sessionCookie 是管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // request 是手动自动评价运行请求。 + request := httptest.NewRequest(http.MethodPost, "/api/v1/account-tasks/acc1/run", strings.NewReader(`{"task_type":"auto_rate"}`)) + request.Header.Set("Content-Type", "application/json") + request.AddCookie(sessionCookie) + // recorder 保存任务运行响应。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) +} + +// contractChatPort 是只返回确定性消息的聊天 HTTP 应用端口。 +type contractChatPort struct{} + +// SendingAvailable 报告测试端口支持文字发送。 +func (contractChatPort) SendingAvailable() bool { return true } + +// ImageUploadAvailable 报告测试端口支持图片上传。 +func (contractChatPort) ImageUploadAvailable() bool { return true } + +// Subscribe 返回空事件流,当前场景不验证 WebSocket。 +func (contractChatPort) Subscribe(context.Context, int64) (<-chan chatapp.Event, func(), error) { + return nil, func() {}, nil +} + +// RefreshConversations 返回空联系人页。 +func (contractChatPort) RefreshConversations(context.Context, string, int64, int) (chatapp.ConversationPage, error) { + return chatapp.ConversationPage{}, nil +} + +// RefreshHistory 返回不可用错误,使查询回退本地存储。 +func (contractChatPort) RefreshHistory(context.Context, string, string, int64, int, chatapp.Session) (chatapp.HistoryPage, error) { + return chatapp.HistoryPage{}, chatapp.ErrRefreshUnavailable +} + +// SendText 返回确定性外发消息。 +func (contractChatPort) SendText(context.Context, chatapp.OutgoingInput) (*chatapp.Message, error) { + return &chatapp.Message{AccountID: "acc1", ChatID: "chat", MessageKey: "contract-message", Direction: "outgoing", MessageType: "text", Content: "hello", Status: "sent"}, nil +} + +// SendImage 返回确定性外发图片消息。 +func (contractChatPort) SendImage(context.Context, chatapp.ImageInput) (*chatapp.Message, error) { + return &chatapp.Message{AccountID: "acc1", ChatID: "chat", MessageKey: "contract-image", Direction: "outgoing", MessageType: "image", Content: "https://img.example/i.png", Status: "sent"}, nil +} + +// ListStoredMessages 返回空消息页。 +func (contractChatPort) ListStoredMessages(context.Context, int64, string, string, int64, int) (chatapp.Page, error) { + return chatapp.Page{}, nil +} + +// ListSessions 返回空会话集合。 +func (contractChatPort) ListSessions(context.Context, int64, string, int) ([]chatapp.Session, error) { + return nil, nil +} + +// FindSession 返回空会话。 +func (contractChatPort) FindSession(context.Context, int64, string, string) (chatapp.Session, error) { + return chatapp.Session{}, nil +} + +// ResolveReadMessageID 返回有效测试平台消息标识。 +func (contractChatPort) ResolveReadMessageID(context.Context, string, string, string) string { + return "contract.PNM" +} + +// CleanupEmptySessions 在测试端口中无副作用。 +func (contractChatPort) CleanupEmptySessions(context.Context, string) error { return nil } + +// OwnsAccount 始终确认测试账号归属。 +func (contractChatPort) OwnsAccount(context.Context, int64, string) (bool, error) { return true, nil } + +// MarkRead 确认本地已读更新成功。 +func (contractChatPort) MarkRead(context.Context, int64, string, string) error { return nil } + +// ReportPlatformRead 确认平台已读上报成功。 +func (contractChatPort) ReportPlatformRead(context.Context, string, string, []map[string]any) error { + return nil +} + +// ResolveSessionIdentity 保持测试会话为空。 +func (contractChatPort) ResolveSessionIdentity(context.Context, chatapp.Session) (chatapp.Session, error) { + return chatapp.Session{}, nil +} + +// RefreshSessionIdentities 返回空会话集合。 +func (contractChatPort) RefreshSessionIdentities(context.Context, string, []chatapp.Session) ([]chatapp.Session, error) { + return nil, nil +} + +// contractItemPublishPort 是只返回确定性商品结果的单商品发布端口。 +type contractItemPublishPort struct{} + +// PublishSingle 返回确定性远端发布结果。 +func (contractItemPublishPort) PublishSingle(context.Context, itemapp.PublishInput) (itemapp.PublishOutcome, error) { + return itemapp.PublishOutcome{Result: &itemapp.PublishResult{ItemID: "contract-published", ItemURL: "https://item.example/contract", Title: "契约发布", PriceText: "10.00", Quantity: 1}}, nil +} + +// contractAccountTasksPort 是只返回确定性统计结果的账号任务端口。 +type contractAccountTasksPort struct{} + +// contractNotificationChannelsPort 是只覆盖渠道测试动作的通知渠道端口。 +type contractNotificationChannelsPort struct{ NotificationChannelsPort } + +// CreateChannel 返回固定渠道标识,使后续测试请求仍通过真实 HTTP handler。 +func (contractNotificationChannelsPort) CreateChannel(context.Context, int64, notificationsapp.ChannelInput) (int64, error) { + return 1, nil +} + +// TestChannel 将渠道测试视为已由本地替身成功发送。 +func (contractNotificationChannelsPort) TestChannel(context.Context, int64, int64, time.Time) error { + return nil +} + +// GetSettings 返回测试账号默认任务设置。 +func (contractAccountTasksPort) GetSettings(context.Context, string) (automationapp.AccountTaskSettings, error) { + return automationapp.AccountTaskSettings{CookieID: "acc1"}, nil +} + +// UpdateSettings 返回规范化后的测试设置。 +func (contractAccountTasksPort) UpdateSettings(context.Context, automationapp.AccountTaskSettings) (automationapp.AccountTaskSettings, error) { + return automationapp.AccountTaskSettings{CookieID: "acc1"}, nil +} + +// ListRuns 返回空运行记录。 +func (contractAccountTasksPort) ListRuns(context.Context, string, int) ([]automationapp.AccountTaskRun, error) { + return nil, nil +} + +// Run 返回包含一个成功动作的任务摘要。 +func (contractAccountTasksPort) Run(context.Context, string, string) (automationapp.TaskSummary, error) { + return automationapp.TaskSummary{TaskType: automationapp.TaskAutoRate, Success: 1}, nil +} diff --git a/internal/server/openapi_response_contract_test.go b/internal/server/openapi_response_contract_test.go index edc47f9..a442347 100644 --- a/internal/server/openapi_response_contract_test.go +++ b/internal/server/openapi_response_contract_test.go @@ -3,10 +3,13 @@ package server import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/http/httptest" "path/filepath" + "sort" + "strconv" "strings" "testing" @@ -15,6 +18,74 @@ import ( "github.com/getkin/kin-openapi/routers/legacy" ) +// TestOpenAPISuccessContractCoverage 从唯一 OpenAPI 文档自动枚举普通 operation,确认每个 operation 都有真实成功响应断言记录。 +func TestOpenAPISuccessContractCoverage(t *testing.T) { + // scenarios 是按领域组织的真实 Router 成功场景;覆盖集合由每次成功断言的 operationId 自动产生。 + scenarios := []struct { + // name 是失败输出使用的稳定领域名称。 + name string + // run 会执行该领域完整的真实 HTTP 成功场景。 + run func(*testing.T) + }{ + {name: "session-and-qr", run: TestOpenAPISessionAndQRResponses}, + {name: "accounts-and-system", run: TestOpenAPIAccountAndSystemResponses}, + {name: "query-chat-orders", run: TestOpenAPIQueryChatAndOrderResponses}, + {name: "items-and-cards", run: TestOpenAPIItemAndCardResponses}, + {name: "notifications", run: TestOpenAPINotificationResponses}, + {name: "versioned-session", run: TestVersionedSessionRoutesPreserveLegacyContracts}, + {name: "versioned-account", run: TestVersionedAccountRoutesPreserveLegacyContracts}, + {name: "versioned-account-credentials", run: TestVersionedAccountCredentialRoutesPreserveLegacyContracts}, + {name: "versioned-account-settings", run: TestVersionedAccountSettingsRoutesPreserveLegacyContracts}, + {name: "versioned-items", run: TestVersionedItemRoutesPreserveLegacyContracts}, + {name: "versioned-orders", run: TestVersionedOrderRoutesPreserveLegacyContracts}, + {name: "versioned-order-refresh", run: TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts}, + {name: "versioned-qr", run: TestVersionedQRLoginRoutesPreserveLegacyContracts}, + {name: "versioned-admin-analytics", run: TestVersionedAdminAnalyticsRoutesPreserveLegacyContracts}, + {name: "versioned-settings-cards-notifications", run: TestVersionedSettingsCardNotificationRoutesPreserveLegacyContracts}, + {name: "versioned-item-batches", run: TestVersionedItemBatchRoutesPreserveLegacyContracts}, + {name: "versioned-chat-tasks", run: TestVersionedChatTaskRoutesPreserveLegacyContracts}, + {name: "versioned-replies", run: TestVersionedReplyRoutesPreserveLegacyContracts}, + {name: "versioned-remaining", run: TestVersionedRemainingRoutesPreserveLegacyContracts}, + {name: "named-success", run: TestNamedSuccessResponseContracts}, + {name: "remaining-success", run: TestRemainingSuccessResponseContracts}, + {name: "settings-cards-notifications-batch", run: TestSettingsCardsNotificationsBatchContracts}, + {name: "dynamic-success", run: TestDynamicCompatibilitySuccessContracts}, + {name: "reply-and-account-task-success", run: TestReplyAndAccountTaskSuccessResponseContracts}, + {name: "analytics-admin-public-success", run: TestAnalyticsAdminAndPublicSuccessResponseContracts}, + {name: "local-resource-mutations", run: TestOpenAPILocalResourceMutationResponses}, + {name: "remaining-versioned-success", run: TestOpenAPIRemainingVersionedSuccessResponses}, + } + // scenario 是当前执行的领域真实响应场景。 + for _, scenario := range scenarios { + // scenario 保存当前领域成功场景,子测试名称和执行函数必须保持同一实例。 + scenario := scenario + t.Run(scenario.name, func(t *testing.T) { + scenario.run(t) + }) + } + // document 是包含全部 operation 的唯一 OpenAPI 契约。 + document := loadOpenAPIContractForCoverage(t) + // missing 保存未被成功断言记录、且没有显式特殊校验的 operationId。 + missing := make([]string, 0) + for _, path := range document.Paths.Keys() { // path 是当前 OpenAPI 路径模板。 + // pathItem 保存该模板下声明的全部 HTTP operation。 + pathItem := document.Paths.Find(path) + for _, operation := range pathItem.Operations() { // operation 是当前待检查的 OpenAPI operation。 + if openAPIContractSuccessExceptionKind(operation) != "" { + continue + } + // exists 表示该 operation 是否已由真实成功响应记录。 + if _, exists := openAPISuccessOperations.Load(operation.OperationID); !exists { + missing = append(missing, operation.OperationID) + } + } + } + sort.Strings(missing) + if len(missing) > 0 { + t.Fatalf("缺少真实成功响应契约场景: %s", strings.Join(missing, ", ")) + } +} + // assertOpenAPIResponse 验证真实 HTTP 响应的状态码、Content-Type 和 JSON 形状符合对应 OpenAPI operation。 func assertOpenAPIResponse(t *testing.T, request *http.Request, recorder *httptest.ResponseRecorder) { t.Helper() @@ -57,6 +128,9 @@ func assertOpenAPISuccessResponse(t *testing.T, request *http.Request, recorder t.Fatalf("成功响应状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String()) } assertOpenAPIResponse(t, request, recorder) + // operationID 是从请求匹配的 OpenAPI operation 读取的稳定成功覆盖键。 + operationID := openAPIOperationIDForRequest(t, request) + openAPISuccessOperations.Store(operationID, struct{}{}) } // assertOpenAPIExpectedStatusResponse 验证非 200 成功状态的真实响应仍符合 operation 契约。 @@ -66,6 +140,127 @@ func assertOpenAPIExpectedStatusResponse(t *testing.T, request *http.Request, re t.Fatalf("成功响应状态错误: %s %s status=%d want=%d body=%s", request.Method, request.URL.Path, recorder.Code, wantStatus, recorder.Body.String()) } assertOpenAPIResponse(t, request, recorder) + // operationID 是从请求匹配的 OpenAPI operation 读取的稳定成功覆盖键。 + operationID := openAPIOperationIDForRequest(t, request) + openAPISuccessOperations.Store(operationID, struct{}{}) +} + +// assertOpenAPIRecordedSuccessResponse 验证任意 2xx 的真实响应并记录其 operationId,供已存在的兼容路由成功场景复用。 +func assertOpenAPIRecordedSuccessResponse(t *testing.T, request *http.Request, recorder *httptest.ResponseRecorder) { + t.Helper() + if recorder.Code < http.StatusOK || recorder.Code >= http.StatusMultipleChoices { + t.Fatalf("成功响应状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String()) + } + assertOpenAPIResponse(t, request, recorder) + // operationID 是从成功请求匹配出的稳定 OpenAPI operation 标识。 + operationID := openAPIOperationIDForRequest(t, request) + openAPISuccessOperations.Store(operationID, struct{}{}) +} + +// contractRecordingHandler 在契约覆盖场景中捕获版本化成功响应,避免手写 operation 名单或遗漏断言点。 +func contractRecordingHandler(t *testing.T, next http.Handler) http.Handler { + t.Helper() + return http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { + // recorder 暂存真实 handler 的完整响应,便于校验后再复制到调用方记录器。 + recorder := httptest.NewRecorder() + next.ServeHTTP(recorder, request) + // headerValue 表示真实 handler 写出的响应头值集合。 + for headerName, headerValues := range recorder.Header() { + responseWriter.Header()[headerName] = append([]string(nil), headerValues...) + } + responseWriter.WriteHeader(recorder.Code) + _, _ = responseWriter.Write(recorder.Body.Bytes()) + if (strings.HasPrefix(request.URL.Path, "/api/v1/") || request.URL.Path == "/health") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices { + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } + }) +} + +// serveOpenAPISuccess 以真实 Router 执行一个本地可确定的版本化成功请求,并记录 operationId 作为覆盖证据。 +func serveOpenAPISuccess(t *testing.T, handler http.Handler, sessionCookie *http.Cookie, method string, path string, body string) *httptest.ResponseRecorder { + t.Helper() + // request 是本次本地资源生命周期操作使用的版本化 HTTP 请求。 + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if sessionCookie != nil { + request.AddCookie(sessionCookie) + } + // recorder 保存真实 handler 的完整成功响应,供 OpenAPI 校验和调用方业务断言复用。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + return recorder +} + +// openAPIOperationIDForRequest 使用唯一 OpenAPI 文档匹配真实请求并返回稳定 operationId。 +func openAPIOperationIDForRequest(t *testing.T, request *http.Request) string { + t.Helper() + // specPath 是从 Server 测试目录定位到唯一 OpenAPI 契约文件的路径。 + specPath := filepath.Join("..", "..", "api", "openapi.yaml") + // document、loadErr 分别是解析后的 OpenAPI 文档及其加载失败原因。 + document, loadErr := openapi3.NewLoader().LoadFromFile(specPath) + if loadErr != nil { + t.Fatalf("加载 OpenAPI 契约失败: %v", loadErr) + } + // router、routerErr 分别是请求与 operation 匹配使用的 OpenAPI 路由器及其构建错误。 + router, routerErr := legacy.NewRouter(document) + if routerErr != nil { + t.Fatalf("构建 OpenAPI 路由器失败: %v", routerErr) + } + // route、_、findErr 分别是匹配结果、无需读取的路径参数和路由匹配失败原因。 + route, _, findErr := router.FindRoute(request) + if findErr != nil || route.Operation == nil || route.Operation.OperationID == "" { + t.Fatalf("读取成功响应 operationId 失败: %s %s err=%v", request.Method, request.URL.Path, findErr) + } + return route.Operation.OperationID +} + +// openAPIContractSuccessExceptionKind 返回 operation 显式登记的特殊成功校验类别;普通 HTTP operation 返回空字符串。 +func openAPIContractSuccessExceptionKind(operation *openapi3.Operation) string { + if operation == nil || operation.Extensions == nil { + return "" + } + // exception、valid 分别是 YAML 扩展对象及其是否符合受限结构。 + exception, valid := operation.Extensions["x-contract-success-exception"].(map[string]any) + if !valid { + return "" + } + // kind、valid 分别是特殊校验类别及其是否为稳定字符串。 + kind, valid := exception["kind"].(string) + if !valid { + return "" + } + return kind +} + +// TestOpenAPIPasswordLoginDisabledOperations 验证永久关闭的密码登录 operation 真实返回 501 统一错误,而非伪造 2xx 成功响应。 +func TestOpenAPIPasswordLoginDisabledOperations(t *testing.T) { + // srv、_、cleanup 分别是独立测试 Server、无需直接读取的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是承载版本化密码登录关闭策略的真实 chi Router。 + handler := srv.Router() + // sessionCookie 是访问受保护密码登录 operation 所需的管理员认证会话。 + sessionCookie := loginHelper(t, handler) + // requests 保存三个永久关闭 operation 的最小版本化请求。 + requests := []*http.Request{ + httptest.NewRequest(http.MethodPost, "/api/v1/password-login", strings.NewReader(`{"account_id":"acc1","account":"contract-user","password":"not-a-real-secret"}`)), + httptest.NewRequest(http.MethodGet, "/api/v1/password-login/check/contract-session", nil), + httptest.NewRequest(http.MethodDelete, "/api/v1/password-login/cancel/contract-session", nil), + } + // request 是当前待验证的永久关闭版本化 operation 请求。 + for _, request := range requests { + request.AddCookie(sessionCookie) + // recorder 捕获关闭策略的实际 HTTP 状态、Content-Type 和统一错误响应体。 + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + if recorder.Code != http.StatusNotImplemented { + t.Fatalf("永久关闭 operation 状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String()) + } + assertOpenAPIResponse(t, request, recorder) + } } // TestOpenAPISessionAndQRResponses 验证阶段二会话与二维码主链路的成功、未认证和风控响应均满足真实契约。 @@ -333,6 +528,53 @@ func TestOpenAPIItemAndCardResponses(t *testing.T) { handler.ServeHTTP(cardsRecorder, cardsRequest) assertOpenAPISuccessResponse(t, cardsRequest, cardsRecorder) + // createCardRequest 是创建 data 卡券的版本化请求,供后续资源生命周期操作复用。 + createCardRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards", strings.NewReader(`{"name":"OpenAPI 数据卡","type":"data","data_content":"K1","enabled":true}`)) + createCardRequest.AddCookie(sessionCookie) + // createCardRecorder 捕获创建操作的具名数值主键响应。 + createCardRecorder := httptest.NewRecorder() + handler.ServeHTTP(createCardRecorder, createCardRequest) + assertOpenAPISuccessResponse(t, createCardRequest, createCardRecorder) + // createdCard 保存创建操作返回的数值主键,后续请求必须使用真实归属资源。 + var createdCard struct { + // ID 是本次生命周期中由服务端分配的卡券标识。 + ID int64 `json:"id"` + } + // decodeErr 表示无法从已校验响应中读取资源标识的失败原因。 + if decodeErr := json.Unmarshal(createCardRecorder.Body.Bytes(), &createdCard); decodeErr != nil || createdCard.ID <= 0 { + t.Fatalf("读取创建卡券标识失败: id=%d err=%v", createdCard.ID, decodeErr) + } + // cardID 是 URL 路径使用的真实卡券标识字符串。 + cardID := strconv.FormatInt(createdCard.ID, 10) + // getCardRequest 是读取刚创建资源详情的成功请求。 + getCardRequest := httptest.NewRequest(http.MethodGet, "/api/v1/cards/"+cardID, nil) + getCardRequest.AddCookie(sessionCookie) + // getCardRecorder 捕获详情 DTO,验证不再错误使用通用成功 envelope。 + getCardRecorder := httptest.NewRecorder() + handler.ServeHTTP(getCardRecorder, getCardRequest) + assertOpenAPISuccessResponse(t, getCardRequest, getCardRecorder) + // updateCardRequest 是更新同一 data 卡券的成功请求。 + updateCardRequest := httptest.NewRequest(http.MethodPut, "/api/v1/cards/"+cardID, strings.NewReader(`{"name":"OpenAPI 数据卡更新","type":"data","data_content":"K1","enabled":true}`)) + updateCardRequest.AddCookie(sessionCookie) + // updateCardRecorder 捕获更新成功响应。 + updateCardRecorder := httptest.NewRecorder() + handler.ServeHTTP(updateCardRecorder, updateCardRequest) + assertOpenAPISuccessResponse(t, updateCardRequest, updateCardRecorder) + // appendCardRequest 是为 data 卡券追加库存的成功请求。 + appendCardRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards/"+cardID+"/append-data", strings.NewReader(`{"content":"K2\nK3"}`)) + appendCardRequest.AddCookie(sessionCookie) + // appendCardRecorder 捕获追加数量响应。 + appendCardRecorder := httptest.NewRecorder() + handler.ServeHTTP(appendCardRecorder, appendCardRequest) + assertOpenAPISuccessResponse(t, appendCardRequest, appendCardRecorder) + // deleteCardRequest 是删除同一资源的成功请求,保证测试不依赖虚构路径参数。 + deleteCardRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/cards/"+cardID, nil) + deleteCardRequest.AddCookie(sessionCookie) + // deleteCardRecorder 捕获删除成功响应。 + deleteCardRecorder := httptest.NewRecorder() + handler.ServeHTTP(deleteCardRecorder, deleteCardRequest) + assertOpenAPISuccessResponse(t, deleteCardRequest, deleteCardRecorder) + // invalidUploadRequest 是缺失文件的卡券上传请求,必须返回统一错误 envelope。 invalidUploadRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards/batch", strings.NewReader("--openapi--\r\n")) invalidUploadRequest.Header.Set("Content-Type", "multipart/form-data; boundary=openapi") @@ -370,4 +612,37 @@ func TestOpenAPINotificationResponses(t *testing.T) { bindingsRecorder := httptest.NewRecorder() handler.ServeHTTP(bindingsRecorder, bindingsRequest) assertOpenAPISuccessResponse(t, bindingsRequest, bindingsRecorder) + + // createChannelRequest 是创建通知渠道的版本化成功请求,配置字段只使用测试占位值。 + createChannelRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"OpenAPI 渠道","type":"webhook","config":"{}","event_types":"[]","enabled":true}`)) + createChannelRequest.AddCookie(sessionCookie) + // createChannelRecorder 捕获渠道创建返回的数值主键。 + createChannelRecorder := httptest.NewRecorder() + handler.ServeHTTP(createChannelRecorder, createChannelRequest) + assertOpenAPISuccessResponse(t, createChannelRequest, createChannelRecorder) + // createdChannel 保存创建响应中的渠道标识。 + var createdChannel struct { + // ID 是服务端分配的通知渠道主键。 + ID int64 `json:"id"` + } + // channelDecodeErr 表示创建响应无法解析为具名主键 DTO 的失败原因。 + if channelDecodeErr := json.Unmarshal(createChannelRecorder.Body.Bytes(), &createdChannel); channelDecodeErr != nil || createdChannel.ID <= 0 { + t.Fatalf("读取通知渠道标识失败: id=%d err=%v", createdChannel.ID, channelDecodeErr) + } + // channelID 是通知渠道路径参数的稳定字符串形式。 + channelID := strconv.FormatInt(createdChannel.ID, 10) + // updateChannelRequest 是仅切换启用状态的部分更新成功请求。 + updateChannelRequest := httptest.NewRequest(http.MethodPut, "/api/v1/notifications/channels/"+channelID, strings.NewReader(`{"enabled":false}`)) + updateChannelRequest.AddCookie(sessionCookie) + // updateChannelRecorder 捕获渠道更新成功响应。 + updateChannelRecorder := httptest.NewRecorder() + handler.ServeHTTP(updateChannelRecorder, updateChannelRequest) + assertOpenAPISuccessResponse(t, updateChannelRequest, updateChannelRecorder) + // deleteChannelRequest 是删除已归属通知渠道的成功请求。 + deleteChannelRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/notifications/channels/"+channelID, nil) + deleteChannelRequest.AddCookie(sessionCookie) + // deleteChannelRecorder 捕获渠道删除成功响应。 + deleteChannelRecorder := httptest.NewRecorder() + handler.ServeHTTP(deleteChannelRecorder, deleteChannelRequest) + assertOpenAPISuccessResponse(t, deleteChannelRequest, deleteChannelRecorder) } diff --git a/internal/server/publish_batch_test.go b/internal/server/publish_batch_test.go index 4062a83..926e35c 100644 --- a/internal/server/publish_batch_test.go +++ b/internal/server/publish_batch_test.go @@ -735,6 +735,16 @@ func TestDownloadItemPublishBatchResultExportsRows(t *testing.T) { if !strings.HasPrefix(body, "\xEF\xBB\xBF") || !strings.Contains(body, "行号") || !strings.Contains(body, "商品A") || !strings.Contains(body, "item-1") { t.Fatalf("导出 CSV 内容异常: %q", body) } + // versionedRequest 使用与旧入口相同的已完成批次,验证二进制特殊 operation 的真实成功响应。 + versionedRequest := httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches/"+batchID+"/result.csv", nil) + versionedRequest.AddCookie(cookie) + // versionedRecorder 捕获版本化 CSV 下载响应,供 OpenAPI 校验状态、Content-Type 与二进制 schema。 + versionedRecorder := httptest.NewRecorder() + h.ServeHTTP(versionedRecorder, versionedRequest) + assertOpenAPISuccessResponse(t, versionedRequest, versionedRecorder) + if !strings.HasPrefix(versionedRecorder.Header().Get("Content-Type"), "text/csv") { + t.Fatalf("版本化 CSV Content-Type=%q", versionedRecorder.Header().Get("Content-Type")) + } } // TestDownloadItemPublishBatchResultHidesOtherUserBatch 验证结果下载不会泄露其他用户的批次存在性。 diff --git a/internal/server/success_api_contract_test.go b/internal/server/success_api_contract_test.go index be78bc9..545fd89 100644 --- a/internal/server/success_api_contract_test.go +++ b/internal/server/success_api_contract_test.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" "testing" + + "xianyu-go/internal/db" ) // TestNamedSuccessResponseContracts 验证认证、订单和聊天主链路使用具名成功响应 DTO。 @@ -16,7 +18,7 @@ func TestNamedSuccessResponseContracts(t *testing.T) { srv, _, cleanup := newTestServer(t) defer cleanup() // handler 是当前测试使用的完整路由树。 - handler := srv.Router() + handler := contractRecordingHandler(t, srv.Router()) // sessionCookie 是管理员登录后得到的认证会话。 sessionCookie := loginHelper(t, handler) @@ -84,7 +86,7 @@ func TestRemainingSuccessResponseContracts(t *testing.T) { srv, store, cleanup := newTestServer(t) defer cleanup() // handler 是当前测试使用的完整路由树。 - handler := srv.Router() + handler := contractRecordingHandler(t, srv.Router()) // sessionCookie 是管理员登录后得到的认证会话。 sessionCookie := loginHelper(t, handler) // seedErr 是测试商品写入模板数据库失败的原因。 @@ -195,12 +197,12 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { srv, _, cleanup := newTestServer(t) defer cleanup() // handler 是当前测试使用的完整路由树。 - handler := srv.Router() + handler := contractRecordingHandler(t, srv.Router()) // sessionCookie 是管理员登录后得到的认证会话。 sessionCookie := loginHelper(t, handler) // settingReq 是更新单个系统设置的请求。 - settingReq := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader(`{"value":"contract-blue"}`)) + settingReq := httptest.NewRequest(http.MethodPut, "/api/v1/settings/system/theme_color", strings.NewReader(`{"value":"contract-blue"}`)) settingReq.AddCookie(sessionCookie) // settingRecorder 是捕获系统设置响应的记录器。 settingRecorder := httptest.NewRecorder() @@ -219,7 +221,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { } // aiReq 是更新账号 AI 回复设置的请求。 - aiReq := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(`{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"契约测试"}`)) + aiReq := httptest.NewRequest(http.MethodPut, "/api/v1/settings/ai-reply/acc1", strings.NewReader(`{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"契约测试"}`)) aiReq.AddCookie(sessionCookie) // aiRecorder 是捕获账号 AI 设置响应的记录器。 aiRecorder := httptest.NewRecorder() @@ -238,7 +240,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { } // aiGetReq 是读取账号 AI 设置的请求。 - aiGetReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil) + aiGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/ai-reply/acc1", nil) aiGetReq.AddCookie(sessionCookie) // aiGetRecorder 是捕获账号 AI 设置查询响应的记录器。 aiGetRecorder := httptest.NewRecorder() @@ -257,7 +259,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { } // cardReq 是创建文本卡券组的请求。 - cardReq := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(`{"name":"契约卡","type":"text","text_content":"CARD","enabled":true}`)) + cardReq := httptest.NewRequest(http.MethodPost, "/api/v1/cards", strings.NewReader(`{"name":"契约卡","type":"text","text_content":"CARD","enabled":true}`)) cardReq.AddCookie(sessionCookie) // cardRecorder 是捕获卡券创建响应的记录器。 cardRecorder := httptest.NewRecorder() @@ -276,7 +278,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { } // cardGetReq 是读取卡券详情的请求。 - cardGetReq := httptest.NewRequest(http.MethodGet, "/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil) + cardGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil) cardGetReq.AddCookie(sessionCookie) // cardGetRecorder 是捕获卡券详情响应的记录器。 cardGetRecorder := httptest.NewRecorder() @@ -295,7 +297,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { } // channelReq 是创建通知渠道的请求。 - channelReq := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(`{"name":"契约通知","type":"bark","config":"{}","enabled":true}`)) + channelReq := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"契约通知","type":"bark","config":"{}","enabled":true}`)) channelReq.AddCookie(sessionCookie) // channelRecorder 是捕获通知渠道创建响应的记录器。 channelRecorder := httptest.NewRecorder() @@ -314,7 +316,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { } // bindingReq 是将通知渠道绑定到测试账号的请求。 - bindingReq := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(`{"channel_ids":[`+strconv.FormatInt(channelResponse.ID, 10)+`]}`)) + bindingReq := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/accounts/acc1/bindings", strings.NewReader(`{"channel_ids":[`+strconv.FormatInt(channelResponse.ID, 10)+`]}`)) bindingReq.AddCookie(sessionCookie) // bindingRecorder 是捕获通知绑定响应的记录器。 bindingRecorder := httptest.NewRecorder() @@ -333,7 +335,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { } // bindingGetReq 是读取账号通知绑定的请求。 - bindingGetReq := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil) + bindingGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/notifications/accounts/acc1/bindings", nil) bindingGetReq.AddCookie(sessionCookie) // bindingGetRecorder 是捕获账号通知绑定响应的记录器。 bindingGetRecorder := httptest.NewRecorder() @@ -352,7 +354,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) { } // batchReq 是读取商品批量任务列表的请求。 - batchReq := httptest.NewRequest(http.MethodGet, "/items/publish-batches?limit=10", nil) + batchReq := httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches?limit=10", nil) batchReq.AddCookie(sessionCookie) // batchRecorder 是捕获商品批量任务列表响应的记录器。 batchRecorder := httptest.NewRecorder() @@ -377,12 +379,12 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { srv, store, cleanup := newTestServer(t) defer cleanup() // handler 是当前测试使用的完整路由树。 - handler := srv.Router() + handler := contractRecordingHandler(t, srv.Router()) // sessionCookie 是管理员登录后得到的认证会话。 sessionCookie := loginHelper(t, handler) // publicSettingsReq 是读取公开系统设置的请求。 - publicSettingsReq := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil) + publicSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/system/public", nil) // publicSettingsRecorder 是捕获公开设置响应的记录器。 publicSettingsRecorder := httptest.NewRecorder() handler.ServeHTTP(publicSettingsRecorder, publicSettingsReq) @@ -400,7 +402,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { } // allSettingsReq 是读取管理员系统设置的请求。 - allSettingsReq := httptest.NewRequest(http.MethodGet, "/system-settings", nil) + allSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/system", nil) allSettingsReq.AddCookie(sessionCookie) // allSettingsRecorder 是捕获管理员设置响应的记录器。 allSettingsRecorder := httptest.NewRecorder() @@ -419,7 +421,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { } // userSettingsReq 是读取当前用户设置的请求。 - userSettingsReq := httptest.NewRequest(http.MethodGet, "/user-settings", nil) + userSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/user", nil) userSettingsReq.AddCookie(sessionCookie) // userSettingsRecorder 是捕获用户设置响应的记录器。 userSettingsRecorder := httptest.NewRecorder() @@ -450,7 +452,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { statusSessionID := "contract-qr" ownQRSession(t, srv, store, statusSessionID) // qrStatusReq 是读取二维码状态的请求。 - qrStatusReq := httptest.NewRequest(http.MethodGet, "/qr-login/check/"+statusSessionID, nil) + qrStatusReq := httptest.NewRequest(http.MethodGet, "/api/v1/qr-login/check/"+statusSessionID, nil) qrStatusReq.AddCookie(sessionCookie) // qrStatusRecorder 是捕获二维码状态响应的记录器。 qrStatusRecorder := httptest.NewRecorder() @@ -488,7 +490,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { completeSessionID := "contract-complete" ownQRSession(t, srv, store, completeSessionID) // completeReq 是提交二维码风控验证完成的请求。 - completeReq := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/"+completeSessionID, nil) + completeReq := httptest.NewRequest(http.MethodPost, "/api/v1/qr-login/complete-verification/"+completeSessionID, nil) completeReq.AddCookie(sessionCookie) // completeRecorder 是捕获验证完成响应的记录器。 completeRecorder := httptest.NewRecorder() @@ -513,12 +515,12 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) { srv, _, cleanup := newTestServer(t) defer cleanup() // handler 是当前测试使用的完整路由树。 - handler := srv.Router() + handler := contractRecordingHandler(t, srv.Router()) // sessionCookie 是管理员登录后得到的认证会话。 sessionCookie := loginHelper(t, handler) // keywordReq 是创建带商品范围关键词的请求。 - keywordReq := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(`{"keyword":"契约关键词","reply":"契约回复","item_id":"contract-item"}`)) + keywordReq := httptest.NewRequest(http.MethodPost, "/api/v1/reply-rules/acc1/items", strings.NewReader(`{"keyword":"契约关键词","reply":"契约回复","item_id":"contract-item"}`)) keywordReq.Header.Set("Content-Type", "application/json") keywordReq.AddCookie(sessionCookie) // keywordRecorder 是捕获关键词创建响应的记录器。 @@ -538,7 +540,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) { } // keywordListReq 是读取带类型关键词列表的请求。 - keywordListReq := httptest.NewRequest(http.MethodGet, "/keywords-with-type/acc1", nil) + keywordListReq := httptest.NewRequest(http.MethodGet, "/api/v1/reply-rules/acc1/typed", nil) keywordListReq.AddCookie(sessionCookie) // keywordListRecorder 是捕获关键词列表响应的记录器。 keywordListRecorder := httptest.NewRecorder() @@ -557,7 +559,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) { } // itemReplyReq 是保存指定商品回复的请求。 - itemReplyReq := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/contract-item", strings.NewReader(`{"reply_content":"商品契约回复"}`)) + itemReplyReq := httptest.NewRequest(http.MethodPut, "/api/v1/reply-rules/items/acc1/contract-item", strings.NewReader(`{"reply_content":"商品契约回复"}`)) itemReplyReq.Header.Set("Content-Type", "application/json") itemReplyReq.AddCookie(sessionCookie) // itemReplyRecorder 是捕获指定商品回复响应的记录器。 @@ -577,7 +579,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) { } // defaultReplyReq 是保存默认回复的请求。 - defaultReplyReq := httptest.NewRequest(http.MethodPut, "/api/default-reply/acc1", strings.NewReader(`{"enabled":true,"reply_content":"默认契约回复","reply_once":true,"reply_image_url":""}`)) + defaultReplyReq := httptest.NewRequest(http.MethodPut, "/api/v1/default-replies/acc1", strings.NewReader(`{"enabled":true,"reply_content":"默认契约回复","reply_once":true,"reply_image_url":""}`)) defaultReplyReq.Header.Set("Content-Type", "application/json") defaultReplyReq.AddCookie(sessionCookie) // defaultReplyRecorder 是捕获默认回复响应的记录器。 @@ -597,7 +599,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) { } // defaultReplyGetReq 是读取默认回复的请求。 - defaultReplyGetReq := httptest.NewRequest(http.MethodGet, "/api/default-reply/acc1", nil) + defaultReplyGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/default-replies/acc1", nil) defaultReplyGetReq.AddCookie(sessionCookie) // defaultReplyGetRecorder 是捕获默认回复查询响应的记录器。 defaultReplyGetRecorder := httptest.NewRecorder() @@ -616,7 +618,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) { } // taskSettingsReq 是读取账号任务设置的请求。 - taskSettingsReq := httptest.NewRequest(http.MethodGet, "/api/account-tasks/acc1", nil) + taskSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/account-tasks/acc1", nil) taskSettingsReq.AddCookie(sessionCookie) // taskSettingsRecorder 是捕获账号任务设置响应的记录器。 taskSettingsRecorder := httptest.NewRecorder() @@ -635,7 +637,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) { } // taskRunsReq 是读取账号任务执行记录的请求。 - taskRunsReq := httptest.NewRequest(http.MethodGet, "/api/account-tasks/acc1/runs", nil) + taskRunsReq := httptest.NewRequest(http.MethodGet, "/api/v1/account-tasks/acc1/runs", nil) taskRunsReq.AddCookie(sessionCookie) // taskRunsRecorder 是捕获账号任务执行记录响应的记录器。 taskRunsRecorder := httptest.NewRecorder() @@ -660,7 +662,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { srv, store, cleanup := newTestServer(t) defer cleanup() // handler 是当前测试使用的完整路由树。 - handler := srv.Router() + handler := contractRecordingHandler(t, srv.Router()) // sessionCookie 是管理员登录后得到的认证会话。 sessionCookie := loginHelper(t, handler) // seedErr 是统计测试订单写入失败的原因。 @@ -669,7 +671,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { } // adminStatsReq 是读取管理员全局统计的请求。 - adminStatsReq := httptest.NewRequest(http.MethodGet, "/admin/stats", nil) + adminStatsReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/stats", nil) adminStatsReq.AddCookie(sessionCookie) // adminStatsRecorder 是捕获管理员统计响应的记录器。 adminStatsRecorder := httptest.NewRecorder() @@ -688,7 +690,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { } // adminUsersReq 是读取管理员用户列表的请求。 - adminUsersReq := httptest.NewRequest(http.MethodGet, "/admin/users", nil) + adminUsersReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/users", nil) adminUsersReq.AddCookie(sessionCookie) // adminUsersRecorder 是捕获管理员用户列表响应的记录器。 adminUsersRecorder := httptest.NewRecorder() @@ -707,7 +709,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { } // adminCookiesReq 是读取管理员账号列表的请求。 - adminCookiesReq := httptest.NewRequest(http.MethodGet, "/admin/cookies", nil) + adminCookiesReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/cookies", nil) adminCookiesReq.AddCookie(sessionCookie) // adminCookiesRecorder 是捕获管理员账号列表响应的记录器。 adminCookiesRecorder := httptest.NewRecorder() @@ -726,7 +728,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { } // dashboardReq 是读取当前用户概览统计的请求。 - dashboardReq := httptest.NewRequest(http.MethodGet, "/dashboard/stats", nil) + dashboardReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/dashboard", nil) dashboardReq.AddCookie(sessionCookie) // dashboardRecorder 是捕获概览统计响应的记录器。 dashboardRecorder := httptest.NewRecorder() @@ -745,7 +747,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { } // analyticsReq 是读取订单分析统计的请求。 - analyticsReq := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-08-14&end_date=2026-08-14", nil) + analyticsReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/orders?start_date=2026-08-14&end_date=2026-08-14", nil) analyticsReq.AddCookie(sessionCookie) // analyticsRecorder 是捕获订单分析响应的记录器。 analyticsRecorder := httptest.NewRecorder() @@ -764,7 +766,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { } // validOrdersReq 是读取有效订单分页的请求。 - validOrdersReq := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-08-14&end_date=2026-08-14", nil) + validOrdersReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/orders/valid?start_date=2026-08-14&end_date=2026-08-14", nil) validOrdersReq.AddCookie(sessionCookie) // validOrdersRecorder 是捕获有效订单响应的记录器。 validOrdersRecorder := httptest.NewRecorder() @@ -785,7 +787,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { // 二维码生成使用测试专用平台替身。 setTestQRLogin(srv, &fakeQRLoginService{}) // qrReq 是生成扫码登录二维码的请求。 - qrReq := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil) + qrReq := httptest.NewRequest(http.MethodPost, "/api/v1/qr-login/generate", nil) qrReq.AddCookie(sessionCookie) // qrRecorder 是捕获二维码生成响应的记录器。 qrRecorder := httptest.NewRecorder() @@ -803,3 +805,127 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) { t.Fatalf("qr response=%+v", qrResponse) } } + +// TestOpenAPILocalResourceMutationResponses 验证会话、账号和管理员本地资源变更均有真实版本化成功响应。 +func TestOpenAPILocalResourceMutationResponses(t *testing.T) { + // srv、store、cleanup 分别提供独立 HTTP 服务、测试数据库和资源释放责任。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // handler 是全量 chi Router,所有请求均通过正式版本化路由执行。 + handler := srv.Router() + // healthRecorder 保存无需认证的健康检查成功响应。 + healthRecorder := serveOpenAPISuccess(t, handler, nil, http.MethodGet, "/health", "") + if healthRecorder.Code != http.StatusOK { + t.Fatalf("health status=%d body=%s", healthRecorder.Code, healthRecorder.Body.String()) + } + // sessionCookie 是初始管理员会话,用于验证当前密码并执行账号管理操作。 + sessionCookie := loginHelper(t, handler) + // passwordRecorder 保存当前用户修改密码后的成功响应;该操作会废弃旧会话。 + passwordRecorder := serveOpenAPISuccess(t, handler, sessionCookie, http.MethodPost, "/api/v1/session/password", `{"current_password":"pw","new_password":"new-password"}`) + if passwordRecorder.Code != http.StatusOK { + t.Fatalf("change password status=%d body=%s", passwordRecorder.Code, passwordRecorder.Body.String()) + } + // refreshedCookie 是使用新密码重新登录后的会话,后续操作不依赖已撤销的旧会话。 + refreshedCookie := loginAsHelper(t, handler, "admin", "new-password") + // credentialsRecorder 保存管理员用户名更新成功响应;当前密码保持新密码以验证敏感输入仅在服务端处理。 + credentialsRecorder := serveOpenAPISuccess(t, handler, refreshedCookie, http.MethodPut, "/api/v1/session/credentials", `{"current_password":"new-password","new_username":"admin-contract"}`) + if credentialsRecorder.Code != http.StatusOK { + t.Fatalf("update credentials status=%d body=%s", credentialsRecorder.Code, credentialsRecorder.Body.String()) + } + // renamedCookie 是用户名变更后重新登录得到的会话,确保后续管理员操作使用当前身份。 + renamedCookie := loginAsHelper(t, handler, "admin-contract", "new-password") + // adminPasswordRecorder 保存管理员密码变更成功响应,覆盖管理员专属密码 operation。 + adminPasswordRecorder := serveOpenAPISuccess(t, handler, renamedCookie, http.MethodPost, "/api/v1/admin/password", `{"current_password":"new-password","new_password":"final-password"}`) + if adminPasswordRecorder.Code != http.StatusOK { + t.Fatalf("change admin password status=%d body=%s", adminPasswordRecorder.Code, adminPasswordRecorder.Body.String()) + } + // finalCookie 是最终密码对应的管理员会话,供账号和用户删除生命周期使用。 + finalCookie := loginAsHelper(t, handler, "admin-contract", "final-password") + // accountRecorder 保存新建可删除账号的成功响应;请求内 Cookie 只用于测试输入,响应不得返回该明文。 + accountRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/accounts", `{"id":"delete-contract","value":"unb=delete-contract","login_method":"manual"}`) + if accountRecorder.Code != http.StatusOK || strings.Contains(accountRecorder.Body.String(), "unb=delete-contract") { + t.Fatalf("create account response invalid: status=%d body=%s", accountRecorder.Code, accountRecorder.Body.String()) + } + // deleteAccountRecorder 保存同一账号的删除成功响应,形成真实账号资源生命周期闭环。 + deleteAccountRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/accounts/delete-contract", "") + if deleteAccountRecorder.Code != http.StatusOK { + t.Fatalf("delete account status=%d body=%s", deleteAccountRecorder.Code, deleteAccountRecorder.Body.String()) + } + // created、createUserErr 分别表示普通用户是否已写入和创建失败原因。 + created, createUserErr := store.Users.Create(context.Background(), "delete-user", "delete-user@example.com", "pw") + if createUserErr != nil { + t.Fatalf("create deletable user: %v", createUserErr) + } + if !created { + t.Fatal("create deletable user returned false") + } + // deletableUser、getUserErr 分别保存待删除普通用户的稳定数据库 ID 和重新读取失败原因。 + deletableUser, getUserErr := store.Users.GetByUsername(context.Background(), "delete-user") + if getUserErr != nil || deletableUser == nil { + t.Fatalf("load deletable user: user=%+v err=%v", deletableUser, getUserErr) + } + // deleteUserRecorder 保存管理员删除普通用户的成功响应,避免把不存在用户的 4xx 当作成功证据。 + deleteUserRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/admin/users/"+strconv.FormatInt(deletableUser.ID, 10), "") + if deleteUserRecorder.Code != http.StatusOK { + t.Fatalf("delete user status=%d body=%s", deleteUserRecorder.Code, deleteUserRecorder.Body.String()) + } + // automationCardID、automationCreateRecorder 分别保存自动化规则所需卡券 ID 和创建响应。 + automationCardID, cardErr := store.Cards.Create(context.Background(), &db.CardFull{Name: "契约自动化卡", Type: "text", TextContent: "CARD", Enabled: true, UserID: 1}) + if cardErr != nil { + t.Fatalf("create automation card: %v", cardErr) + } + // itemErr 表示自动化规则关联商品夹具写入失败。 + if _, itemErr := store.DB.ExecContext(context.Background(), `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','contract-automation-item','自动化商品')`); itemErr != nil { + t.Fatalf("create automation item: %v", itemErr) + } + // automationCreateRecorder 保存自动化规则创建成功响应。 + automationCreateRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/automation-rules", `{"cookie_id":"acc1","item_id":"contract-automation-item","trigger_type":"order_paid","enabled":true,"actions":[{"action_type":"send_card","card_id":`+strconv.FormatInt(automationCardID, 10)+`,"delivery_count":1}]}`) + // automationCreateResponse 保存自动化规则创建返回的数值主键。 + var automationCreateResponse mutationIDResponse + // decodeErr 表示解析自动化规则创建响应失败。 + if decodeErr := json.Unmarshal(automationCreateRecorder.Body.Bytes(), &automationCreateResponse); decodeErr != nil || automationCreateResponse.ID == 0 { + t.Fatalf("decode automation create: id=%d err=%v body=%s", automationCreateResponse.ID, decodeErr, automationCreateRecorder.Body.String()) + } + // automationRuleID 是后续更新和删除操作使用的规则路径标识。 + automationRuleID := strconv.FormatInt(automationCreateResponse.ID, 10) + serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/automation-rules/"+automationRuleID, `{"cookie_id":"acc1","item_id":"contract-automation-item","trigger_type":"order_paid","enabled":false,"actions":[{"action_type":"send_card","card_id":`+strconv.FormatInt(automationCardID, 10)+`,"delivery_count":1}]}`) + serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/automation-rules/"+automationRuleID, "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/default-replies/acc1", `{"enabled":true,"reply_content":"契约默认回复","reply_once":true}`) + serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies/acc1", "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies", "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies/list", "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/default-replies/acc1/clear-records", "{}") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/default-replies/acc1", "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/items/cookie/acc1", "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/items/publish-batches", "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/cards/1/details", "") + // orderID 是用于删除订单成功场景的本地订单标识。 + orderID := "contract-delete-order" + // orderErr 表示订单删除成功场景夹具写入失败。 + if _, orderErr := store.DB.ExecContext(context.Background(), `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id) VALUES ('contract-delete-order','contract-automation-item','buyer','pending_ship','acc1')`); orderErr != nil { + t.Fatalf("create delete order: %v", orderErr) + } + serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/orders/"+orderID, "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/items/acc1/contract-automation-item/multi-spec", `{"enabled":true}`) + serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/items/acc1/contract-automation-item/multi-quantity-delivery", `{"enabled":true}`) + // keywordRecorder 保存普通关键词规则创建成功响应,后续通过带类型列表获取稳定 ID。 + keywordRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/reply-rules/acc1", `{"keyword":"契约关键字","reply":"契约回复"}`) + if keywordRecorder.Code != http.StatusOK { + t.Fatalf("create keyword status=%d body=%s", keywordRecorder.Code, keywordRecorder.Body.String()) + } + // keywordListRecorder 保存带类型关键词列表成功响应。 + keywordListRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/reply-rules/acc1/typed", "") + // keywordRows 保存带稳定数值主键的关键词规则集合。 + var keywordRows []keywordTypedResponse + // keywordListErr 表示解析带类型关键词列表失败。 + if keywordListErr := json.Unmarshal(keywordListRecorder.Body.Bytes(), &keywordRows); keywordListErr != nil || len(keywordRows) == 0 { + t.Fatalf("load typed keywords: rows=%+v err=%v", keywordRows, keywordListErr) + } + // keywordID 是当前创建规则的稳定主键,用于更新、按 ID 删除与按索引删除的成功场景。 + keywordID := strconv.FormatInt(keywordRows[0].ID, 10) + serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/reply-rules/acc1/typed/"+keywordID, `{"keyword":"契约关键字","reply":"已更新回复","type":"text"}`) + serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/reply-rules/acc1/typed/"+keywordID, "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/reply-rules/acc1", `{"keyword":"索引关键字","reply":"索引回复"}`) + serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/reply-rules/acc1/index/0", "") + serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/account-tasks/acc1", `{"auto_rate_enabled":true,"rate_content":"服务很好","auto_polish_enabled":false,"polish_time":"03:00"}`) +} diff --git a/internal/server/success_contract_test.go b/internal/server/success_contract_test.go index 1475c92..8f167df 100644 --- a/internal/server/success_contract_test.go +++ b/internal/server/success_contract_test.go @@ -62,6 +62,16 @@ func TestChatEventDTOUsesFrontendContract(t *testing.T) { if loadErr != nil { t.Fatalf("加载 OpenAPI WebSocket 契约: %v", loadErr) } + // webSocketPath 是版本化聊天 WebSocket operation 的 OpenAPI 路径定义。 + webSocketPath := document.Paths.Find("/api/v1/chat/ws") + if webSocketPath == nil || webSocketPath.Get == nil || webSocketPath.Get.Responses == nil || webSocketPath.Get.Responses.Value("101") == nil { + t.Fatal("OpenAPI 缺少聊天 WebSocket 101 升级响应") + } + // rawException、exceptionOK 分别是成功响应特殊校验扩展原值及其对象结构是否有效。 + rawException, exceptionOK := webSocketPath.Get.Extensions["x-contract-success-exception"].(map[string]any) + if !exceptionOK || rawException["kind"] != "websocket" { + t.Fatalf("聊天 WebSocket 未登记 websocket 特殊校验: %#v", webSocketPath.Get.Extensions["x-contract-success-exception"]) + } // eventSchemaRef 保存 WebSocket 推送帧的具名 schema 引用。 eventSchemaRef := document.Components.Schemas["ChatWebSocketEvent"] if eventSchemaRef == nil || eventSchemaRef.Value == nil { diff --git a/internal/server/test_database_test.go b/internal/server/test_database_test.go index 6ac7ede..a287aa1 100644 --- a/internal/server/test_database_test.go +++ b/internal/server/test_database_test.go @@ -21,6 +21,8 @@ var ( serverTestTemplatePath string // serverTestTemplateErr 保存创建共享模板时遇到的错误。 serverTestTemplateErr error + // openAPISuccessOperations 收集当前 Go 测试进程中经真实 Router 成功响应校验的 operationId。 + openAPISuccessOperations sync.Map ) // TestMain 在所有 server 测试结束后删除共享数据库模板目录。 diff --git a/internal/server/versioned_account_contract_test.go b/internal/server/versioned_account_contract_test.go index ddecab4..99e82d6 100644 --- a/internal/server/versioned_account_contract_test.go +++ b/internal/server/versioned_account_contract_test.go @@ -27,9 +27,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) { // listRecorder 是捕获账号摘要响应的记录器。 listRecorder := httptest.NewRecorder() handler.ServeHTTP(listRecorder, listReq) - if listRecorder.Code != http.StatusOK { - t.Fatalf("versioned account list status=%d body=%s", listRecorder.Code, listRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, listReq, listRecorder) // accountIDs 是版本化账号摘要 ID 列表。 var accountIDs []string // listDecodeErr 是账号摘要响应反序列化失败的原因。 @@ -46,9 +44,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) { // detailsRecorder 是捕获账号详情响应的记录器。 detailsRecorder := httptest.NewRecorder() handler.ServeHTTP(detailsRecorder, detailsReq) - if detailsRecorder.Code != http.StatusOK { - t.Fatalf("versioned account details status=%d body=%s", detailsRecorder.Code, detailsRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, detailsReq, detailsRecorder) // detailsValue 是版本化账号详情 DTO 集合。 var detailsValue []cookieSummaryResponse // detailsDecodeErr 是账号详情响应反序列化失败的原因。 @@ -68,9 +64,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) { // runtimeRecorder 是捕获账号运行状态响应的记录器。 runtimeRecorder := httptest.NewRecorder() handler.ServeHTTP(runtimeRecorder, runtimeReq) - if runtimeRecorder.Code != http.StatusOK { - t.Fatalf("versioned runtime status=%d body=%s", runtimeRecorder.Code, runtimeRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, runtimeReq, runtimeRecorder) // runtimeValue 是版本化账号运行状态映射。 var runtimeValue map[string]engine.RuntimeStatus // runtimeDecodeErr 是运行状态响应反序列化失败的原因。 @@ -87,9 +81,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) { // detailRecorder 是捕获单账号详情响应的记录器。 detailRecorder := httptest.NewRecorder() handler.ServeHTTP(detailRecorder, detailReq) - if detailRecorder.Code != http.StatusOK { - t.Fatalf("versioned account detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, detailReq, detailRecorder) // detailValue 是版本化单账号详情 DTO。 var detailValue cookieDetailResponse // detailDecodeErr 是单账号详情响应反序列化失败的原因。 @@ -106,9 +98,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) { // statusRecorder 是捕获账号状态变更响应的记录器。 statusRecorder := httptest.NewRecorder() handler.ServeHTTP(statusRecorder, statusReq) - if statusRecorder.Code != http.StatusOK { - t.Fatalf("versioned account status=%d body=%s", statusRecorder.Code, statusRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, statusReq, statusRecorder) // statusValue 是账号状态变更具名响应 DTO。 var statusValue operationResponse // statusDecodeErr 是状态变更响应反序列化失败的原因。 @@ -157,9 +147,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) { // addRecorder 是捕获新增账号响应的记录器。 addRecorder := httptest.NewRecorder() handler.ServeHTTP(addRecorder, addReq) - if addRecorder.Code != http.StatusOK { - t.Fatalf("versioned add account status=%d body=%s", addRecorder.Code, addRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, addReq, addRecorder) // addValue 是新增账号响应中的具名结果 DTO。 var addValue accountMutationResponse // addDecodeErr 是新增账号响应反序列化失败的原因。 @@ -179,9 +167,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) { // updateRecorder 是捕获 Cookie 更新响应的记录器。 updateRecorder := httptest.NewRecorder() handler.ServeHTTP(updateRecorder, updateReq) - if updateRecorder.Code != http.StatusOK { - t.Fatalf("versioned update account status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, updateReq, updateRecorder) // updateValue 是 Cookie 更新响应中的具名结果 DTO。 var updateValue operationResponse // updateDecodeErr 是 Cookie 更新响应反序列化失败的原因。 @@ -201,9 +187,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) { // loginInfoRecorder 是捕获登录信息更新响应的记录器。 loginInfoRecorder := httptest.NewRecorder() handler.ServeHTTP(loginInfoRecorder, loginInfoReq) - if loginInfoRecorder.Code != http.StatusOK { - t.Fatalf("versioned login info status=%d body=%s", loginInfoRecorder.Code, loginInfoRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, loginInfoReq, loginInfoRecorder) // loginInfoValue 是登录信息更新响应中的具名结果 DTO。 var loginInfoValue operationResponse // loginInfoDecodeErr 是登录信息响应反序列化失败的原因。 @@ -250,9 +234,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) { // settingsRecorder 是捕获聚合设置响应的记录器。 settingsRecorder := httptest.NewRecorder() handler.ServeHTTP(settingsRecorder, settingsReq) - if settingsRecorder.Code != http.StatusOK { - t.Fatalf("versioned settings status=%d body=%s", settingsRecorder.Code, settingsRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, settingsReq, settingsRecorder) // settingsValue 是聚合账号设置具名响应 DTO。 var settingsValue cookieSettingsResponse // settingsDecodeErr 是聚合设置响应反序列化失败的原因。 @@ -269,9 +251,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) { // remarkRecorder 是捕获备注响应的记录器。 remarkRecorder := httptest.NewRecorder() handler.ServeHTTP(remarkRecorder, remarkReq) - if remarkRecorder.Code != http.StatusOK { - t.Fatalf("versioned remark status=%d body=%s", remarkRecorder.Code, remarkRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, remarkReq, remarkRecorder) // remarkValue 是备注变更具名响应 DTO。 var remarkValue operationResponse // remarkDecodeErr 是备注响应反序列化失败的原因。 @@ -288,9 +268,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) { // autoConfirmRecorder 是捕获自动确认响应的记录器。 autoConfirmRecorder := httptest.NewRecorder() handler.ServeHTTP(autoConfirmRecorder, autoConfirmReq) - if autoConfirmRecorder.Code != http.StatusOK { - t.Fatalf("versioned auto-confirm status=%d body=%s", autoConfirmRecorder.Code, autoConfirmRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, autoConfirmReq, autoConfirmRecorder) // pauseReq 是更新版本化暂停时长的请求。 pauseReq := httptest.NewRequest(http.MethodPut, "/api/v1/accounts/acc1/pause-duration", strings.NewReader(`{"pause_duration":15}`)) @@ -298,9 +276,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) { // pauseRecorder 是捕获暂停时长响应的记录器。 pauseRecorder := httptest.NewRecorder() handler.ServeHTTP(pauseRecorder, pauseReq) - if pauseRecorder.Code != http.StatusOK { - t.Fatalf("versioned pause status=%d body=%s", pauseRecorder.Code, pauseRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, pauseReq, pauseRecorder) // pauseValue 是暂停时长具名响应 DTO。 var pauseValue cookieSettingsResponse // pauseDecodeErr 是暂停响应反序列化失败的原因。 @@ -317,9 +293,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) { // autoConfirmGetRecorder 是捕获自动确认查询响应的记录器。 autoConfirmGetRecorder := httptest.NewRecorder() handler.ServeHTTP(autoConfirmGetRecorder, autoConfirmGetReq) - if autoConfirmGetRecorder.Code != http.StatusOK { - t.Fatalf("versioned auto-confirm get status=%d body=%s", autoConfirmGetRecorder.Code, autoConfirmGetRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, autoConfirmGetReq, autoConfirmGetRecorder) // autoConfirmValue 是自动确认查询具名响应 DTO。 var autoConfirmValue autoConfirmResponse // autoConfirmDecodeErr 是自动确认查询响应反序列化失败的原因。 @@ -336,9 +310,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) { // pauseGetRecorder 是捕获暂停查询响应的记录器。 pauseGetRecorder := httptest.NewRecorder() handler.ServeHTTP(pauseGetRecorder, pauseGetReq) - if pauseGetRecorder.Code != http.StatusOK { - t.Fatalf("versioned pause get status=%d body=%s", pauseGetRecorder.Code, pauseGetRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, pauseGetReq, pauseGetRecorder) // pauseGetValue 是暂停查询具名响应 DTO。 var pauseGetValue pauseDurationResponse // pauseGetDecodeErr 是暂停查询响应反序列化失败的原因。 @@ -355,9 +327,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) { // profileRecorder 是捕获资料刷新响应的记录器。 profileRecorder := httptest.NewRecorder() handler.ServeHTTP(profileRecorder, profileReq) - if profileRecorder.Code != http.StatusOK { - t.Fatalf("versioned profile status=%d body=%s", profileRecorder.Code, profileRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, profileReq, profileRecorder) // profileValue 是资料刷新具名响应 DTO。 var profileValue cookieProfileResponse // profileDecodeErr 是资料刷新响应反序列化失败的原因。 diff --git a/internal/server/versioned_admin_analytics_contract_test.go b/internal/server/versioned_admin_analytics_contract_test.go index f733396..0da3247 100644 --- a/internal/server/versioned_admin_analytics_contract_test.go +++ b/internal/server/versioned_admin_analytics_contract_test.go @@ -33,6 +33,9 @@ func requestAdminAnalyticsRoute(t *testing.T, handler http.Handler, sessionCooki // recorder 是捕获兼容入口响应的记录器。 recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) + if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices { + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } return recorder.Code } diff --git a/internal/server/versioned_chat_task_contract_test.go b/internal/server/versioned_chat_task_contract_test.go index 5a00c2c..0bfe7df 100644 --- a/internal/server/versioned_chat_task_contract_test.go +++ b/internal/server/versioned_chat_task_contract_test.go @@ -32,6 +32,9 @@ func requestChatTaskRoute(t *testing.T, handler http.Handler, sessionCookie *htt // recorder 是捕获兼容入口响应的记录器。 recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) + if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices { + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } return recorder.Code } diff --git a/internal/server/versioned_item_batch_contract_test.go b/internal/server/versioned_item_batch_contract_test.go index f05f4b9..8988f3c 100644 --- a/internal/server/versioned_item_batch_contract_test.go +++ b/internal/server/versioned_item_batch_contract_test.go @@ -32,6 +32,9 @@ func requestItemBatchRoute(t *testing.T, handler http.Handler, sessionCookie *ht // recorder 是捕获商品批量响应的记录器。 recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) + if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices { + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } return recorder.Code } diff --git a/internal/server/versioned_item_contract_test.go b/internal/server/versioned_item_contract_test.go index 84e4895..c7fa7a9 100644 --- a/internal/server/versioned_item_contract_test.go +++ b/internal/server/versioned_item_contract_test.go @@ -32,9 +32,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) { // listRecorder 是捕获版本化商品列表响应的记录器。 listRecorder := httptest.NewRecorder() handler.ServeHTTP(listRecorder, listReq) - if listRecorder.Code != http.StatusOK { - t.Fatalf("versioned item list status=%d body=%s", listRecorder.Code, listRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, listReq, listRecorder) // listValue 是版本化商品列表响应 DTO 集合。 var listValue []itemListResponse // listDecodeErr 是商品列表响应反序列化失败的原因。 @@ -51,9 +49,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) { // detailRecorder 是捕获版本化商品详情响应的记录器。 detailRecorder := httptest.NewRecorder() handler.ServeHTTP(detailRecorder, detailReq) - if detailRecorder.Code != http.StatusOK { - t.Fatalf("versioned item detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, detailReq, detailRecorder) // detailValue 是版本化商品详情响应 DTO。 var detailValue itemDetailResponse // detailDecodeErr 是商品详情响应反序列化失败的原因。 @@ -70,9 +66,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) { // updateRecorder 是捕获版本化商品更新响应的记录器。 updateRecorder := httptest.NewRecorder() handler.ServeHTTP(updateRecorder, updateReq) - if updateRecorder.Code != http.StatusOK { - t.Fatalf("versioned item update status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, updateReq, updateRecorder) // updatedItem 是数据库中用于确认版本化更新结果的商品记录。 updatedItem, updatedErr := store.Items.Get(ctx, "acc1", "item-v1") if updatedErr != nil || updatedItem == nil || updatedItem.ItemTitle != "版本化新商品名" { @@ -95,9 +89,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) { // deleteRecorder 是捕获版本化商品删除响应的记录器。 deleteRecorder := httptest.NewRecorder() handler.ServeHTTP(deleteRecorder, deleteReq) - if deleteRecorder.Code != http.StatusOK { - t.Fatalf("versioned item delete status=%d body=%s", deleteRecorder.Code, deleteRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, deleteReq, deleteRecorder) // legacyDeleteReq 是验证旧商品删除入口仍可用的请求。 legacyDeleteReq := httptest.NewRequest(http.MethodDelete, "/items/acc1/item-legacy", nil) diff --git a/internal/server/versioned_order_contract_test.go b/internal/server/versioned_order_contract_test.go index af8a818..5f975ad 100644 --- a/internal/server/versioned_order_contract_test.go +++ b/internal/server/versioned_order_contract_test.go @@ -34,9 +34,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) { // listRecorder 是捕获版本化订单列表响应的记录器。 listRecorder := httptest.NewRecorder() handler.ServeHTTP(listRecorder, listReq) - if listRecorder.Code != http.StatusOK { - t.Fatalf("versioned order list status=%d body=%s", listRecorder.Code, listRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, listReq, listRecorder) // listValue 是版本化订单列表响应 DTO。 var listValue orderListResponse // listDecodeErr 是订单列表响应反序列化失败的原因。 @@ -53,9 +51,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) { // detailRecorder 是捕获版本化订单详情响应的记录器。 detailRecorder := httptest.NewRecorder() handler.ServeHTTP(detailRecorder, detailReq) - if detailRecorder.Code != http.StatusOK { - t.Fatalf("versioned order detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, detailReq, detailRecorder) // detailValue 是版本化订单详情响应 DTO。 var detailValue orderDetailResponse // detailDecodeErr 是订单详情响应反序列化失败的原因。 @@ -72,9 +68,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) { // updateRecorder 是捕获版本化订单更新响应的记录器。 updateRecorder := httptest.NewRecorder() handler.ServeHTTP(updateRecorder, updateReq) - if updateRecorder.Code != http.StatusOK { - t.Fatalf("versioned order update status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, updateReq, updateRecorder) // updateValue 是版本化订单更新响应 DTO。 var updateValue operationResponse // updateDecodeErr 是订单更新响应反序列化失败的原因。 @@ -124,20 +118,38 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T // refreshRecorder 是捕获版本化刷新响应的记录器。 refreshRecorder := httptest.NewRecorder() handler.ServeHTTP(refreshRecorder, refreshReq) - if refreshRecorder.Code != http.StatusAccepted { - t.Fatalf("versioned order refresh status=%d body=%s", refreshRecorder.Code, refreshRecorder.Body.String()) - } + assertOpenAPIExpectedStatusResponse(t, refreshReq, refreshRecorder, http.StatusAccepted) // refreshStart 是版本化刷新任务创建响应 DTO。 var refreshStart orderRefreshJobStartResponse // refreshDecodeErr 是刷新任务创建响应反序列化失败的原因。 if refreshDecodeErr := json.Unmarshal(refreshRecorder.Body.Bytes(), &refreshStart); refreshDecodeErr != nil { t.Fatalf("decode versioned order refresh: %v", refreshDecodeErr) } + // versionedStatusReq 查询刚创建的版本化刷新任务,覆盖真实 200 状态响应。 + versionedStatusReq := httptest.NewRequest(http.MethodGet, "/api/v1/orders/refresh/"+refreshStart.JobID, nil) + versionedStatusReq.AddCookie(sessionCookie) + // versionedStatusRecorder 保存版本化刷新任务查询响应。 + versionedStatusRecorder := httptest.NewRecorder() + handler.ServeHTTP(versionedStatusRecorder, versionedStatusReq) + assertOpenAPIRecordedSuccessResponse(t, versionedStatusReq, versionedStatusRecorder) // refreshValue 是版本化刷新任务完成后的具名结果。 refreshValue := waitOrderRefreshJob(t, handler, sessionCookie, refreshStart.JobID) if refreshValue.Message == "" { t.Fatalf("versioned order refresh should preserve a named success response: %+v", refreshValue) } + // queuedJob 是专门用于版本化取消 operation 的排队任务夹具。 + queuedJob := &db.OrderRefreshJob{ID: "versioned-cancel-job", UserID: 1, Status: "queued"} + // createErr 表示写入版本化取消任务夹具失败。 + if createErr := store.OrderRefreshJobs.Create(ctx, queuedJob); createErr != nil { + t.Fatalf("create versioned cancel job: %v", createErr) + } + // versionedCancelReq 请求取消该排队任务。 + versionedCancelReq := httptest.NewRequest(http.MethodDelete, "/api/v1/orders/refresh/"+queuedJob.ID, nil) + versionedCancelReq.AddCookie(sessionCookie) + // versionedCancelRecorder 保存版本化取消响应。 + versionedCancelRecorder := httptest.NewRecorder() + handler.ServeHTTP(versionedCancelRecorder, versionedCancelReq) + assertOpenAPIRecordedSuccessResponse(t, versionedCancelReq, versionedCancelRecorder) // legacyRefreshReq 是验证旧订单列表刷新入口仍可用的请求。 legacyRefreshReq := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil) @@ -167,10 +179,7 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T // singleRecorder 是捕获版本化单订单刷新响应的记录器。 singleRecorder := httptest.NewRecorder() handler.ServeHTTP(singleRecorder, singleReq) - // 夹具客户端提供订单详情响应,新旧入口都应返回成功刷新结果。 - if singleRecorder.Code != http.StatusOK { - t.Fatalf("versioned single order refresh status=%d body=%s", singleRecorder.Code, singleRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, singleReq, singleRecorder) // legacySingleReq 是验证旧单订单刷新入口仍可用的请求。 legacySingleReq := httptest.NewRequest(http.MethodPost, "/api/orders/order-single-v1/refresh", nil) @@ -208,9 +217,7 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T // importRecorder 是捕获版本化导入响应的记录器。 importRecorder := httptest.NewRecorder() handler.ServeHTTP(importRecorder, importReq) - if importRecorder.Code != http.StatusOK { - t.Fatalf("versioned order import status=%d body=%s", importRecorder.Code, importRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, importReq, importRecorder) // legacyImportReq 是验证旧导入入口仍可用的请求。 legacyImportReq := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(`[]`)) diff --git a/internal/server/versioned_qr_routes_contract_test.go b/internal/server/versioned_qr_routes_contract_test.go index a8e10b7..6987884 100644 --- a/internal/server/versioned_qr_routes_contract_test.go +++ b/internal/server/versioned_qr_routes_contract_test.go @@ -33,6 +33,9 @@ func requestQRLoginRoute(t *testing.T, handler http.Handler, sessionCookie *http // recorder 是捕获二维码响应的测试记录器。 recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) + if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices { + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } return recorder.Code } diff --git a/internal/server/versioned_remaining_routes_contract_test.go b/internal/server/versioned_remaining_routes_contract_test.go index 49e9f54..ccd9939 100644 --- a/internal/server/versioned_remaining_routes_contract_test.go +++ b/internal/server/versioned_remaining_routes_contract_test.go @@ -32,6 +32,9 @@ func requestRemainingVersionedRoute(t *testing.T, handler http.Handler, sessionC // recorder 是捕获公共兼容入口响应的记录器。 recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) + if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices { + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } return recorder.Code } diff --git a/internal/server/versioned_reply_contract_test.go b/internal/server/versioned_reply_contract_test.go index 57868f9..ea23cd9 100644 --- a/internal/server/versioned_reply_contract_test.go +++ b/internal/server/versioned_reply_contract_test.go @@ -32,6 +32,9 @@ func requestReplyRoute(t *testing.T, handler http.Handler, sessionCookie *http.C // recorder 是捕获兼容入口响应的记录器。 recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) + if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices { + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } return recorder.Code } diff --git a/internal/server/versioned_session_contract_test.go b/internal/server/versioned_session_contract_test.go index 58517a1..c83642f 100644 --- a/internal/server/versioned_session_contract_test.go +++ b/internal/server/versioned_session_contract_test.go @@ -22,9 +22,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) { // loginRecorder 是捕获版本化登录响应的记录器。 loginRecorder := httptest.NewRecorder() handler.ServeHTTP(loginRecorder, loginReq) - if loginRecorder.Code != http.StatusOK { - t.Fatalf("versioned login status=%d body=%s", loginRecorder.Code, loginRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, loginReq, loginRecorder) // loginResponseValue 是版本化登录响应 DTO。 var loginResponseValue loginResponse // loginDecodeErr 是版本化登录响应反序列化失败的原因。 @@ -43,9 +41,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) { // verifyRecorder 是捕获版本化会话校验响应的记录器。 verifyRecorder := httptest.NewRecorder() handler.ServeHTTP(verifyRecorder, verifyReq) - if verifyRecorder.Code != http.StatusOK { - t.Fatalf("versioned verify status=%d body=%s", verifyRecorder.Code, verifyRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, verifyReq, verifyRecorder) // verifyResponseValue 是版本化会话校验响应 DTO。 var verifyResponseValue sessionVerificationResponse // verifyDecodeErr 是版本化会话校验响应反序列化失败的原因。 @@ -72,9 +68,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) { // logoutRecorder 是捕获版本化注销响应的记录器。 logoutRecorder := httptest.NewRecorder() handler.ServeHTTP(logoutRecorder, logoutReq) - if logoutRecorder.Code != http.StatusOK { - t.Fatalf("versioned logout status=%d body=%s", logoutRecorder.Code, logoutRecorder.Body.String()) - } + assertOpenAPISuccessResponse(t, logoutReq, logoutRecorder) // legacyLoginReq 是验证旧登录入口仍可用的请求。 legacyLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(loginBody)) diff --git a/internal/server/versioned_settings_card_notification_contract_test.go b/internal/server/versioned_settings_card_notification_contract_test.go index 1d9810a..4e5355c 100644 --- a/internal/server/versioned_settings_card_notification_contract_test.go +++ b/internal/server/versioned_settings_card_notification_contract_test.go @@ -32,6 +32,9 @@ func requestSettingsCardNotificationRoute(t *testing.T, handler http.Handler, se // recorder 是捕获兼容入口响应的记录器。 recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) + if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices { + assertOpenAPIRecordedSuccessResponse(t, request, recorder) + } return recorder.Code } diff --git a/internal/webui/static/assets/AccountList-DX3reM6l.js b/internal/webui/static/assets/AccountList-DX3reM6l.js new file mode 100644 index 0000000..68eac59 --- /dev/null +++ b/internal/webui/static/assets/AccountList-DX3reM6l.js @@ -0,0 +1,3 @@ +import{b as ie,j as e,a as l,c as Me}from"./react-vendor-l-BBvuKH.js";import{r as T,c as L}from"./index-CiBUw4Te.js";import{c as Ae,o as Pe}from"./contract-COFcZjyb.js";import{n as de,X as ce,f as Be,L as J,o as qe,p as Ge,q as Oe,r as Te,s as Le,U as Ee,t as ae,u as ze,k as we,Q as _e,v as Ie,R as We,w as Ve,x as Ke,y as Ne,K as He,z as Je,F as Xe,e as Ye,H as Ze}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const Fe=(t,s)=>{const r=t.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",s),a.toString()}catch{return r}},es=async t=>{const s=await T(n=>L.GET("/api/v1/accounts/details",{signal:n}),t),r=Ae(s,["data","accounts","details"]),a=Date.now().toString();return r.map(n=>({id:n.id,cookie_configured:n.has_cookie===!0,enabled:n.enabled,auto_confirm:n.auto_confirm,remark:n.remark,pause_duration:n.pause_duration,paused_until:Number(n.paused_until||0),paused:n.paused===!0,username:n.username||"",login_password_configured:void 0,show_browser:n.show_browser===!0||n.show_browser===1||n.show_browser==="1"||n.show_browser==="true",nickname:n.nickname||n.remark||`账号 ${n.id.substring(0,6)}`,avatar_url:Fe(n,a),profile_error:n.profile_error||"",ai_enabled:!1,auto_rate_enabled:n.auto_rate_enabled,rate_content:n.rate_content||"不错的买家,交易愉快",auto_polish_enabled:n.auto_polish_enabled,polish_time:n.polish_time||"03:00",last_rate_scan_at:Number(n.last_rate_scan_at||0),last_polish_date:n.last_polish_date||"",last_polish_at:Number(n.last_polish_at||0)}))},ve=async(t,s)=>T(r=>L.GET("/api/v1/account-tasks/{cid}",{params:{path:{cid:t}},signal:r}),s),ke=async(t,s,r)=>T(a=>L.PUT("/api/v1/account-tasks/{cid}",{params:{path:{cid:t}},body:s,signal:a}),r),ss=async(t,s,r)=>T(a=>L.POST("/api/v1/account-tasks/{cid}/run",{params:{path:{cid:t}},body:{task_type:s},signal:a}),{timeoutMs:12e4,...r}),ts=async t=>await T(r=>L.GET("/api/v1/accounts/runtime-status",{signal:r}),t),as=async t=>T(s=>L.POST("/api/v1/qr-login/generate",{signal:s}),{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),rs=async(t,s)=>T(r=>L.GET("/api/v1/qr-login/check/{session_id}",{params:{path:{session_id:t}},signal:r}),{signal:s,timeoutMs:1e4}),ns=async(t,s)=>T(r=>L.POST("/api/v1/qr-login/complete-verification/{session_id}",{params:{path:{session_id:t}},body:{target_account_id:s||""},signal:r})),ls=async(t,s)=>T(r=>L.PUT("/api/v1/accounts/{cid}/status",{params:{path:{cid:t}},body:{enabled:s},signal:r})),os=async t=>T(s=>L.DELETE("/api/v1/accounts/{cid}",{params:{path:{cid:t}},signal:s})),is=async(t,s,r)=>T(a=>L.PUT("/api/v1/accounts/{cid}/pause-duration",{params:{path:{cid:t}},body:{pause_duration:s},signal:a}),r),cs=async(t,s,r)=>T(a=>L.PUT("/api/v1/accounts/{cid}/settings",{params:{path:{cid:t}},body:s,signal:a}),r),ds=async(t,s)=>T(r=>L.GET("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:t}},signal:r}),s),us=async(t,s,r)=>T(a=>L.PUT("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:t}},body:{enabled:s},signal:a}),r),xs=async(t,s)=>T(r=>L.POST("/api/v1/password-login",{body:t,signal:r}),s),ms=async(t,s)=>T(a=>L.GET("/api/v1/password-login/check/{session_id}",{params:{path:{session_id:t}},signal:a}),{signal:s,timeoutMs:1e4}),bs=async(t,s)=>T(r=>L.DELETE("/api/v1/password-login/cancel/{session_id}",{params:{path:{session_id:t}},signal:r}),s),hs=async t=>T(s=>L.POST("/api/v1/accounts/{cid}/refresh-profile",{params:{path:{cid:t}},signal:s})),gs=async t=>{const s=await T(r=>L.GET("/api/v1/settings/ai-reply",{signal:r}),t);return Pe(s,["settings","data","result"])||{}},ps=async(t,s)=>T(r=>L.GET("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:t}},signal:r}),s),fs=async(t,s,r)=>{const a={ai_enabled:s.ai_enabled??!1,max_discount_percent:s.max_discount_percent??10,max_discount_amount:s.max_discount_amount??100,max_bargain_rounds:s.max_bargain_rounds??3,custom_prompts:s.custom_prompts??""};return T(n=>L.PUT("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:t}},body:a,signal:n}),r)},ys=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const s=JSON.parse(t);if(Array.isArray(s))return s.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},js=async t=>{const s=await T(a=>L.GET("/api/v1/notifications/channels",{signal:a}),t);return{success:!0,data:Ae(s,["data","channels","items"]).map(a=>{const n={},c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:n,event_types:ys(a.event_types),enabled:a.enabled}})}},ws=async(t,s)=>{const r=await T(n=>L.GET("/api/v1/notifications/accounts/{cid}/bindings",{params:{path:{cid:t}},signal:n}),s),a=Pe(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},_s=({account:t,settings:s,saving:r,onChange:a,onClose:n,onSave:c})=>{const i=u=>a({...s,...u}),d=()=>i({ai_enabled:!s.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(de,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:n,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(ce,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(de,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:d,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.ai_enabled?"bg-brand":"bg-gray-300"}`,"aria-label":"切换 AI 自动回复",children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:s.max_discount_percent,onChange:b,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:s.max_discount_amount,onChange:m,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:s.max_bargain_rounds,onChange:f,className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:s.custom_prompts,onChange:h,placeholder:`输入自定义的AI回复规则或风格指引... + +例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(qe,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Ce=t=>({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),Z=(t,s,r)=>t===s&&!r.aborted,ye=(t,s)=>t instanceof Error?t.message:s,je=t=>t instanceof Error&&t.message==="请求已取消",Se=(t,s)=>!t&&s==="",Ns=({account:t,onSaved:s})=>{const[r,a]=l.useState(()=>Ce(t)),[n,c]=l.useState(!0),[i,d]=l.useState(!1),[b,m]=l.useState(""),[f,h]=l.useState(""),[u,A]=l.useState(null),[k,g]=l.useState(null),p=l.useRef(0),E=l.useRef(null);l.useEffect(()=>{var N;const S=++p.current;(N=E.current)==null||N.abort();const j=new AbortController;return E.current=j,a(Ce(t)),A(null),h(""),d(!1),m(""),g(null),c(!0),ve(t.id,{signal:j.signal}).then(R=>{Z(p.current,S,j.signal)&&a(R)}).catch(R=>{Z(p.current,S,j.signal)&&!je(R)&&h(ye(R,"加载任务设置失败"))}).finally(()=>{Z(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[t.id]),l.useEffect(()=>(()=>{var S;return(S=E.current)==null?void 0:S.abort()}),[]);const B=l.useCallback(async()=>{var N;if(!Se(i,b))return;const S=++p.current;(N=E.current)==null||N.abort();const j=new AbortController;E.current=j,d(!0),h(""),g(null);try{const R=await ke(t.id,r,{signal:j.signal});if(!Z(p.current,S,j.signal))return;a(R),s(R)}catch(R){Z(p.current,S,j.signal)&&!je(R)&&(h(ye(R,"保存失败")),g(()=>B))}finally{Z(p.current,S,j.signal)&&d(!1)}},[t.id,r,s,b,i]),G=l.useCallback(async S=>{var R;if(!Se(i,b)||!t.enabled)return;const j=++p.current;(R=E.current)==null||R.abort();const N=new AbortController;E.current=N,m(S),h(""),A(null),g(null);try{await ke(t.id,r,{signal:N.signal});const w=await ss(t.id,S,{signal:N.signal}),P=await ve(t.id,{signal:N.signal});if(!Z(p.current,j,N.signal))return;A(w.summary),a(P),s(P)}catch(w){Z(p.current,j,N.signal)&&!je(w)&&(h(ye(w,"任务执行失败")),g(()=>(()=>G(S))))}finally{Z(p.current,j,N.signal)&&m("")}},[t.enabled,t.id,r,s,b,i]),D=l.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:n,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:B,run:G,retry:D}},Re=({checked:t,onChange:s,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":t,onClick:s,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6":""}`})}),vs=({account:t,onClose:s,onSaved:r})=>{const{form:a,loading:n,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=Ns({account:t,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:s,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(ce,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[n&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",children:"正在读取任务设置..."}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(Ge,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(Re,{checked:a.auto_rate_enabled,onChange:(()=>f(k=>({...k,auto_rate_enabled:!k.auto_rate_enabled}))),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:a.rate_content,maxLength:500,onChange:(k=>f(g=>({...g,rate_content:k.target.value}))),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",a.last_rate_scan_at?new Date(a.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:i!==""||!t.enabled,onClick:(()=>void u("auto_rate")),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[i==="auto_rate"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Oe,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(Te,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(Re,{checked:a.auto_polish_enabled,onChange:(()=>f(k=>({...k,auto_polish_enabled:!k.auto_polish_enabled}))),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:a.polish_time,onChange:(k=>f(g=>({...g,polish_time:k.target.value}))),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:i!==""||!t.enabled,onClick:(()=>void u("auto_polish")),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[i==="auto_polish"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Le,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",a.last_polish_at?new Date(a.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),b&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",b.found," 项,成功 ",b.success,",失败 ",b.failed,",跳过 ",b.skipped,"。",b.message||""]}),d&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:[e.jsx("span",{children:d}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void A()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:s,disabled:c||i!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:(()=>void h()),disabled:c||i!==""||a.auto_rate_enabled&&!a.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[c?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(qe,{className:"h-4 w-4"}),"保存"]})]})})]})})},ks=(t,s)=>{if(!t||!s)return!1;const r=Date.parse(t),a=Date.parse(s);return Number.isFinite(r)&&Number.isFinite(a)&&at.map(r=>{const a=s[r.id];return!a||ks(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}}),Ss=t=>{if(!t.enabled||t.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(t.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"runtime_conflict":return{label:"运行状态冲突",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},Rs=Me.memo(function({account:s,refreshing:r,deleting:a,onRefreshProfile:n,onReauthorize:c,onEdit:i,onAI:d,onTasks:b,onToggle:m,onDelete:f}){const h=Ss(s),u=s.runtime_state==="auth_expired"||s.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:[s.avatar_url?e.jsx("img",{src:s.avatar_url,alt:s.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:s.runtime_state==="online"&&e.jsx(ae,{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:s.nickname||s.remark||`账号 ${s.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}),s.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(de,{className:"w-3 h-3"})," AI"]}),s.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(ze,{className:"h-3 w-3"})," 自动评价"]}),s.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(Te,{className:"h-3 w-3"})," 每日擦亮"]}),s.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(ae,{className:"h-3 w-3"})," 自动确认发货"]}),s.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:s.profile_error,children:[e.jsx(we,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"text-sm font-medium text-gray-500",children:[e.jsx("p",{children:s.remark||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",s.id]})]}),s.runtime_message&&s.runtime_state!=="online"&&s.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${u?"text-red-700":"text-amber-700"}`,children:[e.jsx(we,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:s.runtime_message}),u&&e.jsxs("button",{type:"button",onClick:(()=>c(s)),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(_e,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),s.paused&&e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700",children:[e.jsx(Ie,{className:"h-3 w-3"})," 暂停处理中"]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:(()=>n(s)),disabled:r,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(We,{className:`w-5 h-5 ${r?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>c(s)),className:`p-3 rounded-xl transition-colors ${u?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(_e,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>i(s)),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Ve,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>d(s)),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(de,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>b(s)),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Le,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>m(s.id,s.enabled)),className:`p-3 rounded-xl transition-colors ${s.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:s.enabled?"停用账号":"启用账号",children:e.jsx(Ke,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>f(s)),disabled:a,className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:a?"删除中…":`删除账号 ${s.nickname||s.remark||s.id}`,children:a?e.jsx(J,{className:"w-5 h-5 animate-spin"}):e.jsx(Ne,{className:"w-5 h-5"})})]})]})]})]})})}),As=({account:t,deleting:s,error:r,onClose:a,onConfirm:n})=>ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",role:"presentation",children:e.jsxs("div",{className:"h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal",role:"dialog","aria-modal":"true","aria-labelledby":"delete-account-title","aria-describedby":"delete-account-description",children:[e.jsxs("div",{className:"relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5",children:[e.jsx("div",{className:"absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl"}),e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200",children:e.jsx(Ne,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{id:"delete-account-title",className:"text-lg font-extrabold tracking-tight text-gray-950",children:"删除这个账号?"}),e.jsx("p",{id:"delete-account-description",className:"mt-1 text-xs leading-5 text-gray-600",children:"删除后,该账号的关联配置也会一并清理,此操作无法撤销。"})]}),e.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"关闭删除确认",children:e.jsx(ce,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:t.nickname||t.remark||"未命名账号"}),t.remark&&t.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",t.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",t.id]})]}),s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(J,{className:"h-5 w-5 flex-shrink-0 animate-spin text-brand"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-blue-950",children:"正在删除账号"}),e.jsx("div",{className:"mt-0.5 text-xs text-blue-700",children:"正在清理关联数据,请保持页面打开…"})]})]}),r&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3",role:"alert",children:[e.jsx(we,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-red-800",children:"删除失败"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-red-700",children:r})]})]})]}),e.jsxs("div",{className:"flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4",children:[e.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50",children:"取消"}),e.jsx("button",{type:"button",onClick:(()=>void n()),disabled:s,className:"flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400",children:s?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),De=({src:t,alt:s,className:r=""})=>e.jsx("img",{src:t,alt:s,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),Ps=({account:t,editForm:s,setEditForm:r,saving:a,onClose:n,onSave:c,onRestartPause:i,longLogin:d,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:f,onCancelPasswordLogin:h,notifChannels:u,selectedChannelIds:A,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:p,onRetryBindings:E,onToggleChannel:B,onSettingsDirty:G})=>{const D=(C,K)=>{r(se=>({...se,[C]:K}))},S=()=>void n(),j=()=>void c(),N=C=>D("remark",C.target.value),R=C=>D("cookie",C.target.value),w=()=>D("auto_confirm",!s.auto_confirm),P=C=>D("pause_duration",parseInt(C.target.value,10)||0),U=()=>void i(),Y=()=>void b(),X=C=>D("username",C.target.value),V=C=>r(K=>({...K,login_password:C.target.value,clear_password:!1})),H=()=>D("showLoginPassword",!s.showLoginPassword),z=C=>r(K=>({...K,clear_password:C.target.checked,login_password:C.target.checked?"":K.login_password})),I=()=>D("show_browser",!s.show_browser),W=()=>void h(),$=()=>void f(),M=()=>void E(),ee=C=>{k&&(B(C),G())},re=C=>{const K=A.includes(Number(C.id)),se=()=>ee(Number(C.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:se,disabled:!k,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${K?"bg-brand border-brand":"bg-white border-gray-300"}`,children:K&&e.jsx(ae,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:C.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[C.type,C.enabled?"":" · 已停用"]})]})]},C.id)};return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(ce,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:t.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:s.remark,onChange:N,placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:s.cookie,onChange:R,placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",s.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ae,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:w,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.auto_confirm?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:s.pause_duration,onChange:P,placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),s.pause_duration>0&&!t.paused&&s.pause_duration===(t.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:U,className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(He,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),d.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:d.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:d.loading||d.saving||!d.canOpen,onClick:Y,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${d.enabled?"bg-brand":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${d.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:s.username,onChange:X,placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:s.showLoginPassword?"text":"password",value:s.login_password,onChange:V,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:H,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:s.showLoginPassword?e.jsx(Je,{className:"w-5 h-5"}):e.jsx(Xe,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:s.clear_password,onChange:z,className:"w-4 h-4 accent-brand"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:I,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.show_browser?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),m.status==="processing"||m.status==="verification_required"?e.jsx("button",{type:"button",onClick:W,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:$,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),m.message&&e.jsx("div",{className:`text-sm font-medium ${m.status==="failed"?"text-red-700":m.status==="success"?"text-green-700":"text-blue-800"}`,children:m.message}),m.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),m.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(De,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(u.length>0||g||p)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(Ye,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),g&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(J,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),p&&!g&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:p}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:M,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:u.map(re)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:S,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:a,children:"取消"}),e.jsxs("button",{onClick:j,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:a,children:[a?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(ae,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},qs=({faceQrUrl:t,verificationScreenshot:s})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(Ze,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:t?e.jsx("img",{src:t,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):s?e.jsx("img",{src:s,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(J,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),Ts=({target:t,status:s,codeUrl:r,errorMessage:a,faceQrUrl:n,verificationScreenshot:c,onClose:i})=>ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:i,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors","aria-label":"关闭二维码登录",children:e.jsx(ce,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:t?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:t?`请用闲鱼APP扫码,为「${t.nickname||t.remark||t.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${s==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[s==="loading"&&e.jsx(J,{className:"w-10 h-10 text-brand animate-spin"}),s==="waiting"&&e.jsx(De,{src:r,alt:"闲鱼登录二维码",className:"p-2"}),s==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(ae,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),s==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:a||"请关闭窗口后重新发起扫码登录。"})]}),s==="verification"&&e.jsx(qs,{faceQrUrl:n,verificationScreenshot:c})]}),s!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),Ls=(t,s)=>t.map(r=>{var a,n,c,i,d;return{...r,ai_enabled:((a=s[r.id])==null?void 0:a.ai_enabled)??!1,max_discount_percent:((n=s[r.id])==null?void 0:n.max_discount_percent)??10,max_discount_amount:((c=s[r.id])==null?void 0:c.max_discount_amount)??100,max_bargain_rounds:((i=s[r.id])==null?void 0:i.max_bargain_rounds)??3,custom_prompts:((d=s[r.id])==null?void 0:d.custom_prompts)??""}}),Es=()=>{const[t,s]=l.useState([]),[r,a]=l.useState(!0),n=l.useRef(0),c=l.useRef(null),i=l.useCallback(async()=>{var m;const d=++n.current;(m=c.current)==null||m.abort();const b=new AbortController;c.current=b,a(!0);try{const f={signal:b.signal},[h,u]=await Promise.allSettled([es(f),gs(f)]);if(d!==n.current)return;if(h.status==="rejected")throw h.reason;const A=u.status==="fulfilled"?u.value:{};u.status==="rejected"&&console.error("加载 AI 设置失败:",u.reason),s(Ls(h.value,A))}catch(f){d===n.current&&!b.signal.aborted&&console.error("加载账号失败:",f)}finally{d===n.current&&a(!1)}},[]);return l.useEffect(()=>{let d=!1,b=null;const m=new AbortController,f=async()=>{try{const u=await ts({signal:m.signal,timeoutMs:1e4});d||s(A=>Cs(A,u))}catch(u){d||console.error("加载账号运行状态失败:",u)}finally{d||(b=window.setTimeout(()=>void f(),2e3))}};return i().finally(()=>{d||f()}),()=>{var u;d=!0,m.abort(),n.current+=1,(u=c.current)==null||u.abort(),b!==null&&window.clearTimeout(b)}},[i]),{accounts:t,setAccounts:s,loading:r,loadAccounts:i}},Is=new Set(["expired","cancelled","error","not_found"]),Ds=()=>{let t=0;return{next:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:(s=>s===t)}},Qs=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let s=null,r=null,a=-1,n=0;const c=()=>{n+=1,r==null||r.abort(),r=null,s!==null&&(t.clearInterval(s),s=null)};return{start:(d,b,m,f=2e3)=>{c();const h=n;r=new AbortController;const u=r.signal;s=t.setInterval(()=>{a===h||h!==n||(a=h,(async()=>{var A,k;try{const g=await b(d,u);if(g.status==="success"){c(),await m.onSuccess(g);return}if(g.status==="scanned"){(A=m.onScanned)==null||A.call(m,g);return}if(g.status==="verification_required"){(k=m.onVerificationRequired)==null||k.call(m,g);return}g.status&&Is.has(g.status)&&(c(),m.onTerminalError(g))}catch(g){if(u.aborted||h!==n)return;c(),m.onPollError(g)}finally{a===h&&(a=-1)}})())},f)},stop:c,isActive:(()=>s!==null)}},Us=({onLoginSuccess:t})=>{const[s,r]=l.useState(!1),[a,n]=l.useState(""),[c,i]=l.useState("pending"),[d,b]=l.useState(""),[m,f]=l.useState(""),[h,u]=l.useState(""),[A,k]=l.useState(null),g=l.useRef(null),p=l.useRef(null),E=l.useRef(null),B=l.useRef(null);g.current===null&&(g.current=Qs()),p.current===null&&(p.current=Ds());const G=()=>{B.current!==null&&(window.clearTimeout(B.current),B.current=null)},D=()=>{var w;(w=g.current)==null||w.stop()},S=()=>{var w,P;(w=E.current)==null||w.abort(),(P=p.current)==null||P.cancel(),D(),G(),r(!1)},j=()=>{G(),B.current=window.setTimeout(()=>{B.current=null,r(!1),t()},1e3)};l.useEffect(()=>()=>{var P,U;D(),(P=p.current)==null||P.cancel(),(U=E.current)==null||U.abort(),G()},[]);const N=async(w,P)=>{const U=await ns(w,P==null?void 0:P.id);if(!U.success||!U.account_id)throw new Error("保存扫码授权失败");return U.account_id};return{showQRModal:s,qrCodeUrl:a,qrStatus:c,qrErrorMessage:d,verificationScreenshot:m,faceQrUrl:h,qrReauthTarget:A,startQRLogin:async w=>{var X,V,H,z;D(),(X=E.current)==null||X.abort();const P=new AbortController;E.current=P;const U=p.current.next();G();const Y=w||null;k(Y),r(!0),i("loading"),b(""),n(""),f(""),u("");try{const I=await as({signal:P.signal});if(!((V=p.current)!=null&&V.isCurrent(U)))return;if(!I.success||!I.qr_code_url||!I.session_id)throw new Error(I.message||"闲鱼未返回可用的登录二维码");const W=I.session_id;n(I.qr_code_url),i("waiting"),(H=g.current)==null||H.start(W,rs,{onSuccess:(async()=>{try{await N(W,Y)}catch($){console.error("保存扫码授权失败",$),i("error");return}i("success"),j()}),onScanned:(()=>{i("waiting")}),onTerminalError:(()=>{i("error")}),onPollError:($=>{console.error("轮询扫码状态失败",$),i("error")}),onVerificationRequired:($=>{i("verification"),$.face_qr_url&&u($.face_qr_url),$.verification_screenshot&&f($.verification_screenshot)})})}catch(I){if(!((z=p.current)!=null&&z.isCurrent(U))||P.signal.aborted)return;b(I instanceof Error?I.message:"二维码获取失败,请稍后重试"),i("error")}finally{E.current===P&&(E.current=null)}},closeQRModal:S}},$s=(t,s)=>t&&s,Ms=(t,s)=>t!==(s.pause_duration||0),Bs=(t,s)=>{const r=s.username!==(t.username||""),a=s.show_browser!==(t.show_browser||!1),n=s.login_password!=="",c=s.clear_password===!0;if(!r&&!a&&!n&&!c)return null;const i={username:s.username,show_browser:s.show_browser};return c?i.clear_password=!0:n&&(i.login_password=s.login_password),i},F=(t,s,r,a)=>t===s&&r===a,Gs=t=>t.status==="success"?{sessionId:"",status:"success",message:t.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}:t.status==="processing"||t.status==="verification_required"?{sessionId:"",status:t.status,message:t.message||(t.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:t.qr_code_url||""}:{sessionId:"",status:"failed",message:t.error||t.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""},Os=({editingAccount:t,setEditingAccount:s,setActiveModal:r,editForm:a,setEditForm:n,loadAccounts:c})=>{const[i,d]=l.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[b,m]=l.useState([]),[f,h]=l.useState([]),[u,A]=l.useState(!1),[k,g]=l.useState(!1),[p,E]=l.useState(!1),[B,G]=l.useState(""),[D,S]=l.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[j,N]=l.useState(!1),[R,w]=l.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),P=l.useRef(0),U=l.useRef(null),Y=l.useRef(0),X=l.useRef(null),V=l.useRef(0),H=l.useRef(null),z=l.useRef(0),I=l.useRef(""),W=l.useRef(null),$=l.useRef(null),M=l.useCallback(()=>{$.current!==null&&(window.clearTimeout($.current),$.current=null)},[]),ee=l.useCallback(async o=>{var O;const x=++P.current;(O=U.current)==null||O.abort();const v=new AbortController;U.current=v,g(!0),A(!1),E(!1),G("");const[Q,_]=await Promise.allSettled([js({signal:v.signal}),ws(o,{signal:v.signal})]);F(x,P.current,o,o)&&(Q.status==="fulfilled"?m(Q.value.data||[]):(m([]),G("通知渠道列表加载失败,请重试")),_.status==="fulfilled"?(h(_.value||[]),A(!0)):(h([]),G("通知绑定加载失败;本次保存不会修改现有绑定")),g(!1))},[]),re=l.useCallback(o=>{h(x=>x.includes(o)?x.filter(v=>v!==o):[...x,o]),E(!0)},[]),C=l.useCallback(async o=>{var _,O;const x=++Y.current;(_=X.current)==null||_.abort();const v=new AbortController;X.current=v,z.current+=1,I.current=o.id,(O=W.current)==null||O.abort(),M(),w({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),s(o),n({remark:o.remark||"",cookie:"",auto_confirm:o.auto_confirm||!1,pause_duration:o.pause_duration||0,username:o.username||"",login_password:"",show_browser:o.show_browser||!1,showLoginPassword:!1,clear_password:!1}),r("edit"),d({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,Q]=await Promise.allSettled([ee(o.id),ds(o.id,{signal:v.signal})]);x===Y.current&&(Q.status==="fulfilled"?d({loading:!1,saving:!1,canOpen:Q.value.can_open_long_login,enabled:Q.value.enabled,error:""}):d({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"}))},[M,ee,r,n,s]),K=l.useCallback(async()=>{if(!t||i.loading||i.saving||!i.canOpen)return;const o=!i.enabled;d(x=>({...x,saving:!0,error:""}));try{const x=await us(t.id,o);d({loading:!1,saving:!1,canOpen:x.can_open_long_login,enabled:x.enabled,error:""})}catch(x){d(v=>({...v,saving:!1,error:x instanceof Error?x.message:"保存登录信息设置失败"}))}},[t,i]),se=l.useCallback(async o=>{var Q;const x=++V.current;(Q=H.current)==null||Q.abort();const v=new AbortController;H.current=v,s(o),r("ai-settings"),N(!0);try{const _=await ps(o.id,{signal:v.signal});if(!F(x,V.current,o.id,o.id))return;S({ai_enabled:_.ai_enabled??!1,max_discount_percent:_.max_discount_percent??10,max_discount_amount:_.max_discount_amount??100,max_bargain_rounds:_.max_bargain_rounds??3,custom_prompts:_.custom_prompts??""})}catch(_){F(x,V.current,o.id,o.id)&&console.error("加载 AI 设置失败:",_)}finally{F(x,V.current,o.id,o.id)&&N(!1)}},[r,s]),ue=l.useCallback(async()=>{if(!(!t||j)){N(!0);try{await fs(t.id,D),r(null),await c()}catch(o){console.error("更新 AI 设置失败:",o)}finally{N(!1)}}},[D,t,c,j,r]),xe=l.useCallback(async()=>{if(!(!t||j)){N(!0);try{const o={};a.remark!==(t.remark||"")&&(o.remark=a.remark),a.cookie&&(o.cookie=a.cookie),a.auto_confirm!==t.auto_confirm&&(o.auto_confirm=a.auto_confirm),Ms(a.pause_duration,t)&&(o.pause_duration=a.pause_duration);const x=Bs(t,a);x&&Object.assign(o,x),$s(u,p)&&(o.channel_ids=f),Object.keys(o).length>0&&await cs(t.id,o),r(null),await c()}catch(o){console.error("更新账号失败:",o)}finally{N(!1)}}},[p,u,a,t,c,f,j,r]),me=l.useCallback(async()=>{if(!(!t||a.pause_duration<=0||j)){N(!0);try{const o=await is(t.id,a.pause_duration);s(x=>x&&{...x,pause_duration:a.pause_duration,paused:(o==null?void 0:o.paused)===!0,paused_until:Number((o==null?void 0:o.paused_until)||0)}),await c()}catch(o){console.error("重新暂停失败:",o)}finally{N(!1)}}},[a.pause_duration,t,c,j,s]),ne=l.useCallback(async(o,x,v)=>{var _;(_=W.current)==null||_.abort();const Q=new AbortController;W.current=Q;try{const O=await ms(o,Q.signal);if(!F(x,z.current,v,I.current))return;const oe={...Gs(O),sessionId:o};if(O.status==="success"){M(),w(oe),n(pe=>({...pe,login_password:"",showLoginPassword:!1})),await c();return}if(O.status==="processing"||O.status==="verification_required"){w(oe),M(),$.current=window.setTimeout(()=>void ne(o,x,v),1500);return}M(),w(oe)}catch(O){if(!F(x,z.current,v,I.current))return;M(),w({sessionId:o,status:"failed",message:O instanceof Error?O.message:"查询密码登录状态失败",qrCodeUrl:""})}},[M,c,n]),be=l.useCallback(async()=>{var Q;if(!t)return;const o=a.username.trim();if(!o||!a.login_password)return;M(),(Q=W.current)==null||Q.abort();const x=++z.current;I.current=t.id;const v=new AbortController;W.current=v,w({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const _=await xs({account_id:t.id,account:o,password:a.login_password,show_browser:a.show_browser},{signal:v.signal});if(!F(x,z.current,t.id,I.current))return;if(!_.success||!_.session_id)throw new Error(_.message||"无法启动密码登录");w({sessionId:_.session_id,status:"processing",message:_.message||"登录处理中",qrCodeUrl:""}),await ne(_.session_id,x,t.id)}catch(_){if(!F(x,z.current,t.id,I.current))return;w({sessionId:"",status:"failed",message:_ instanceof Error?_.message:"启动密码登录失败",qrCodeUrl:""})}},[M,a.login_password,a.show_browser,a.username,t,ne]),le=l.useCallback(async()=>{var x;const o=R.sessionId;z.current+=1,I.current="",(x=W.current)==null||x.abort(),M(),o&&await bs(o).catch(()=>{}),w({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},[M,R.sessionId]),he=l.useCallback(async()=>{var o,x,v;(o=U.current)==null||o.abort(),Y.current+=1,(x=X.current)==null||x.abort(),(v=H.current)==null||v.abort(),(R.status==="processing"||R.status==="verification_required")&&await le(),r(null)},[le,R.status,r]),ge=l.useCallback(()=>{var o;V.current+=1,(o=H.current)==null||o.abort(),r(null)},[r]);return l.useEffect(()=>(()=>{var o,x,v,Q;(o=U.current)==null||o.abort(),(x=X.current)==null||x.abort(),(v=H.current)==null||v.abort(),(Q=W.current)==null||Q.abort(),M()}),[M]),{longLogin:i,notifChannels:b,selectedChannelIds:f,bindingsLoaded:u,bindingsLoading:k,bindingsDirty:p,bindingsLoadError:B,aiSettings:D,saving:j,passwordLoginView:R,setAiSettings:S,setBindingsDirty:E,setEditForm:n,openEditModal:C,closeEditModal:he,openAIModal:se,closeAIModal:ge,loadNotificationBindings:ee,toggleNotificationChannel:re,handleLongLoginToggle:K,handleSaveAISettings:ue,handleSaveEdit:xe,handleRestartPause:me,handlePasswordLogin:be,handleCancelPasswordLogin:le}},Js=()=>{const{accounts:t,setAccounts:s,loading:r,loadAccounts:a}=Es(),[n,c]=l.useState(""),[i,d]=l.useState(""),[b,m]=l.useState(""),[f,h]=l.useState(null),[u,A]=l.useState(""),[k,g]=l.useState(null),[p,E]=l.useState(null),[B,G]=l.useState(null),[D,S]=l.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),j=Os({editingAccount:p,setEditingAccount:E,setActiveModal:g,editForm:D,setEditForm:S,loadAccounts:a}),{longLogin:N,notifChannels:R,selectedChannelIds:w,bindingsLoaded:P,bindingsLoading:U,bindingsLoadError:Y,aiSettings:X,saving:V,passwordLoginView:H,setAiSettings:z,setBindingsDirty:I,openEditModal:W,closeEditModal:$,openAIModal:M,closeAIModal:ee,loadNotificationBindings:re,toggleNotificationChannel:C,handleLongLoginToggle:K,handleSaveAISettings:se,handleSaveEdit:ue,handleRestartPause:xe,handlePasswordLogin:me,handleCancelPasswordLogin:ne}=j,be=Us({onLoginSuccess:a}),{showQRModal:le,qrCodeUrl:he,qrStatus:ge,qrErrorMessage:o,verificationScreenshot:x,faceQrUrl:v,qrReauthTarget:Q,startQRLogin:_,closeQRModal:O}=be,oe=async(y,q)=>{await ls(y,!q),a()},pe=y=>{b||(A(""),h(y))},Qe=()=>{b||(A(""),h(null))},Ue=async()=>{const y=f;if(!(!y||b)){m(y.id),A("");try{await os(y.id),s(q=>q.filter(te=>te.id!==y.id)),h(null)}catch(q){console.error("删除账号失败:",q),A((q==null?void 0:q.message)||"删除账号失败,请稍后重试")}finally{m("")}}},$e=async y=>{d(y.id);try{const q=await hs(y.id);q!=null&&q.profile_error&&alert("资料刷新失败:"+q.profile_error),await a()}catch(q){console.error("刷新账号资料失败:",q),alert((q==null?void 0:q.message)||"刷新账号资料失败,请先重新授权该账号")}finally{d("")}};if(r)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(J,{className:"w-8 h-8 text-brand animate-spin"})});const fe=t.filter(y=>{const q=n.trim().toLowerCase();return q?[y.id,y.nickname,y.remark,y.username,y.runtime_message].some(te=>(te||"").toLowerCase().includes(q)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:n,onChange:(y=>c(y.target.value)),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:(()=>_()),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(_e,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",fe.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[fe.map(y=>e.jsx(Rs,{account:y,refreshing:i===y.id,deleting:b===y.id,onRefreshProfile:$e,onReauthorize:_,onEdit:W,onAI:M,onTasks:G,onToggle:oe,onDelete:pe},y.id)),t.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Ee,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),t.length>0&&fe.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),B&&ie.createPortal(e.jsx(vs,{account:B,onClose:(()=>G(null)),onSaved:(y=>{s(q=>q.map(te=>te.id===B.id?{...te,auto_rate_enabled:y.auto_rate_enabled,rate_content:y.rate_content,auto_polish_enabled:y.auto_polish_enabled,polish_time:y.polish_time,last_rate_scan_at:y.last_rate_scan_at,last_polish_date:y.last_polish_date,last_polish_at:y.last_polish_at}:te))})}),document.body),f&&e.jsx(As,{account:f,deleting:b===f.id,error:u,onClose:Qe,onConfirm:Ue}),le&&e.jsx(Ts,{target:Q,status:ge,codeUrl:he,errorMessage:o,faceQrUrl:v,verificationScreenshot:x,onClose:O}),k==="edit"&&p&&e.jsx(Ps,{account:p,editForm:D,setEditForm:S,saving:V,onClose:$,onSave:ue,onRestartPause:xe,longLogin:N,onToggleLongLogin:K,passwordLoginView:H,onPasswordLogin:me,onCancelPasswordLogin:ne,notifChannels:R,selectedChannelIds:w,bindingsLoaded:P,bindingsLoading:U,bindingsLoadError:Y,onRetryBindings:(()=>re(p.id)),onToggleChannel:C,onSettingsDirty:(()=>I(!0))}),k==="ai-settings"&&p&&e.jsx(_s,{account:p,settings:X,saving:V,onChange:z,onClose:ee,onSave:se})]})};export{Js as default}; diff --git a/internal/webui/static/assets/AccountList-DgwrfNi_.js b/internal/webui/static/assets/AccountList-DgwrfNi_.js deleted file mode 100644 index 52281f5..0000000 --- a/internal/webui/static/assets/AccountList-DgwrfNi_.js +++ /dev/null @@ -1,3 +0,0 @@ -import{b as ie,j as e,a as n,c as Oe}from"./react-vendor-l-BBvuKH.js";import{r as O,c as Pe,g as ce,o as qe,p as Le,a as G,b as Ge}from"./index-WrujSo30.js";import{n as ue,X as de,f as ze,L as J,o as Te,p as We,q as Ve,r as Ie,s as Ee,U as De,t as ae,u as Ke,k as _e,Q as Ne,v as $e,R as He,w as Je,x as Xe,y as ve,K as Ye,z as Ze,F as Fe,e as es,H as ss}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const ts=(t,s)=>{const r=t.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",s),a.toString()}catch{return r}},as=async t=>{const s=await O(l=>G.GET("/api/v1/accounts/details",{signal:l}),t),r=Pe(s,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ts(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},rs=async t=>await O(r=>G.GET("/api/v1/accounts/runtime-status",{signal:r}),t),ns=async t=>O(s=>G.POST("/api/v1/qr-login/generate",{signal:s}),{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),ls=async(t,s)=>O(r=>G.GET("/api/v1/qr-login/check/{session_id}",{params:{path:{session_id:t}},signal:r}),{signal:s,timeoutMs:1e4}),os=async(t,s)=>O(r=>G.POST("/api/v1/qr-login/complete-verification/{session_id}",{params:{path:{session_id:t}},body:{target_account_id:s||""},signal:r})),is=async(t,s)=>O(r=>G.PUT("/api/v1/accounts/{cid}/status",{params:{path:{cid:t}},body:{enabled:s},signal:r})),cs=async t=>O(s=>G.DELETE("/api/v1/accounts/{cid}",{params:{path:{cid:t}},signal:s})),ds=async(t,s,r)=>O(a=>G.PUT("/api/v1/accounts/{cid}/pause-duration",{params:{path:{cid:t}},body:{pause_duration:s},signal:a}),r),us=async(t,s,r)=>O(a=>G.PUT("/api/v1/accounts/{cid}/settings",{params:{path:{cid:t}},body:s,signal:a}),r),xs=async(t,s)=>O(r=>G.GET("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:t}},signal:r}),s),ms=async(t,s,r)=>O(a=>G.PUT("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:t}},body:{enabled:s},signal:a}),r),bs=async(t,s)=>O(r=>G.POST("/api/v1/password-login",{body:t,signal:r}),s),hs=async(t,s)=>O(a=>G.GET("/api/v1/password-login/check/{session_id}",{params:{path:{session_id:t}},signal:a}),{signal:s,timeoutMs:1e4}),gs=async(t,s)=>O(r=>G.DELETE("/api/v1/password-login/cancel/{session_id}",{params:{path:{session_id:t}},signal:r}),s),ps=async t=>O(s=>G.POST("/api/v1/accounts/{cid}/refresh-profile",{params:{path:{cid:t}},signal:s})),fs=async t=>{const s=await ce("/api/v1/settings/ai-reply",void 0,t);return qe(s,["settings","data","result"])||{}},ys=async(t,s)=>ce(`/api/v1/settings/ai-reply/${t}`,void 0,s),js=async(t,s,r)=>{const a={ai_enabled:s.ai_enabled??!1,max_discount_percent:s.max_discount_percent??10,max_discount_amount:s.max_discount_amount??100,max_bargain_rounds:s.max_bargain_rounds??3,custom_prompts:s.custom_prompts??""};return Le(`/api/v1/settings/ai-reply/${t}`,a,r)},ws=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const s=JSON.parse(t);if(Array.isArray(s))return s.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},_s=async t=>{const s=await ce("/api/v1/notifications/channels",void 0,t);return{success:!0,data:Pe(s,["data","channels","items"]).map(a=>{const l={},c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:ws(a.event_types),enabled:a.enabled}})}},Ns=async(t,s)=>{const r=await ce(`/api/v1/notifications/accounts/${t}/bindings`,void 0,s),a=qe(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},vs=({account:t,settings:s,saving:r,onChange:a,onClose:l,onSave:c})=>{const i=u=>a({...s,...u}),d=()=>i({ai_enabled:!s.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:l,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:d,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.ai_enabled?"bg-brand":"bg-gray-300"}`,"aria-label":"切换 AI 自动回复",children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:s.max_discount_percent,onChange:b,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:s.max_discount_amount,onChange:m,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:s.max_bargain_rounds,onChange:f,className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:s.custom_prompts,onChange:h,placeholder:`输入自定义的AI回复规则或风格指引... - -例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(ze,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(Te,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},ke=async(t,s)=>ce(`/api/v1/account-tasks/${t}`,void 0,s),Ce=async(t,s,r)=>Le(`/api/v1/account-tasks/${t}`,s,r),ks=async(t,s,r)=>Ge(`/api/v1/account-tasks/${t}/run`,{task_type:s},{timeoutMs:12e4,...r}),Se=t=>({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),Z=(t,s,r)=>t===s&&!r.aborted,je=(t,s)=>t instanceof Error?t.message:s,we=t=>t instanceof Error&&t.message==="请求已取消",Re=(t,s)=>!t&&s==="",Cs=({account:t,onSaved:s})=>{const[r,a]=n.useState(()=>Se(t)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var N;const S=++p.current;(N=L.current)==null||N.abort();const j=new AbortController;return L.current=j,a(Se(t)),A(null),h(""),d(!1),m(""),g(null),c(!0),ke(t.id,{signal:j.signal}).then(R=>{Z(p.current,S,j.signal)&&a(R)}).catch(R=>{Z(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Z(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[t.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var N;if(!Re(i,b))return;const S=++p.current;(N=L.current)==null||N.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Ce(t.id,r,{signal:j.signal});if(!Z(p.current,S,j.signal))return;a(R),s(R)}catch(R){Z(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Z(p.current,S,j.signal)&&d(!1)}},[t.id,r,s,b,i]),M=n.useCallback(async S=>{var R;if(!Re(i,b)||!t.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const N=new AbortController;L.current=N,m(S),h(""),A(null),g(null);try{await Ce(t.id,r,{signal:N.signal});const w=await ks(t.id,S,{signal:N.signal}),P=await ke(t.id,{signal:N.signal});if(!Z(p.current,j,N.signal))return;A(w.summary),a(P),s(P)}catch(w){Z(p.current,j,N.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Z(p.current,j,N.signal)&&m("")}},[t.enabled,t.id,r,s,b,i]),I=n.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:l,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:U,run:M,retry:I}},Ae=({checked:t,onChange:s,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":t,onClick:s,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6":""}`})}),Ss=({account:t,onClose:s,onSaved:r})=>{const{form:a,loading:l,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=Cs({account:t,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:s,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(de,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[l&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",children:"正在读取任务设置..."}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(We,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(Ae,{checked:a.auto_rate_enabled,onChange:(()=>f(k=>({...k,auto_rate_enabled:!k.auto_rate_enabled}))),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:a.rate_content,maxLength:500,onChange:(k=>f(g=>({...g,rate_content:k.target.value}))),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",a.last_rate_scan_at?new Date(a.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:i!==""||!t.enabled,onClick:(()=>void u("auto_rate")),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[i==="auto_rate"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Ve,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(Ie,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(Ae,{checked:a.auto_polish_enabled,onChange:(()=>f(k=>({...k,auto_polish_enabled:!k.auto_polish_enabled}))),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:a.polish_time,onChange:(k=>f(g=>({...g,polish_time:k.target.value}))),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:i!==""||!t.enabled,onClick:(()=>void u("auto_polish")),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[i==="auto_polish"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Ee,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",a.last_polish_at?new Date(a.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),b&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",b.found," 项,成功 ",b.success,",失败 ",b.failed,",跳过 ",b.skipped,"。",b.message||""]}),d&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:[e.jsx("span",{children:d}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void A()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:s,disabled:c||i!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:(()=>void h()),disabled:c||i!==""||a.auto_rate_enabled&&!a.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[c?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"保存"]})]})})]})})},Rs=(t,s)=>{if(!t||!s)return!1;const r=Date.parse(t),a=Date.parse(s);return Number.isFinite(r)&&Number.isFinite(a)&&at.map(r=>{const a=s[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}}),Ps=t=>{if(!t.enabled||t.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(t.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"runtime_conflict":return{label:"运行状态冲突",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},qs=Oe.memo(function({account:s,refreshing:r,deleting:a,onRefreshProfile:l,onReauthorize:c,onEdit:i,onAI:d,onTasks:b,onToggle:m,onDelete:f}){const h=Ps(s),u=s.runtime_state==="auth_expired"||s.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:[s.avatar_url?e.jsx("img",{src:s.avatar_url,alt:s.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(De,{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:s.runtime_state==="online"&&e.jsx(ae,{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:s.nickname||s.remark||`账号 ${s.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}),s.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"]}),s.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(Ke,{className:"h-3 w-3"})," 自动评价"]}),s.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"})," 每日擦亮"]}),s.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(ae,{className:"h-3 w-3"})," 自动确认发货"]}),s.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:s.profile_error,children:[e.jsx(_e,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"text-sm font-medium text-gray-500",children:[e.jsx("p",{children:s.remark||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",s.id]})]}),s.runtime_message&&s.runtime_state!=="online"&&s.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${u?"text-red-700":"text-amber-700"}`,children:[e.jsx(_e,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:s.runtime_message}),u&&e.jsxs("button",{type:"button",onClick:(()=>c(s)),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(Ne,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),s.paused&&e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700",children:[e.jsx($e,{className:"h-3 w-3"})," 暂停处理中"]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:(()=>l(s)),disabled:r,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(He,{className:`w-5 h-5 ${r?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>c(s)),className:`p-3 rounded-xl transition-colors ${u?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Ne,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>i(s)),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Je,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>d(s)),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(ue,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>b(s)),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Ee,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>m(s.id,s.enabled)),className:`p-3 rounded-xl transition-colors ${s.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:s.enabled?"停用账号":"启用账号",children:e.jsx(Xe,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>f(s)),disabled:a,className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:a?"删除中…":`删除账号 ${s.nickname||s.remark||s.id}`,children:a?e.jsx(J,{className:"w-5 h-5 animate-spin"}):e.jsx(ve,{className:"w-5 h-5"})})]})]})]})]})})}),Ls=({account:t,deleting:s,error:r,onClose:a,onConfirm:l})=>ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",role:"presentation",children:e.jsxs("div",{className:"h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal",role:"dialog","aria-modal":"true","aria-labelledby":"delete-account-title","aria-describedby":"delete-account-description",children:[e.jsxs("div",{className:"relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5",children:[e.jsx("div",{className:"absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl"}),e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200",children:e.jsx(ve,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{id:"delete-account-title",className:"text-lg font-extrabold tracking-tight text-gray-950",children:"删除这个账号?"}),e.jsx("p",{id:"delete-account-description",className:"mt-1 text-xs leading-5 text-gray-600",children:"删除后,该账号的关联配置也会一并清理,此操作无法撤销。"})]}),e.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"关闭删除确认",children:e.jsx(de,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:t.nickname||t.remark||"未命名账号"}),t.remark&&t.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",t.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",t.id]})]}),s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(J,{className:"h-5 w-5 flex-shrink-0 animate-spin text-brand"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-blue-950",children:"正在删除账号"}),e.jsx("div",{className:"mt-0.5 text-xs text-blue-700",children:"正在清理关联数据,请保持页面打开…"})]})]}),r&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3",role:"alert",children:[e.jsx(_e,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-red-800",children:"删除失败"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-red-700",children:r})]})]})]}),e.jsxs("div",{className:"flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4",children:[e.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50",children:"取消"}),e.jsx("button",{type:"button",onClick:(()=>void l()),disabled:s,className:"flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400",children:s?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),Qe=({src:t,alt:s,className:r=""})=>e.jsx("img",{src:t,alt:s,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),Ts=({account:t,editForm:s,setEditForm:r,saving:a,onClose:l,onSave:c,onRestartPause:i,longLogin:d,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:f,onCancelPasswordLogin:h,notifChannels:u,selectedChannelIds:A,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:p,onRetryBindings:L,onToggleChannel:U,onSettingsDirty:M})=>{const I=(C,K)=>{r(se=>({...se,[C]:K}))},S=()=>void l(),j=()=>void c(),N=C=>I("remark",C.target.value),R=C=>I("cookie",C.target.value),w=()=>I("auto_confirm",!s.auto_confirm),P=C=>I("pause_duration",parseInt(C.target.value,10)||0),D=()=>void i(),Y=()=>void b(),X=C=>I("username",C.target.value),V=C=>r(K=>({...K,login_password:C.target.value,clear_password:!1})),H=()=>I("showLoginPassword",!s.showLoginPassword),z=C=>r(K=>({...K,clear_password:C.target.checked,login_password:C.target.checked?"":K.login_password})),T=()=>I("show_browser",!s.show_browser),W=()=>void h(),$=()=>void f(),Q=()=>void L(),ee=C=>{k&&(U(C),M())},re=C=>{const K=A.includes(Number(C.id)),se=()=>ee(Number(C.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:se,disabled:!k,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${K?"bg-brand border-brand":"bg-white border-gray-300"}`,children:K&&e.jsx(ae,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:C.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[C.type,C.enabled?"":" · 已停用"]})]})]},C.id)};return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:t.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:s.remark,onChange:N,placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:s.cookie,onChange:R,placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",s.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ae,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:w,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.auto_confirm?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx($e,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:s.pause_duration,onChange:P,placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),s.pause_duration>0&&!t.paused&&s.pause_duration===(t.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:D,className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(Ye,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),d.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:d.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:d.loading||d.saving||!d.canOpen,onClick:Y,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${d.enabled?"bg-brand":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${d.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:s.username,onChange:X,placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:s.showLoginPassword?"text":"password",value:s.login_password,onChange:V,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:H,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:s.showLoginPassword?e.jsx(Ze,{className:"w-5 h-5"}):e.jsx(Fe,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:s.clear_password,onChange:z,className:"w-4 h-4 accent-brand"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:T,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.show_browser?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),m.status==="processing"||m.status==="verification_required"?e.jsx("button",{type:"button",onClick:W,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:$,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),m.message&&e.jsx("div",{className:`text-sm font-medium ${m.status==="failed"?"text-red-700":m.status==="success"?"text-green-700":"text-blue-800"}`,children:m.message}),m.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),m.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Qe,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(u.length>0||g||p)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(es,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),g&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(J,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),p&&!g&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:p}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:Q,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:u.map(re)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:S,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:a,children:"取消"}),e.jsxs("button",{onClick:j,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:a,children:[a?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(ae,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},Is=({faceQrUrl:t,verificationScreenshot:s})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(ss,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:t?e.jsx("img",{src:t,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):s?e.jsx("img",{src:s,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(J,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),Es=({target:t,status:s,codeUrl:r,errorMessage:a,faceQrUrl:l,verificationScreenshot:c,onClose:i})=>ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:i,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors","aria-label":"关闭二维码登录",children:e.jsx(de,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:t?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:t?`请用闲鱼APP扫码,为「${t.nickname||t.remark||t.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${s==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[s==="loading"&&e.jsx(J,{className:"w-10 h-10 text-brand animate-spin"}),s==="waiting"&&e.jsx(Qe,{src:r,alt:"闲鱼登录二维码",className:"p-2"}),s==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(ae,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),s==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:a||"请关闭窗口后重新发起扫码登录。"})]}),s==="verification"&&e.jsx(Is,{faceQrUrl:l,verificationScreenshot:c})]}),s!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),Ds=(t,s)=>t.map(r=>{var a,l,c,i,d;return{...r,ai_enabled:((a=s[r.id])==null?void 0:a.ai_enabled)??!1,max_discount_percent:((l=s[r.id])==null?void 0:l.max_discount_percent)??10,max_discount_amount:((c=s[r.id])==null?void 0:c.max_discount_amount)??100,max_bargain_rounds:((i=s[r.id])==null?void 0:i.max_bargain_rounds)??3,custom_prompts:((d=s[r.id])==null?void 0:d.custom_prompts)??""}}),$s=()=>{const[t,s]=n.useState([]),[r,a]=n.useState(!0),l=n.useRef(0),c=n.useRef(null),i=n.useCallback(async()=>{var m;const d=++l.current;(m=c.current)==null||m.abort();const b=new AbortController;c.current=b,a(!0);try{const f={signal:b.signal},[h,u]=await Promise.allSettled([as(f),fs(f)]);if(d!==l.current)return;if(h.status==="rejected")throw h.reason;const A=u.status==="fulfilled"?u.value:{};u.status==="rejected"&&console.error("加载 AI 设置失败:",u.reason),s(Ds(h.value,A))}catch(f){d===l.current&&!b.signal.aborted&&console.error("加载账号失败:",f)}finally{d===l.current&&a(!1)}},[]);return n.useEffect(()=>{let d=!1,b=null;const m=new AbortController,f=async()=>{try{const u=await rs({signal:m.signal,timeoutMs:1e4});d||s(A=>As(A,u))}catch(u){d||console.error("加载账号运行状态失败:",u)}finally{d||(b=window.setTimeout(()=>void f(),2e3))}};return i().finally(()=>{d||f()}),()=>{var u;d=!0,m.abort(),l.current+=1,(u=c.current)==null||u.abort(),b!==null&&window.clearTimeout(b)}},[i]),{accounts:t,setAccounts:s,loading:r,loadAccounts:i}},Qs=new Set(["expired","cancelled","error","not_found"]),Us=()=>{let t=0;return{next:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:(s=>s===t)}},Ms=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let s=null,r=null,a=-1,l=0;const c=()=>{l+=1,r==null||r.abort(),r=null,s!==null&&(t.clearInterval(s),s=null)};return{start:(d,b,m,f=2e3)=>{c();const h=l;r=new AbortController;const u=r.signal;s=t.setInterval(()=>{a===h||h!==l||(a=h,(async()=>{var A,k;try{const g=await b(d,u);if(g.status==="success"){c(),await m.onSuccess(g);return}if(g.status==="scanned"){(A=m.onScanned)==null||A.call(m,g);return}if(g.status==="verification_required"){(k=m.onVerificationRequired)==null||k.call(m,g);return}g.status&&Qs.has(g.status)&&(c(),m.onTerminalError(g))}catch(g){if(u.aborted||h!==l)return;c(),m.onPollError(g)}finally{a===h&&(a=-1)}})())},f)},stop:c,isActive:(()=>s!==null)}},Bs=({onLoginSuccess:t})=>{const[s,r]=n.useState(!1),[a,l]=n.useState(""),[c,i]=n.useState("pending"),[d,b]=n.useState(""),[m,f]=n.useState(""),[h,u]=n.useState(""),[A,k]=n.useState(null),g=n.useRef(null),p=n.useRef(null),L=n.useRef(null),U=n.useRef(null);g.current===null&&(g.current=Ms()),p.current===null&&(p.current=Us());const M=()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},I=()=>{var w;(w=g.current)==null||w.stop()},S=()=>{var w,P;(w=L.current)==null||w.abort(),(P=p.current)==null||P.cancel(),I(),M(),r(!1)},j=()=>{M(),U.current=window.setTimeout(()=>{U.current=null,r(!1),t()},1e3)};n.useEffect(()=>()=>{var P,D;I(),(P=p.current)==null||P.cancel(),(D=L.current)==null||D.abort(),M()},[]);const N=async(w,P)=>{const D=await os(w,P==null?void 0:P.id);if(!D.success||!D.account_id)throw new Error("保存扫码授权失败");return D.account_id};return{showQRModal:s,qrCodeUrl:a,qrStatus:c,qrErrorMessage:d,verificationScreenshot:m,faceQrUrl:h,qrReauthTarget:A,startQRLogin:async w=>{var X,V,H,z;I(),(X=L.current)==null||X.abort();const P=new AbortController;L.current=P;const D=p.current.next();M();const Y=w||null;k(Y),r(!0),i("loading"),b(""),l(""),f(""),u("");try{const T=await ns({signal:P.signal});if(!((V=p.current)!=null&&V.isCurrent(D)))return;if(!T.success||!T.qr_code_url||!T.session_id)throw new Error(T.message||"闲鱼未返回可用的登录二维码");const W=T.session_id;l(T.qr_code_url),i("waiting"),(H=g.current)==null||H.start(W,ls,{onSuccess:(async()=>{try{await N(W,Y)}catch($){console.error("保存扫码授权失败",$),i("error");return}i("success"),j()}),onScanned:(()=>{i("waiting")}),onTerminalError:(()=>{i("error")}),onPollError:($=>{console.error("轮询扫码状态失败",$),i("error")}),onVerificationRequired:($=>{i("verification"),$.face_qr_url&&u($.face_qr_url),$.verification_screenshot&&f($.verification_screenshot)})})}catch(T){if(!((z=p.current)!=null&&z.isCurrent(D))||P.signal.aborted)return;b(T instanceof Error?T.message:"二维码获取失败,请稍后重试"),i("error")}finally{L.current===P&&(L.current=null)}},closeQRModal:S}},Os=(t,s)=>t&&s,Gs=(t,s)=>t!==(s.pause_duration||0),zs=(t,s)=>{const r=s.username!==(t.username||""),a=s.show_browser!==(t.show_browser||!1),l=s.login_password!=="",c=s.clear_password===!0;if(!r&&!a&&!l&&!c)return null;const i={username:s.username,show_browser:s.show_browser};return c?i.clear_password=!0:l&&(i.login_password=s.login_password),i},F=(t,s,r,a)=>t===s&&r===a,Ws=t=>t.status==="success"?{sessionId:"",status:"success",message:t.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}:t.status==="processing"||t.status==="verification_required"?{sessionId:"",status:t.status,message:t.message||(t.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:t.qr_code_url||""}:{sessionId:"",status:"failed",message:t.error||t.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""},Vs=({editingAccount:t,setEditingAccount:s,setActiveModal:r,editForm:a,setEditForm:l,loadAccounts:c})=>{const[i,d]=n.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[b,m]=n.useState([]),[f,h]=n.useState([]),[u,A]=n.useState(!1),[k,g]=n.useState(!1),[p,L]=n.useState(!1),[U,M]=n.useState(""),[I,S]=n.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[j,N]=n.useState(!1),[R,w]=n.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),P=n.useRef(0),D=n.useRef(null),Y=n.useRef(0),X=n.useRef(null),V=n.useRef(0),H=n.useRef(null),z=n.useRef(0),T=n.useRef(""),W=n.useRef(null),$=n.useRef(null),Q=n.useCallback(()=>{$.current!==null&&(window.clearTimeout($.current),$.current=null)},[]),ee=n.useCallback(async o=>{var B;const x=++P.current;(B=D.current)==null||B.abort();const v=new AbortController;D.current=v,g(!0),A(!1),L(!1),M("");const[E,_]=await Promise.allSettled([_s({signal:v.signal}),Ns(o,{signal:v.signal})]);F(x,P.current,o,o)&&(E.status==="fulfilled"?m(E.value.data||[]):(m([]),M("通知渠道列表加载失败,请重试")),_.status==="fulfilled"?(h(_.value||[]),A(!0)):(h([]),M("通知绑定加载失败;本次保存不会修改现有绑定")),g(!1))},[]),re=n.useCallback(o=>{h(x=>x.includes(o)?x.filter(v=>v!==o):[...x,o]),L(!0)},[]),C=n.useCallback(async o=>{var _,B;const x=++Y.current;(_=X.current)==null||_.abort();const v=new AbortController;X.current=v,z.current+=1,T.current=o.id,(B=W.current)==null||B.abort(),Q(),w({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),s(o),l({remark:o.remark||"",cookie:"",auto_confirm:o.auto_confirm||!1,pause_duration:o.pause_duration||0,username:o.username||"",login_password:"",show_browser:o.show_browser||!1,showLoginPassword:!1,clear_password:!1}),r("edit"),d({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,E]=await Promise.allSettled([ee(o.id),xs(o.id,{signal:v.signal})]);x===Y.current&&(E.status==="fulfilled"?d({loading:!1,saving:!1,canOpen:E.value.can_open_long_login,enabled:E.value.enabled,error:""}):d({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"}))},[Q,ee,r,l,s]),K=n.useCallback(async()=>{if(!t||i.loading||i.saving||!i.canOpen)return;const o=!i.enabled;d(x=>({...x,saving:!0,error:""}));try{const x=await ms(t.id,o);d({loading:!1,saving:!1,canOpen:x.can_open_long_login,enabled:x.enabled,error:""})}catch(x){d(v=>({...v,saving:!1,error:x instanceof Error?x.message:"保存登录信息设置失败"}))}},[t,i]),se=n.useCallback(async o=>{var E;const x=++V.current;(E=H.current)==null||E.abort();const v=new AbortController;H.current=v,s(o),r("ai-settings"),N(!0);try{const _=await ys(o.id,{signal:v.signal});if(!F(x,V.current,o.id,o.id))return;S({ai_enabled:_.ai_enabled??!1,max_discount_percent:_.max_discount_percent??10,max_discount_amount:_.max_discount_amount??100,max_bargain_rounds:_.max_bargain_rounds??3,custom_prompts:_.custom_prompts??""})}catch(_){F(x,V.current,o.id,o.id)&&console.error("加载 AI 设置失败:",_)}finally{F(x,V.current,o.id,o.id)&&N(!1)}},[r,s]),xe=n.useCallback(async()=>{if(!(!t||j)){N(!0);try{await js(t.id,I),r(null),await c()}catch(o){console.error("更新 AI 设置失败:",o)}finally{N(!1)}}},[I,t,c,j,r]),me=n.useCallback(async()=>{if(!(!t||j)){N(!0);try{const o={};a.remark!==(t.remark||"")&&(o.remark=a.remark),a.cookie&&(o.cookie=a.cookie),a.auto_confirm!==t.auto_confirm&&(o.auto_confirm=a.auto_confirm),Gs(a.pause_duration,t)&&(o.pause_duration=a.pause_duration);const x=zs(t,a);x&&Object.assign(o,x),Os(u,p)&&(o.channel_ids=f),Object.keys(o).length>0&&await us(t.id,o),r(null),await c()}catch(o){console.error("更新账号失败:",o)}finally{N(!1)}}},[p,u,a,t,c,f,j,r]),be=n.useCallback(async()=>{if(!(!t||a.pause_duration<=0||j)){N(!0);try{const o=await ds(t.id,a.pause_duration);s(x=>x&&{...x,pause_duration:a.pause_duration,paused:(o==null?void 0:o.paused)===!0,paused_until:Number((o==null?void 0:o.paused_until)||0)}),await c()}catch(o){console.error("重新暂停失败:",o)}finally{N(!1)}}},[a.pause_duration,t,c,j,s]),ne=n.useCallback(async(o,x,v)=>{var _;(_=W.current)==null||_.abort();const E=new AbortController;W.current=E;try{const B=await hs(o,E.signal);if(!F(x,z.current,v,T.current))return;const oe={...Ws(B),sessionId:o};if(B.status==="success"){Q(),w(oe),l(fe=>({...fe,login_password:"",showLoginPassword:!1})),await c();return}if(B.status==="processing"||B.status==="verification_required"){w(oe),Q(),$.current=window.setTimeout(()=>void ne(o,x,v),1500);return}Q(),w(oe)}catch(B){if(!F(x,z.current,v,T.current))return;Q(),w({sessionId:o,status:"failed",message:B instanceof Error?B.message:"查询密码登录状态失败",qrCodeUrl:""})}},[Q,c,l]),he=n.useCallback(async()=>{var E;if(!t)return;const o=a.username.trim();if(!o||!a.login_password)return;Q(),(E=W.current)==null||E.abort();const x=++z.current;T.current=t.id;const v=new AbortController;W.current=v,w({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const _=await bs({account_id:t.id,account:o,password:a.login_password,show_browser:a.show_browser},{signal:v.signal});if(!F(x,z.current,t.id,T.current))return;if(!_.success||!_.session_id)throw new Error(_.message||"无法启动密码登录");w({sessionId:_.session_id,status:"processing",message:_.message||"登录处理中",qrCodeUrl:""}),await ne(_.session_id,x,t.id)}catch(_){if(!F(x,z.current,t.id,T.current))return;w({sessionId:"",status:"failed",message:_ instanceof Error?_.message:"启动密码登录失败",qrCodeUrl:""})}},[Q,a.login_password,a.show_browser,a.username,t,ne]),le=n.useCallback(async()=>{var x;const o=R.sessionId;z.current+=1,T.current="",(x=W.current)==null||x.abort(),Q(),o&&await gs(o).catch(()=>{}),w({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},[Q,R.sessionId]),ge=n.useCallback(async()=>{var o,x,v;(o=D.current)==null||o.abort(),Y.current+=1,(x=X.current)==null||x.abort(),(v=H.current)==null||v.abort(),(R.status==="processing"||R.status==="verification_required")&&await le(),r(null)},[le,R.status,r]),pe=n.useCallback(()=>{var o;V.current+=1,(o=H.current)==null||o.abort(),r(null)},[r]);return n.useEffect(()=>(()=>{var o,x,v,E;(o=D.current)==null||o.abort(),(x=X.current)==null||x.abort(),(v=H.current)==null||v.abort(),(E=W.current)==null||E.abort(),Q()}),[Q]),{longLogin:i,notifChannels:b,selectedChannelIds:f,bindingsLoaded:u,bindingsLoading:k,bindingsDirty:p,bindingsLoadError:U,aiSettings:I,saving:j,passwordLoginView:R,setAiSettings:S,setBindingsDirty:L,setEditForm:l,openEditModal:C,closeEditModal:ge,openAIModal:se,closeAIModal:pe,loadNotificationBindings:ee,toggleNotificationChannel:re,handleLongLoginToggle:K,handleSaveAISettings:xe,handleSaveEdit:me,handleRestartPause:be,handlePasswordLogin:he,handleCancelPasswordLogin:le}},Ys=()=>{const{accounts:t,setAccounts:s,loading:r,loadAccounts:a}=$s(),[l,c]=n.useState(""),[i,d]=n.useState(""),[b,m]=n.useState(""),[f,h]=n.useState(null),[u,A]=n.useState(""),[k,g]=n.useState(null),[p,L]=n.useState(null),[U,M]=n.useState(null),[I,S]=n.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),j=Vs({editingAccount:p,setEditingAccount:L,setActiveModal:g,editForm:I,setEditForm:S,loadAccounts:a}),{longLogin:N,notifChannels:R,selectedChannelIds:w,bindingsLoaded:P,bindingsLoading:D,bindingsLoadError:Y,aiSettings:X,saving:V,passwordLoginView:H,setAiSettings:z,setBindingsDirty:T,openEditModal:W,closeEditModal:$,openAIModal:Q,closeAIModal:ee,loadNotificationBindings:re,toggleNotificationChannel:C,handleLongLoginToggle:K,handleSaveAISettings:se,handleSaveEdit:xe,handleRestartPause:me,handlePasswordLogin:be,handleCancelPasswordLogin:ne}=j,he=Bs({onLoginSuccess:a}),{showQRModal:le,qrCodeUrl:ge,qrStatus:pe,qrErrorMessage:o,verificationScreenshot:x,faceQrUrl:v,qrReauthTarget:E,startQRLogin:_,closeQRModal:B}=he,oe=async(y,q)=>{await is(y,!q),a()},fe=y=>{b||(A(""),h(y))},Ue=()=>{b||(A(""),h(null))},Me=async()=>{const y=f;if(!(!y||b)){m(y.id),A("");try{await cs(y.id),s(q=>q.filter(te=>te.id!==y.id)),h(null)}catch(q){console.error("删除账号失败:",q),A((q==null?void 0:q.message)||"删除账号失败,请稍后重试")}finally{m("")}}},Be=async y=>{d(y.id);try{const q=await ps(y.id);q!=null&&q.profile_error&&alert("资料刷新失败:"+q.profile_error),await a()}catch(q){console.error("刷新账号资料失败:",q),alert((q==null?void 0:q.message)||"刷新账号资料失败,请先重新授权该账号")}finally{d("")}};if(r)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(J,{className:"w-8 h-8 text-brand animate-spin"})});const ye=t.filter(y=>{const q=l.trim().toLowerCase();return q?[y.id,y.nickname,y.remark,y.username,y.runtime_message].some(te=>(te||"").toLowerCase().includes(q)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:l,onChange:(y=>c(y.target.value)),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:(()=>_()),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ne,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",ye.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[ye.map(y=>e.jsx(qs,{account:y,refreshing:i===y.id,deleting:b===y.id,onRefreshProfile:Be,onReauthorize:_,onEdit:W,onAI:Q,onTasks:M,onToggle:oe,onDelete:fe},y.id)),t.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(De,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),t.length>0&&ye.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),U&&ie.createPortal(e.jsx(Ss,{account:U,onClose:(()=>M(null)),onSaved:(y=>{s(q=>q.map(te=>te.id===U.id?{...te,auto_rate_enabled:y.auto_rate_enabled,rate_content:y.rate_content,auto_polish_enabled:y.auto_polish_enabled,polish_time:y.polish_time,last_rate_scan_at:y.last_rate_scan_at,last_polish_date:y.last_polish_date,last_polish_at:y.last_polish_at}:te))})}),document.body),f&&e.jsx(Ls,{account:f,deleting:b===f.id,error:u,onClose:Ue,onConfirm:Me}),le&&e.jsx(Es,{target:E,status:pe,codeUrl:ge,errorMessage:o,faceQrUrl:v,verificationScreenshot:x,onClose:B}),k==="edit"&&p&&e.jsx(Ts,{account:p,editForm:I,setEditForm:S,saving:V,onClose:$,onSave:xe,onRestartPause:me,longLogin:N,onToggleLongLogin:K,passwordLoginView:H,onPasswordLogin:be,onCancelPasswordLogin:ne,notifChannels:R,selectedChannelIds:w,bindingsLoaded:P,bindingsLoading:D,bindingsLoadError:Y,onRetryBindings:(()=>re(p.id)),onToggleChannel:C,onSettingsDirty:(()=>T(!0))}),k==="ai-settings"&&p&&e.jsx(vs,{account:p,settings:X,saving:V,onChange:z,onClose:ee,onSave:se})]})};export{Ys as default}; diff --git a/internal/webui/static/assets/CardList-CfmBeFUG.js b/internal/webui/static/assets/CardList-DDZ2JnUG.js similarity index 70% rename from internal/webui/static/assets/CardList-CfmBeFUG.js rename to internal/webui/static/assets/CardList-DDZ2JnUG.js index f4e8fd7..eedf193 100644 --- a/internal/webui/static/assets/CardList-CfmBeFUG.js +++ b/internal/webui/static/assets/CardList-DDZ2JnUG.js @@ -1,17 +1,17 @@ -import{a as i,b as z,j as e}from"./react-vendor-l-BBvuKH.js";import{g as Z,c as ee,p as te,e as ae,b as H,d as se}from"./index-WrujSo30.js";import{X as G,W as le,J as O,Y as ne,L as V,N as U,C as W,_ as re,$ as X,a0 as Y,a1 as oe,I as ie,a2 as ce,V as de,y as xe,P as pe,o as me}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const he=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ue=async l=>{const n=await Z("/api/v1/cards",void 0,l);return ee(n,["cards","data","items"]).map(he)},be=async l=>H("/api/v1/cards",K(l)),J=async(l,n)=>te(`/api/v1/cards/${l}`,K(n)),ge=async l=>ae(`/api/v1/cards/${l}`),ye=async(l,n)=>{const a=new FormData;return a.append("file",l),se("/api/v1/cards/batch",a,n)},fe=async(l,n,a)=>H(`/api/v1/cards/${l}/append-data`,{content:n},a),je=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(` -`).map(n=>n.trim()).filter(Boolean),Ne=(l,n,a)=>!!(l&&Q(n).length>0&&!a),F=(l,n,a,u)=>l===n&&a===u,q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),D=(l,n)=>l instanceof Error?l.message:n,ve=({cards:l,loadCards:n})=>{const[a,u]=i.useState(!1),[m,_]=i.useState(!1),[f,j]=i.useState(null),[d,A]=i.useState({}),[c,y]=i.useState(q),[N,b]=i.useState(""),[r,x]=i.useState(""),s=i.useMemo(()=>l.filter(o=>o.type==="data"),[l]),h=i.useMemo(()=>je(l,N,r),[l,r,N]),E=i.useCallback(o=>{var t,g,k,S,C;j(o),A({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),u(!0)},[]),M=i.useCallback(async()=>{var o,t,g,k,S,C,p,B;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((p=d.data_content)==null?void 0:p.trim())||"":d.type==="image"&&(w.image_url=((B=d.image_url)==null?void 0:B.trim())||""),await J(f.id,w),u(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(D(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await ge(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(D(t,"删除失败,请重试"))}},[n]),v=i.useCallback(async()=>{if(!c.name.trim()){alert("请输入卡密名称");return}if(!c.content.trim()){alert(c.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:c.name.trim(),type:c.type,description:c.description.trim(),enabled:c.enabled,delay_seconds:c.delay_seconds};c.type==="text"&&(o.text_content=c.content.trim()),c.type==="data"&&(o.data_content=c.content.trim()),c.type==="image"&&(o.image_url=c.content.trim()),c.type==="api"&&(o.api_config={url:c.content.trim(),method:c.api_method,timeout:c.api_timeout,headers:c.api_headers.trim()||void 0,params:c.api_params.trim()||void 0}),await be(o),_(!1),y(q()),await n()}catch(o){console.error("添加卡密失败:",o),alert(D(o,"添加失败,请重试"))}},[c,n]),T=i.useCallback(async o=>{try{await J(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),P=i.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),$=i.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 +import{a as c,b as U,j as e}from"./react-vendor-l-BBvuKH.js";import{r as M,c as O,a as ee}from"./index-CiBUw4Te.js";import{c as te}from"./contract-COFcZjyb.js";import{X as V,W as ae,J as z,Y as se,L as q,N as J,C as X,_ as le,$ as Y,a0 as K,a1 as ne,I as re,a2 as oe,V as ce,y as ie,P as de,o as xe}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const pe=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},Q=l=>({name:l.name,type:l.type,api_config:l.api_config?JSON.stringify(l.api_config):"",text_content:l.text_content,data_content:l.data_content,image_url:l.image_url,description:l.description,enabled:l.enabled,delay_seconds:l.delay_seconds,is_multi_spec:l.is_multi_spec,spec_name:l.spec_name,spec_value:l.spec_value}),me=async l=>{const n=await M(p=>O.GET("/api/v1/cards",{signal:p}),l);return te(n,["cards","data","items"]).map(pe)},he=async l=>M(n=>O.POST("/api/v1/cards",{body:Q(l),signal:n})),H=async(l,n)=>M(a=>O.PUT("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},body:Q(n),signal:a})),ue=async l=>M(n=>O.DELETE("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},signal:n})),be=async(l,n)=>{const a=new FormData;return a.append("file",l),M(p=>O.POST("/api/v1/cards/batch",{body:ee(a),signal:p}),n)},ge=async(l,n,a)=>M(p=>O.POST("/api/v1/cards/{card_id}/append-data",{params:{path:{card_id:String(l)}},body:{content:n},signal:p}),a),ye=(l,n,a)=>{const p=a.trim().toLocaleLowerCase();return l.filter(h=>(!n||h.type===n)&&(!p||h.name.toLocaleLowerCase().includes(p)))},Z=l=>l.split(` +`).map(n=>n.trim()).filter(Boolean),fe=(l,n,a)=>!!(l&&Z(n).length>0&&!a),F=(l,n,a,p)=>l===n&&a===p,W=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),G=(l,n)=>l instanceof Error?l.message:n,je=({cards:l,loadCards:n})=>{const[a,p]=c.useState(!1),[h,_]=c.useState(!1),[f,j]=c.useState(null),[d,T]=c.useState({}),[i,y]=c.useState(W),[N,b]=c.useState(""),[r,x]=c.useState(""),s=c.useMemo(()=>l.filter(o=>o.type==="data"),[l]),u=c.useMemo(()=>ye(l,N,r),[l,r,N]),I=c.useCallback(o=>{var t,g,k,S,C;j(o),T({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),p(!0)},[]),L=c.useCallback(async()=>{var o,t,g,k,S,C,m,A;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((m=d.data_content)==null?void 0:m.trim())||"":d.type==="image"&&(w.image_url=((A=d.image_url)==null?void 0:A.trim())||""),await H(f.id,w),p(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(G(w,"更新失败,请重试"))}}},[d,n,f]),P=c.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await ue(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(G(t,"删除失败,请重试"))}},[n]),v=c.useCallback(async()=>{if(!i.name.trim()){alert("请输入卡密名称");return}if(!i.content.trim()){alert(i.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:i.name.trim(),type:i.type,description:i.description.trim(),enabled:i.enabled,delay_seconds:i.delay_seconds};i.type==="text"&&(o.text_content=i.content.trim()),i.type==="data"&&(o.data_content=i.content.trim()),i.type==="image"&&(o.image_url=i.content.trim()),i.type==="api"&&(o.api_config={url:i.content.trim(),method:i.api_method,timeout:i.api_timeout,headers:i.api_headers.trim()||void 0,params:i.api_params.trim()||void 0}),await he(o),_(!1),y(W()),await n()}catch(o){console.error("添加卡密失败:",o),alert(G(o,"添加失败,请重试"))}},[i,n]),B=c.useCallback(async o=>{try{await H(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),R=c.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),D=c.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 VIP-MONTH-002 -VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(p=>p.map(B=>`"${String(B).replace(/"/g,'""')}"`).join(",")).join(` -`),k=new Blob(["\uFEFF"+g],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(k),C=document.createElement("a");C.href=S,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:s,filteredCards:h,typeFilter:N,setTypeFilter:b,nameSearch:r,setNameSearch:x,showEditModal:a,setShowEditModal:u,showAddModal:m,setShowAddModal:_,selectedCard:f,editForm:d,setEditForm:A,addForm:c,setAddForm:y,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}},we=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?z.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(le,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(O,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.batchTab==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),"。 类型填 text/data/image;data 类型的“内容”按行存卡密(CSV 单元格内换行需用引号包裹)。"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:n,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(ne,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx(O,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full 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",{value:a.appendContent,onChange:m,placeholder:`VIP-001 +VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(m=>m.map(A=>`"${String(A).replace(/"/g,'""')}"`).join(",")).join(` +`),k=new Blob(["\uFEFF"+g],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(k),C=document.createElement("a");C.href=S,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:s,filteredCards:u,typeFilter:N,setTypeFilter:b,nameSearch:r,setNameSearch:x,showEditModal:a,setShowEditModal:p,showAddModal:h,setShowAddModal:_,selectedCard:f,editForm:d,setEditForm:T,addForm:i,setAddForm:y,handleEdit:I,handleSaveEdit:L,handleDelete:P,handleAddCard:v,toggleCardStatus:B,copyCardID:R,downloadCardTemplate:D}},Ne=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const p=s=>{var u;a.setBatchFile(((u=s.target.files)==null?void 0:u[0])||null)},h=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),T=()=>void a.handleRetryBatchCreate(),i=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?U.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(V,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(ae,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(z,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.batchTab==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),"。 类型填 text/data/image;data 类型的“内容”按行存卡密(CSV 单元格内换行需用引号包裹)。"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:n,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(se,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx(z,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:p})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:T,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full 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",{value:a.appendContent,onChange:h,placeholder:`VIP-001 VIP-002 -VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:c,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:f,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(V,{className:"w-4 h-4 animate-spin"}):e.jsx(O,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:r,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||l.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(V,{className:"w-4 h-4 animate-spin"}):e.jsx(U,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Ce=({type:l})=>{switch(l){case"text":return e.jsx(Y,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(X,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(re,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(W,{className:"w-5 h-5 text-gray-500"})}},_e=()=>{const[l,n]=i.useState([]),[a,u]=i.useState(!0),m=i.useRef(0),_=i.useRef(null),f=i.useCallback(async()=>{var A;const j=++m.current;(A=_.current)==null||A.abort();const d=new AbortController;_.current=d,u(!0);try{const c=await ue({signal:d.signal});if(j!==m.current)return;n(c)}catch(c){j===m.current&&!d.signal.aborted&&console.error("加载卡密库存失败:",c)}finally{j===m.current&&u(!1)}},[]);return i.useEffect(()=>(f(),()=>{var d;m.current+=1,(d=_.current)==null||d.abort()}),[f]),{cards:l,setCards:n,loading:a,loadCards:f}},ke=l=>{const n=l.dataCards,a=l.loadCards,[u,m]=i.useState(!1),[_,f]=i.useState("create"),[j,d]=i.useState(null),[A,c]=i.useState(null),[y,N]=i.useState(!1),[b,r]=i.useState(""),[x,s]=i.useState(""),[h,E]=i.useState(null),[M,R]=i.useState(""),v=i.useRef(0),T=i.useRef(null),P=i.useRef("");i.useEffect(()=>(()=>{var p;v.current+=1,(p=T.current)==null||p.abort()}),[]);const $=i.useMemo(()=>Q(x),[x]),o=i.useCallback(()=>{var p;f("create"),d(null),c(null),r((p=n[0])!=null&&p.id?String(n[0].id):""),s(""),E(null),R(""),m(!0)},[n]),t=i.useCallback(()=>{var p;v.current+=1,(p=T.current)==null||p.abort(),N(!1),m(!1)},[]),g=i.useCallback(async()=>{var w;if(!j||y)return;const p=++v.current;(w=T.current)==null||w.abort();const B=new AbortController;T.current=B,N(!0),c(null);try{const I=await ye(j,{signal:B.signal});if(!F(p,v.current,"",""))return;c(I),I.created>0&&await a()}catch(I){if(!F(p,v.current,"",""))return;c({error:(I==null?void 0:I.message)||"上传失败"})}finally{F(p,v.current,"","")&&N(!1)}},[y,j,a]),k=i.useCallback(async()=>{var I;if(!Ne(b,x,y))return;const p=b,B=++v.current;P.current=p,(I=T.current)==null||I.abort();const w=new AbortController;T.current=w,N(!0),E(null),R("");try{const L=await fe(p,x,{signal:w.signal});if(!F(B,v.current,p,b))return;E({added:L.added}),s(""),await a()}catch(L){if(!F(B,v.current,p,b))return;R((L==null?void 0:L.message)||"追加失败")}finally{F(B,v.current,p,b)&&N(!1)}},[x,b,y,a]),S=i.useCallback(async()=>{await g()},[g]),C=i.useCallback(async()=>{P.current&&b!==P.current||await k()},[b,k]);return{showBatchModal:u,setShowBatchModal:m,batchTab:_,setBatchTab:f,batchFile:j,setBatchFile:d,batchResult:A,batchBusy:y,appendTargetId:b,setAppendTargetId:r,appendContent:x,setAppendContent:s,appendResult:h,appendError:M,appendPreview:$,openBatchModal:o,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},Ie=()=>{const{cards:l,loadCards:n}=_e(),a=ve({cards:l,loadCards:n}),{dataCards:u,filteredCards:m,typeFilter:_,setTypeFilter:f,nameSearch:j,setNameSearch:d,showEditModal:A,setShowEditModal:c,showAddModal:y,setShowAddModal:N,selectedCard:b,editForm:r,setEditForm:x,addForm:s,setAddForm:h,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}=a,o=ke({dataCards:u,loadCards:n});return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:o.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(O,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>N(!0)),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(U,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(oe,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:_,onChange:(t=>f(t.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(ie,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:j,onChange:(t=>d(t.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",m.length," / ",l.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:m.map(t=>{let g="";return t.type==="data"&&t.data_content?g=`库存: ${t.data_content.split(` -`).filter(S=>S.trim()).length} 条`:t.type==="text"&&t.text_content?g=t.text_content:t.type==="api"&&t.api_config?g=t.api_config.url:t.type==="image"&&t.image_url&&(g="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(Ce,{type:t.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:t.name,children:t.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>P(t.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:t.id}),e.jsx(ce,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${t.type==="text"?"bg-blue-50 text-blue-600":t.type==="data"?"bg-purple-50 text-purple-600":t.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:t.type==="text"?"文本":t.type==="data"?"批量":t.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:g,children:g})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:t.description||"-",children:t.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>T(t)),"aria-label":`切换卡密 ${t.name} 状态`,className:`w-12 h-8 rounded-full relative transition-colors ${t.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${t.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>E(t)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(de,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>R(t.id)),"aria-label":`删除卡密 ${t.name}`,className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(xe,{className:"h-4 w-4"})})]})})]},t.id)})})]})}),m.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(pe,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:l.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),A&&b&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:r.name||"",onChange:(t=>x({...r,name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:r.type||"text",onChange:(t=>x({...r,type:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(b==null?void 0:b.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),r.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:r.api_url||"",onChange:(t=>x({...r,api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:r.api_method||"GET",onChange:(t=>x({...r,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),e.jsx("input",{type:"number",value:r.api_timeout||10,onChange:(t=>x({...r,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:r.api_headers||"",onChange:(t=>x({...r,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:r.api_params||"",onChange:(t=>x({...r,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),r.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:r.text_content||"",onChange:(t=>x({...r,text_content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),r.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:r.data_content||"",onChange:(t=>x({...r,data_content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: +VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:i,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:f,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(q,{className:"w-4 h-4 animate-spin"}):e.jsx(z,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:r,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||l.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(q,{className:"w-4 h-4 animate-spin"}):e.jsx(J,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ve=({type:l})=>{switch(l){case"text":return e.jsx(K,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Y,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(le,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(X,{className:"w-5 h-5 text-gray-500"})}},we=()=>{const[l,n]=c.useState([]),[a,p]=c.useState(!0),h=c.useRef(0),_=c.useRef(null),f=c.useCallback(async()=>{var T;const j=++h.current;(T=_.current)==null||T.abort();const d=new AbortController;_.current=d,p(!0);try{const i=await me({signal:d.signal});if(j!==h.current)return;n(i)}catch(i){j===h.current&&!d.signal.aborted&&console.error("加载卡密库存失败:",i)}finally{j===h.current&&p(!1)}},[]);return c.useEffect(()=>(f(),()=>{var d;h.current+=1,(d=_.current)==null||d.abort()}),[f]),{cards:l,setCards:n,loading:a,loadCards:f}},Ce=l=>{const n=l.dataCards,a=l.loadCards,[p,h]=c.useState(!1),[_,f]=c.useState("create"),[j,d]=c.useState(null),[T,i]=c.useState(null),[y,N]=c.useState(!1),[b,r]=c.useState(""),[x,s]=c.useState(""),[u,I]=c.useState(null),[L,P]=c.useState(""),v=c.useRef(0),B=c.useRef(null),R=c.useRef("");c.useEffect(()=>(()=>{var m;v.current+=1,(m=B.current)==null||m.abort()}),[]);const D=c.useMemo(()=>Z(x),[x]),o=c.useCallback(()=>{var m;f("create"),d(null),i(null),r((m=n[0])!=null&&m.id?String(n[0].id):""),s(""),I(null),P(""),h(!0)},[n]),t=c.useCallback(()=>{var m;v.current+=1,(m=B.current)==null||m.abort(),N(!1),h(!1)},[]),g=c.useCallback(async()=>{var w;if(!j||y)return;const m=++v.current;(w=B.current)==null||w.abort();const A=new AbortController;B.current=A,N(!0),i(null);try{const E=await be(j,{signal:A.signal});if(!F(m,v.current,"",""))return;i(E),E.created>0&&await a()}catch(E){if(!F(m,v.current,"",""))return;i({error:(E==null?void 0:E.message)||"上传失败"})}finally{F(m,v.current,"","")&&N(!1)}},[y,j,a]),k=c.useCallback(async()=>{var E;if(!fe(b,x,y))return;const m=b,A=++v.current;R.current=m,(E=B.current)==null||E.abort();const w=new AbortController;B.current=w,N(!0),I(null),P("");try{const $=await ge(m,x,{signal:w.signal});if(!F(A,v.current,m,b))return;I({added:$.added}),s(""),await a()}catch($){if(!F(A,v.current,m,b))return;P(($==null?void 0:$.message)||"追加失败")}finally{F(A,v.current,m,b)&&N(!1)}},[x,b,y,a]),S=c.useCallback(async()=>{await g()},[g]),C=c.useCallback(async()=>{R.current&&b!==R.current||await k()},[b,k]);return{showBatchModal:p,setShowBatchModal:h,batchTab:_,setBatchTab:f,batchFile:j,setBatchFile:d,batchResult:T,batchBusy:y,appendTargetId:b,setAppendTargetId:r,appendContent:x,setAppendContent:s,appendResult:u,appendError:L,appendPreview:D,openBatchModal:o,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},Be=()=>{const{cards:l,loadCards:n}=we(),a=je({cards:l,loadCards:n}),{dataCards:p,filteredCards:h,typeFilter:_,setTypeFilter:f,nameSearch:j,setNameSearch:d,showEditModal:T,setShowEditModal:i,showAddModal:y,setShowAddModal:N,selectedCard:b,editForm:r,setEditForm:x,addForm:s,setAddForm:u,handleEdit:I,handleSaveEdit:L,handleDelete:P,handleAddCard:v,toggleCardStatus:B,copyCardID:R,downloadCardTemplate:D}=a,o=Ce({dataCards:p,loadCards:n});return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:o.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(z,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>N(!0)),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(J,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ne,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:_,onChange:(t=>f(t.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(re,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:j,onChange:(t=>d(t.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",h.length," / ",l.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:h.map(t=>{let g="";return t.type==="data"&&t.data_content?g=`库存: ${t.data_content.split(` +`).filter(S=>S.trim()).length} 条`:t.type==="text"&&t.text_content?g=t.text_content:t.type==="api"&&t.api_config?g=t.api_config.url:t.type==="image"&&t.image_url&&(g="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ve,{type:t.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:t.name,children:t.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>R(t.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:t.id}),e.jsx(oe,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${t.type==="text"?"bg-blue-50 text-blue-600":t.type==="data"?"bg-purple-50 text-purple-600":t.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:t.type==="text"?"文本":t.type==="data"?"批量":t.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:g,children:g})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:t.description||"-",children:t.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>B(t)),"aria-label":`切换卡密 ${t.name} 状态`,className:`w-12 h-8 rounded-full relative transition-colors ${t.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${t.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>I(t)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(ce,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>P(t.id)),"aria-label":`删除卡密 ${t.name}`,className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(ie,{className:"h-4 w-4"})})]})})]},t.id)})})]})}),h.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(de,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:l.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),T&&b&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>i(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(V,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:r.name||"",onChange:(t=>x({...r,name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:r.type||"text",onChange:(t=>x({...r,type:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(b==null?void 0:b.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),r.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:r.api_url||"",onChange:(t=>x({...r,api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:r.api_method||"GET",onChange:(t=>x({...r,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),e.jsx("input",{type:"number",value:r.api_timeout||10,onChange:(t=>x({...r,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:r.api_headers||"",onChange:(t=>x({...r,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:r.api_params||"",onChange:(t=>x({...r,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),r.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:r.text_content||"",onChange:(t=>x({...r,text_content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),r.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:r.data_content||"",onChange:(t=>x({...r,data_content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: 卡号1:密码1 卡号2:密码2 或者 兑换码1 兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:r.data_content?r.data_content.split(` -`).filter(t=>t.trim()).length:0})," 条"]})]})]}),r.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:r.image_url||"",onChange:(t=>x({...r,image_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"仅保存图片 URL;发货时会临时下载并上传到闲鱼"})]}),r.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:r.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(t=>{t.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:r.delay_seconds||0,onChange:(t=>x({...r,delay_seconds:parseInt(t.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:r.description||"",onChange:(t=>x({...r,description:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>x({...r,enabled:!r.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${r.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${r.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:M,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(me,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),y&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>N(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:s.name,onChange:(t=>h({...s,name:t.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(W,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Y,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(X,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:s.type==="data"?"库存内容(一行一个)":s.type==="text"?"固定回复内容":s.type==="image"?"图片 URL":"API 地址"}),s.type==="api"?e.jsx("input",{type:"url",value:s.content,onChange:(t=>h({...s,content:t.target.value})),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):s.type==="image"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{type:"url",value:s.content,onChange:(t=>h({...s,content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}),e.jsx("p",{className:"text-xs text-gray-500",children:"仅保存图片 URL;发货时会临时下载并上传到闲鱼"})]}):e.jsx("textarea",{value:s.content,onChange:(t=>h({...s,content:t.target.value})),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${s.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:s.type==="data"?`CODE-123456 +`).filter(t=>t.trim()).length:0})," 条"]})]})]}),r.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:r.image_url||"",onChange:(t=>x({...r,image_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"仅保存图片 URL;发货时会临时下载并上传到闲鱼"})]}),r.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:r.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(t=>{t.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:r.delay_seconds||0,onChange:(t=>x({...r,delay_seconds:parseInt(t.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:r.description||"",onChange:(t=>x({...r,description:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>x({...r,enabled:!r.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${r.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${r.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>i(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:L,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),y&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>N(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(V,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:s.name,onChange:(t=>u({...s,name:t.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>u({...s,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(X,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>u({...s,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(K,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>u({...s,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Y,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:s.type==="data"?"库存内容(一行一个)":s.type==="text"?"固定回复内容":s.type==="image"?"图片 URL":"API 地址"}),s.type==="api"?e.jsx("input",{type:"url",value:s.content,onChange:(t=>u({...s,content:t.target.value})),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):s.type==="image"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{type:"url",value:s.content,onChange:(t=>u({...s,content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}),e.jsx("p",{className:"text-xs text-gray-500",children:"仅保存图片 URL;发货时会临时下载并上传到闲鱼"})]}):e.jsx("textarea",{value:s.content,onChange:(t=>u({...s,content:t.target.value})),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${s.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:s.type==="data"?`CODE-123456 CODE-789012 ...`:"请输入每次发货时发送的固定文字"}),s.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:s.content.split(` -`).filter(t=>t.trim()).length})," 条"]})]}),s.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:s.api_method,onChange:(t=>h({...s,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:s.api_timeout,onChange:(t=>h({...s,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:s.api_headers,onChange:(t=>h({...s,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:s.api_params,onChange:(t=>h({...s,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:s.description,onChange:(t=>h({...s,description:t.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:s.delay_seconds,onChange:(t=>h({...s,delay_seconds:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>N(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:v,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(U,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(we,{dataCards:u,downloadCardTemplate:$,...o})]})};export{Ie as default}; +`).filter(t=>t.trim()).length})," 条"]})]}),s.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:s.api_method,onChange:(t=>u({...s,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:s.api_timeout,onChange:(t=>u({...s,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:s.api_headers,onChange:(t=>u({...s,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:s.api_params,onChange:(t=>u({...s,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:s.description,onChange:(t=>u({...s,description:t.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:s.delay_seconds,onChange:(t=>u({...s,delay_seconds:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>N(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:v,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(J,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Ne,{dataCards:p,downloadCardTemplate:D,...o})]})};export{Be as default}; diff --git a/internal/webui/static/assets/Chat-MUERwcqZ.js b/internal/webui/static/assets/Chat-QumIYKUd.js similarity index 99% rename from internal/webui/static/assets/Chat-MUERwcqZ.js rename to internal/webui/static/assets/Chat-QumIYKUd.js index 6168dfd..4ae004d 100644 --- a/internal/webui/static/assets/Chat-MUERwcqZ.js +++ b/internal/webui/static/assets/Chat-QumIYKUd.js @@ -1 +1 @@ -import{j as e,c as x0,a as i}from"./react-vendor-l-BBvuKH.js";import{L as re}from"./vendor-cRYyTeIw.js";import{f as M0,h as le,i as F0,m as P0,s as ce,j as oe,k as pe,l as me,n as z0}from"./index-WrujSo30.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,t as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-Bgrth_9N.js";const Z0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"],["流汗","https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"],["憨笑","https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"],["耶","https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"],["奋斗","https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"],["咒骂","https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"],["疑问","https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"],["嘘","https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"],["晕","https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"],["开心到模糊","https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"],["衰","https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"],["委屈","https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"],["再见","https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"],["鼓掌","https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"],["吐","https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"],["坏笑","https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"],["抠鼻","https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"],["叹气","https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"],["无聊","https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"],["思考","https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"],["呆","https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["哇哦","https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"],["飞吻","https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"],["好喜欢","https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"],["拜托","https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"],["真棒","https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"],["流鼻血","https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"],["费解","https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"],["秃头","https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"],["嘿哈","https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"],["吃土","https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"],["机智","https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"],["举杯","https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"],["握手","https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"],["挥手","https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"],["yeah","https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"],["666","https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"],["棒","https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"],["爱你","https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"],["比心","https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"],["感谢","https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"],["拍手","https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"],["拉钩","https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"],["没钱","https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"],["小刀","https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"],["不刀","https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"],["同出","https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"],["递钱","https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"],["数钱","https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"],["打call","https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"],["号外","https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"],["包邮","https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"],["求赞","https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"],["非主流","https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"],["吃瓜","https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"],["种草","https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"],["佛系","https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"],["超便宜","https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"],["拥抱","https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"],["摊手","https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"],["举手","https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"],["蹲","https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"],["跪了","https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"],["拜","https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"],["排","https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"],["旺财","https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"],["招财猫","https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"],["酸了","https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"],["鸭鸭","https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"],["方了","https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"],["白菜","https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"],["桃子","https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"],["打包","https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"],["沙发","https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["南","https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"],["盯","https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"],["hot","https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"],["new","https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"],["cool","https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"],["1","https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"],["可","https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"],["搬砖","https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"],["菜狗","https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"],["开心面具","https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"],["快递","https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["裂开","https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"],["啤酒","https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"],["瑞思拜","https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"],["小丑","https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"],["爱心","https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"]],we=o=>o,Ne=new Map(Z0.map(([o,p])=>[o,p])),Ce=o=>o.split(/(\[[^\]]+\])/g).map((p,a)=>{const n=p.startsWith("[")?Ne.get(p.slice(1,-1)):void 0;return n?e.jsx("img",{src:n,alt:p,title:p,className:"mx-0.5 inline-block h-7 w-7 align-middle"},a):e.jsx(x0.Fragment,{children:p},a)}),q0=o=>{const p=Number.isFinite(o)?Math.max(0,Math.floor(o)):0;return p>99?"99+":String(p)},W0=o=>(Number.isFinite(o)?Math.max(0,Math.floor(o)):0)<10?"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold leading-none text-white":"inline-flex h-5 min-w-5 shrink-0 items-center justify-center rounded-full bg-red-500 px-1.5 text-[10px] font-bold leading-none text-white",V0=(o,p)=>o.filter(a=>a.direction==="incoming"&&a.message_type!=="system"&&!a.message_key.startsWith("in-")).map(a=>({messageId:a.message_key,sessionId:p,cid:`${p}@goofish`,conversationType:1})),ye=(o,p,a)=>{const n=p.trim().toLowerCase();return o.filter(u=>a&&u.unread_count<=0?!1:n?[u.buyer_name,u.buyer_id,u.item_title,u.last_message].some(y=>(y||"").toLowerCase().includes(n)):!0)},Oe=(o,p)=>{const a=new Set(o.map(n=>n.message_key));return[...p.filter(n=>!a.has(n.message_key)),...o]},T0=(o,p)=>{const a=o.findIndex(n=>n.message_key===p.message_key);return a<0?[...o,p]:o.map((n,u)=>u===a?p:n)},ve=(o,p)=>{if(p.direction!=="incoming"||p.message_type==="system")return o;const a=p.sent_at>0?p.sent_at:Date.now();return o.map(n=>n.chat_id===p.chat_id&&n.direction==="outgoing"&&n.status==="sent"&&n.sent_at<=p.sent_at?{...n,read_status:2,read_at:a}:n)},w=(o,p,a)=>o===p&&!a.aborted,K=o=>o instanceof Error&&o.message==="请求已取消",ke=o=>{if(!o)return"";const p=new Date(o<1e10?o*1e3:o),a=new Date;return p.toDateString()===a.toDateString()?p.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):p.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},Se=o=>new Date(o<1e10?o*1e3:o).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),Re=()=>{const[o,p]=i.useState([]),[a,n]=i.useState(""),[u,y]=i.useState({}),[h,Y]=i.useState(""),[I,k]=i.useState([]),[$,y0]=i.useState(""),[T,O0]=i.useState(!1),[A,u0]=i.useState(""),[D,O]=i.useState(null),[B,L]=i.useState(!0),[M,h0]=i.useState(!1),[J,_0]=i.useState(!1),[e0,b0]=i.useState(!1),[f0,t0]=i.useState(),[s0,a0]=i.useState({}),[i0,n0]=i.useState({}),[r0,l0]=i.useState(!1),[v0,k0]=i.useState(!1),[N,U]=i.useState(!1),[S0,j]=i.useState(""),[R0,E0]=i.useState("connecting"),[Q,c0]=i.useState(null),[W,o0]=i.useState(null),S=i.useRef(""),V=i.useRef(""),H=i.useRef(null),Z=i.useRef({accountID:"",chatID:""}),p0=i.useRef(!0),s=i.useRef(!1),x=i.useRef(null),v=i.useRef(new Set),R=i.useRef(0),F=i.useRef(null),P=i.useRef(0),I0=i.useRef(null),z=i.useRef(0),m0=i.useRef(null),g0=i.useRef(0),j0=i.useRef(null),E=i.useRef(0),G=i.useRef(null);i.useEffect(()=>{S.current=a},[a]),i.useEffect(()=>{V.current=h},[h]);const d0=i.useCallback(async t=>{var m;const r=++R.current;(m=F.current)==null||m.abort();const l=new AbortController;F.current=l;try{const c=await M0(t,void 0,{signal:l.signal},!0);if(!w(R.current,r,l.signal))return[];const g=c.sessions.map(d=>t===S.current&&d.chat_id===V.current?{...d,unread_count:0}:d);return y(d=>({...d,[t]:g})),a0(d=>({...d,[t]:c.next_cursor})),n0(d=>({...d,[t]:c.has_more})),g}catch(c){return w(R.current,r,l.signal)&&!K(c)&&j(c instanceof Error?c.message:"同步会话失败"),[]}},[]);i.useEffect(()=>{const t=new AbortController;return(async()=>{var l;L(!0);try{const[m,c]=await Promise.all([me({signal:t.signal}),z0({signal:t.signal})]),d=m.map(f=>{var q,H0;return{...f,runtime_state:((q=c[f.id])==null?void 0:q.state)||(f.enabled?"connecting":"disabled"),runtime_connected:((H0=c[f.id])==null?void 0:H0.connected)===!0}}).filter(f=>f.enabled),b=await Promise.all(d.map(async f=>[f.id,await M0(f.id,void 0,{signal:t.signal})]));if(t.signal.aborted)return;p(d),y(Object.fromEntries(b.map(([f,q])=>[f,q.sessions]))),a0(Object.fromEntries(b.map(([f,q])=>[f,q.next_cursor]))),n0(Object.fromEntries(b.map(([f,q])=>[f,q.has_more])));const C=window.localStorage.getItem("ydisks.chat.account.v1")||"",L0=d.some(f=>f.id===C)?C:((l=d[0])==null?void 0:l.id)||"";n(L0)}catch(m){t.signal.aborted||j(m instanceof Error?m.message:"加载聊天数据失败")}finally{t.signal.aborted||L(!1)}})(),(()=>t.abort())},[]),i.useEffect(()=>{let t=!1,r=0,l=null;const m=async()=>{l=new AbortController;try{const c=await z0({signal:l.signal,timeoutMs:1e4});t||p(g=>g.map(d=>{var b,C;return{...d,runtime_state:((b=c[d.id])==null?void 0:b.state)||d.runtime_state,runtime_connected:((C=c[d.id])==null?void 0:C.connected)??d.runtime_connected}}))}catch{}finally{t||(r=window.setTimeout(m,3e3))}};return r=window.setTimeout(m,3e3),(()=>{t=!0,window.clearTimeout(r),l==null||l.abort()})},[]),i.useEffect(()=>{if(!a)return;window.localStorage.setItem("ydisks.chat.account.v1",a);const t=u[a]||[];Y(r=>{var l;return t.some(m=>m.chat_id===r)?r:((l=t[0])==null?void 0:l.chat_id)||""})},[a,u]),i.useEffect(()=>{const t=Object.keys(u).length;if(B||o.length>0&&t===0)return;const r=Object.values(u).some(l=>l.some(m=>m.unread_count>0));le(r)},[o.length,B,u]),i.useEffect(()=>{!a||v.current.has(a)||(v.current.add(a),d0(a))},[a,d0]),i.useEffect(()=>{var l,m;if(!a||!h){P.current+=1,z.current+=1,(l=m0.current)==null||l.abort(),s.current=!1,k([]);return}const t=++P.current;(m=I0.current)==null||m.abort();const r=new AbortController;return I0.current=r,h0(!0),F0(a,h,void 0,void 0,{signal:r.signal}).then(c=>{if(!w(P.current,t,r.signal))return;const g=V0(c.messages,h);P0(a,h,g,{signal:r.signal}),k(c.messages),b0(c.has_more),t0(c.next_cursor),c.session&&y(d=>({...d,[a]:(d[a]||[]).map(b=>{var C;return b.chat_id===((C=c.session)==null?void 0:C.chat_id)?c.session:b})})),y(d=>({...d,[a]:(d[a]||[]).map(b=>b.chat_id===h?{...b,unread_count:0}:b)}))}).catch(c=>{w(P.current,t,r.signal)&&!K(c)&&j(c instanceof Error?c.message:"加载消息失败")}).finally(()=>{w(P.current,t,r.signal)&&h0(!1)}),(()=>r.abort())},[a,h]),i.useEffect(()=>{var t;(t=j0.current)==null||t.abort(),g0.current+=1},[a]),i.useEffect(()=>{var t;(t=G.current)==null||t.abort(),E.current+=1},[a,h]),i.useEffect(()=>{O(null)},[a,h]),i.useEffect(()=>{var t;z.current+=1,(t=m0.current)==null||t.abort(),s.current=!1},[a,h]),i.useEffect(()=>(()=>{var t,r,l,m,c;(t=F.current)==null||t.abort(),(r=I0.current)==null||r.abort(),z.current+=1,(l=m0.current)==null||l.abort(),(m=j0.current)==null||m.abort(),(c=G.current)==null||c.abort()}),[]),i.useEffect(()=>{const t=D;return(()=>{t&&URL.revokeObjectURL(t.url)})},[D]);const G0=i.useCallback(async()=>{var g,d;if(!a||!h||J||!e0)return;const t=H.current,r=(t==null?void 0:t.scrollHeight)||0,l=P.current,m=++z.current;(g=m0.current)==null||g.abort();const c=new AbortController;m0.current=c,s.current=!0,_0(!0),j("");try{const b=(d=I[0])==null?void 0:d.id,C=await F0(a,h,f0,b,{signal:c.signal});if(!w(P.current,l,c.signal)||m!==z.current)return;k(L0=>Oe(L0,C.messages)),b0(C.has_more),t0(C.next_cursor),requestAnimationFrame(()=>{m===z.current&&!c.signal.aborted&&t&&(t.scrollTop+=t.scrollHeight-r)})}catch(b){s.current=!1,K(b)||j(b instanceof Error?b.message:"加载历史消息失败")}finally{m===z.current&&_0(!1)}},[a,h,e0,f0,I,J]),A0=i.useCallback(t=>{const r=t.account_id;if(y(l=>{const m=l[r]||[];return m.some(g=>g.chat_id===t.chat_id)?{...l,[r]:m.map(g=>g.chat_id===t.chat_id?{...g,last_message:t.content,last_message_at:t.sent_at,unread_count:t.direction==="incoming"&&t.message_type!=="system"&&(S.current!==r||V.current!==t.chat_id)?g.unread_count+1:g.unread_count}:g).sort((g,d)=>d.last_message_at-g.last_message_at)}:(d0(r),l)}),S.current===r&&V.current===t.chat_id&&(k(l=>ve(T0(l,t),t)),t.direction==="incoming"&&t.message_type!=="system")){const l=V0([t],t.chat_id);P0(r,t.chat_id,l)}},[d0]);i.useEffect(()=>ce(r=>{if(r.type==="connection"){E0(r.state);return}A0(r.message)}),[A0]);const X0=i.useCallback(()=>{const t=H.current;if(!t)return;const r=t.scrollHeight-t.scrollTop-t.clientHeight;p0.current=r<=48},[]);i.useLayoutEffect(()=>{const t=Z.current.accountID!==a||Z.current.chatID!==h;Z.current={accountID:a,chatID:h},t&&(p0.current=!0);const r=H.current;if(r){if(s.current){s.current=!1;return}(M||p0.current)&&(r.scrollTop=r.scrollHeight)}},[a,h,I,M]);const K0=o.find(t=>t.id===a),w0=u[a]||[],_=w0.find(t=>t.chat_id===h),Y0=i.useMemo(()=>ye(w0,$,T),[w0,$,T]),$0=i.useCallback(t=>(u[t]||[]).reduce((r,l)=>r+l.unread_count,0),[u]),ee=i.useCallback(async()=>{var m;if(!a||r0||!i0[a])return;const t=++g0.current;(m=j0.current)==null||m.abort();const r=new AbortController;j0.current=r;const l=a;l0(!0),j("");try{const c=await M0(l,s0[l],{signal:r.signal},!0);if(!w(g0.current,t,r.signal))return;y(g=>({...g,[l]:c.sessions})),a0(g=>({...g,[l]:c.next_cursor})),n0(g=>({...g,[l]:c.has_more}))}catch(c){w(g0.current,t,r.signal)&&!K(c)&&j(c instanceof Error?c.message:"加载历史联系人失败")}finally{w(g0.current,t,r.signal)&&l0(!1)}},[a,s0,r0,i0]),N0=i.useCallback(async(t,r)=>{var c;if(!_||!a||N)return;const l=++E.current;(c=G.current)==null||c.abort();const m=new AbortController;G.current=m,U(!0),j("");try{const g=await oe({account_id:a,chat_id:_.chat_id,buyer_id:_.buyer_id,buyer_name:_.buyer_name,item_id:_.item_id,item_title:_.item_title,text:t},{signal:m.signal});if(!w(E.current,l,m.signal))return;u0(""),c0(null),k(d=>T0(d,g.message))}catch(g){w(E.current,l,m.signal)&&(r&&c0(t),K(g)||j(g instanceof Error?g.message:"消息发送失败"))}finally{w(E.current,l,m.signal)&&U(!1)}},[a,_,N]),C0=i.useCallback(async(t,r)=>{var c;if(!_||!a||N)return;const l=++E.current;(c=G.current)==null||c.abort();const m=new AbortController;G.current=m,U(!0),j("");try{const g=await pe({account_id:a,chat_id:_.chat_id,buyer_id:_.buyer_id,buyer_name:_.buyer_name,buyer_avatar_url:_.buyer_avatar_url,item_id:_.item_id,item_title:_.item_title,image:t},{signal:m.signal});if(!w(E.current,l,m.signal))return;o0(null),k(d=>T0(d,g.message))}catch(g){w(E.current,l,m.signal)&&(r&&o0(t),K(g)||j(g instanceof Error?g.message:"图片发送失败"))}finally{w(E.current,l,m.signal)&&(U(!1),x.current&&(x.current.value=""))}},[a,_,N]),te=i.useCallback(async()=>{const t=A.trim();!t||!_||!a||N||await N0(t,!0)},[a,A,_,N0,N]),D0=i.useCallback(async t=>{if(!(!t||!_||!a||N)){if(!t.type.startsWith("image/")){j("仅支持粘贴/发送图片文件");return}j(""),O({file:t,url:URL.createObjectURL(t)})}},[a,_,N]),se=i.useCallback(async t=>{const r=t.find(l=>l.type.startsWith("image/"));r&&await D0(r)},[D0]),ae=i.useCallback(()=>{O(null),x.current&&(x.current.value="")},[]),ie=i.useCallback(async()=>{if(!D||!_||!a||N)return;const t=D.file;O(null),await C0(t,!0)},[a,D,_,C0,N]),ne=i.useCallback(async()=>{Q?await N0(Q,!1):W&&await C0(W,!1)},[W,Q,C0,N0]);return{accounts:o,activeAccountID:a,activeSessions:w0,selectedSession:_,activeAccount:K0,messages:I,search:$,unreadOnly:T,draft:A,loading:B,messagesLoading:M,olderLoading:J,hasOlder:e0,contactsLoading:r0,hasMoreContacts:i0[a]===!0,emojiOpen:v0,sending:N,error:S0,liveState:R0,pendingImage:D,activeChatID:h,filteredSessions:Y0,scrollRef:H,imageInputRef:x,setActiveAccountID:n,setActiveChatID:Y,setSearch:y0,setUnreadOnly:O0,setDraft:u0,setEmojiOpen:k0,reloadSessions:d0,loadMoreContacts:ee,loadOlderMessages:G0,handleMessageScroll:X0,handleSend:te,handleImage:D0,handlePastedImages:se,confirmSendImage:ie,closeImagePreview:ae,retrySend:ne,retryAvailable:!!(Q||W),unreadForAccount:$0,emojiURL:we,xianyuEmojis:Z0,renderXianyuText:Ce,formatClock:ke,messageTime:Se}},Me=()=>{const{accounts:o,activeAccountID:p,activeChatID:a,activeAccount:n,selectedSession:u,filteredSessions:y,messages:h,search:Y,unreadOnly:I,draft:k,loading:$,messagesLoading:y0,olderLoading:T,hasOlder:O0,contactsLoading:A,hasMoreContacts:u0,emojiOpen:D,sending:O,error:B,liveState:L,pendingImage:M,scrollRef:h0,imageInputRef:J,setActiveAccountID:_0,setActiveChatID:e0,setSearch:b0,setUnreadOnly:f0,setDraft:t0,setEmojiOpen:s0,reloadSessions:a0,loadMoreContacts:i0,loadOlderMessages:n0,handleMessageScroll:r0,handleSend:l0,handleImage:v0,handlePastedImages:k0,confirmSendImage:N,closeImagePreview:U,retrySend:S0,retryAvailable:j,unreadForAccount:R0,emojiURL:E0,xianyuEmojis:Q,renderXianyuText:c0,formatClock:W,messageTime:o0}=Re(),S=x0.useMemo(()=>h.filter(s=>s.message_type==="image"),[h]),V=x0.useMemo(()=>S.map(s=>({src:s.content,alt:"聊天图片"})),[S]),[H,Z]=x0.useState(-1),p0=x0.useCallback(s=>{Z(S.findIndex(x=>x.message_key===s))},[S]);return $?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(X,{className:"h-8 w-8 animate-spin text-sky-500"})}):e.jsxs("section",{className:"flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat",children:[e.jsxs("header",{className:"border-b border-slate-200 bg-slate-50/70 px-5 pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-black tracking-tight text-slate-950",children:"在线聊天"}),e.jsx("p",{className:"mt-0.5 text-xs font-medium text-slate-500",children:"复用账号实时连接,消息按账号完全隔离"})]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${L==="online"?"bg-emerald-50 text-emerald-700":L==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[L==="online"?e.jsx(ge,{className:"h-3.5 w-3.5"}):e.jsx(de,{className:"h-3.5 w-3.5"}),L==="online"?"实时同步中":L==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:o.map(s=>{const x=s.id===p,v=R0(s.id),R=q0(v),F=s.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":x,onClick:(()=>_0(s.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${x?"border-sky-500 text-sky-700":"border-transparent text-slate-500 hover:text-slate-900"}`,children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${F?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:s.nickname||s.remark||s.id}),v>0&&e.jsx("span",{"aria-label":`未读消息 ${R} 条`,className:W0(v),children:R})]},s.id)})})]}),o.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(B0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-800",children:"暂无启用账号"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"先在账号管理中启用账号,聊天会话会自动出现。"})]}):e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40",children:[e.jsxs("div",{className:"space-y-3 border-b border-slate-200 p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(xe,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:Y,onChange:(s=>b0(s.target.value)),placeholder:"搜索用户、商品或消息",className:"h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:(()=>f0(s=>!s)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${I?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:I?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void a0(p)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(ue,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[y.map(s=>e.jsxs("button",{type:"button",onClick:(()=>e0(s.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${s.chat_id===a?"bg-white shadow-chat-active":"hover:bg-white/80"}`,children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500",children:s.buyer_avatar_url?e.jsx("img",{src:s.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(U0,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-extrabold text-slate-900",children:s.buyer_name||`用户 ${s.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:W(s.last_message_at)})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs text-slate-500",children:s.last_message||"暂无消息"}),s.unread_count>0&&e.jsx("span",{"aria-label":`未读消息 ${q0(s.unread_count)} 条`,className:`ml-auto ${W0(s.unread_count)}`,children:q0(s.unread_count)})]}),s.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",s.item_title]})]})]},s.chat_id)),y.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),u0&&!Y&&!I&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void i0()),disabled:A,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[A&&e.jsx(X,{className:"h-3.5 w-3.5 animate-spin"}),A?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:u?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-black text-slate-950",children:u.buyer_name||u.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",u.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(n==null?void 0:n.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(n==null?void 0:n.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:h0,onScroll:r0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:y0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(X,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[O0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void n0()),disabled:T,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[T&&e.jsx(X,{className:"h-3.5 w-3.5 animate-spin"}),T?"正在加载":"加载更早消息"]})}),h.map(s=>{const x=s.direction==="outgoing";return s.message_type==="system"?e.jsx("div",{className:"flex justify-center py-1",children:e.jsxs("div",{className:"max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500",children:[c0(s.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:o0(s.sent_at)})]})},s.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${x?"justify-end":"justify-start"}`,children:[!x&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:u.buyer_avatar_url?e.jsx("img",{src:u.buyer_avatar_url,alt:u.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(U0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${x?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:x?(n==null?void 0:n.nickname)||(n==null?void 0:n.remark)||"我":u.buyer_name||s.sender_name||u.buyer_id}),s.message_type==="image"?e.jsx("button",{type:"button",title:"点击预览大图",onClick:p0.bind(null,s.message_key),className:`block cursor-zoom-in overflow-hidden rounded-2xl border bg-white p-1 text-left shadow-sm ${x?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:s.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):s.message_type==="video"?e.jsx("video",{src:s.content,controls:!0,preload:"metadata",className:"max-h-80 max-w-full rounded-2xl bg-black"}):e.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${x?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:c0(s.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[o0(s.sent_at),x&&(s.status==="failed"?e.jsx(he,{className:"h-3 w-3 text-red-500","aria-label":"发送失败"}):s.read_status===2?e.jsx(_e,{className:"h-3 w-3 text-sky-500","aria-label":"对方已读"}):s.status==="sent"?e.jsx(J0,{className:"h-3 w-3 text-sky-500","aria-label":"已发送未读"}):e.jsx(J0,{className:"h-3 w-3","aria-label":"发送中"}))]})]}),x&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:n!=null&&n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(U0,{className:"m-2 h-5 w-5 text-sky-600"})})]},s.message_key)})]})}),B&&e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:[e.jsx("span",{children:B}),j&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void S0()),children:"重试发送"})]}),e.jsxs("div",{className:"relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:(()=>s0(s=>!s)),disabled:O||(n==null?void 0:n.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"闲鱼表情",children:e.jsx(be,{className:"h-5 w-5"})}),D&&e.jsxs("div",{className:"absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl",children:[e.jsx("div",{className:"mb-2 text-xs font-bold text-slate-500",children:"全部表情"}),e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto",children:Q.map(([s,x])=>e.jsx("button",{type:"button",title:`[${s}]`,onClick:(()=>{t0(v=>v+`[${s}]`),s0(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:E0(x),alt:`[${s}]`,className:"h-8 w-8 object-contain"})},s))})]})]}),e.jsx("input",{ref:J,type:"file",accept:"image/*",className:"hidden",onChange:(s=>{var x;return void v0((x=s.target.files)==null?void 0:x[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var s;return(s=J.current)==null?void 0:s.click()}),disabled:O||(n==null?void 0:n.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"发送图片(最大 10MB)",children:e.jsx(fe,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100",children:[e.jsx("textarea",{value:k,onChange:(s=>t0(s.target.value)),rows:2,maxLength:2e3,onKeyDown:(s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),l0())}),onPaste:(s=>{var R;const x=Array.from(((R=s.clipboardData)==null?void 0:R.files)||[]);x.find(F=>F.type.startsWith("image/"))&&(s.preventDefault(),k0(x))}),disabled:(n==null?void 0:n.runtime_state)!=="online",placeholder:(n==null?void 0:n.runtime_state)==="online"?"输入消息,Enter 发送,Shift + Enter 换行,Ctrl + V 粘贴图片":"账号离线,暂时无法发送",className:"max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed"}),e.jsx("button",{type:"button",onClick:(()=>void l0()),disabled:!k.trim()||O||(n==null?void 0:n.runtime_state)!=="online",className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none","aria-label":"发送消息",children:O?e.jsx(X,{className:"h-4 w-4 animate-spin"}):e.jsx(Q0,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(B0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-700",children:"选择一个用户开始聊天"}),e.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"该账号的新消息会实时出现在左侧列表。"})]})})]}),M&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 p-4",onClick:U,children:e.jsxs("div",{className:"flex max-h-full w-full max-w-2xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:(s=>s.stopPropagation()),children:[e.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-slate-200 px-5 py-3",children:[e.jsx("div",{className:"text-sm font-black text-slate-900",children:"发送图片预览"}),e.jsx("button",{type:"button",title:"取消",onClick:U,className:"rounded-lg p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-700",children:e.jsx(je,{className:"h-5 w-5"})})]}),e.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-slate-100 p-4",children:e.jsx("img",{src:M.url,alt:"待发送图片预览",className:"max-h-[55vh] max-w-full rounded-xl object-contain"})}),e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-slate-200 px-5 py-3",children:[e.jsxs("div",{className:"min-w-0 truncate text-xs text-slate-500",children:[M.file.name||"粘贴的图片"," · ",(M.file.size/1024).toFixed(0)," KB"]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button",onClick:U,className:"rounded-xl px-4 py-2 text-sm font-bold text-slate-600 transition hover:bg-slate-100",children:"取消"}),e.jsxs("button",{type:"button",onClick:(()=>void N()),disabled:O||(n==null?void 0:n.runtime_state)!=="online",className:"flex items-center gap-2 rounded-xl bg-sky-500 px-4 py-2 text-sm font-bold text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:opacity-50",children:[O?e.jsx(X,{className:"h-4 w-4 animate-spin"}):e.jsx(Q0,{className:"h-4 w-4"}),"发送"]})]})]})]})}),e.jsx(re,{open:H>=0,index:Math.max(H,0),close:(()=>Z(-1)),slides:V})]})};export{Me as default}; +import{j as e,c as x0,a as i}from"./react-vendor-l-BBvuKH.js";import{L as re}from"./vendor-cRYyTeIw.js";import{g as M0,p as le,b as F0,m as P0,s as ce,d as oe,e as pe,f as me,h as z0}from"./index-CiBUw4Te.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,t as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-Bgrth_9N.js";const Z0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"],["流汗","https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"],["憨笑","https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"],["耶","https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"],["奋斗","https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"],["咒骂","https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"],["疑问","https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"],["嘘","https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"],["晕","https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"],["开心到模糊","https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"],["衰","https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"],["委屈","https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"],["再见","https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"],["鼓掌","https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"],["吐","https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"],["坏笑","https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"],["抠鼻","https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"],["叹气","https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"],["无聊","https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"],["思考","https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"],["呆","https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["哇哦","https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"],["飞吻","https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"],["好喜欢","https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"],["拜托","https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"],["真棒","https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"],["流鼻血","https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"],["费解","https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"],["秃头","https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"],["嘿哈","https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"],["吃土","https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"],["机智","https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"],["举杯","https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"],["握手","https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"],["挥手","https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"],["yeah","https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"],["666","https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"],["棒","https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"],["爱你","https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"],["比心","https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"],["感谢","https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"],["拍手","https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"],["拉钩","https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"],["没钱","https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"],["小刀","https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"],["不刀","https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"],["同出","https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"],["递钱","https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"],["数钱","https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"],["打call","https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"],["号外","https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"],["包邮","https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"],["求赞","https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"],["非主流","https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"],["吃瓜","https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"],["种草","https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"],["佛系","https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"],["超便宜","https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"],["拥抱","https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"],["摊手","https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"],["举手","https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"],["蹲","https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"],["跪了","https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"],["拜","https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"],["排","https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"],["旺财","https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"],["招财猫","https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"],["酸了","https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"],["鸭鸭","https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"],["方了","https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"],["白菜","https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"],["桃子","https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"],["打包","https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"],["沙发","https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["南","https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"],["盯","https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"],["hot","https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"],["new","https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"],["cool","https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"],["1","https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"],["可","https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"],["搬砖","https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"],["菜狗","https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"],["开心面具","https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"],["快递","https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["裂开","https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"],["啤酒","https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"],["瑞思拜","https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"],["小丑","https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"],["爱心","https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"]],we=o=>o,Ne=new Map(Z0.map(([o,p])=>[o,p])),Ce=o=>o.split(/(\[[^\]]+\])/g).map((p,a)=>{const n=p.startsWith("[")?Ne.get(p.slice(1,-1)):void 0;return n?e.jsx("img",{src:n,alt:p,title:p,className:"mx-0.5 inline-block h-7 w-7 align-middle"},a):e.jsx(x0.Fragment,{children:p},a)}),q0=o=>{const p=Number.isFinite(o)?Math.max(0,Math.floor(o)):0;return p>99?"99+":String(p)},W0=o=>(Number.isFinite(o)?Math.max(0,Math.floor(o)):0)<10?"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold leading-none text-white":"inline-flex h-5 min-w-5 shrink-0 items-center justify-center rounded-full bg-red-500 px-1.5 text-[10px] font-bold leading-none text-white",V0=(o,p)=>o.filter(a=>a.direction==="incoming"&&a.message_type!=="system"&&!a.message_key.startsWith("in-")).map(a=>({messageId:a.message_key,sessionId:p,cid:`${p}@goofish`,conversationType:1})),ye=(o,p,a)=>{const n=p.trim().toLowerCase();return o.filter(u=>a&&u.unread_count<=0?!1:n?[u.buyer_name,u.buyer_id,u.item_title,u.last_message].some(y=>(y||"").toLowerCase().includes(n)):!0)},Oe=(o,p)=>{const a=new Set(o.map(n=>n.message_key));return[...p.filter(n=>!a.has(n.message_key)),...o]},T0=(o,p)=>{const a=o.findIndex(n=>n.message_key===p.message_key);return a<0?[...o,p]:o.map((n,u)=>u===a?p:n)},ve=(o,p)=>{if(p.direction!=="incoming"||p.message_type==="system")return o;const a=p.sent_at>0?p.sent_at:Date.now();return o.map(n=>n.chat_id===p.chat_id&&n.direction==="outgoing"&&n.status==="sent"&&n.sent_at<=p.sent_at?{...n,read_status:2,read_at:a}:n)},w=(o,p,a)=>o===p&&!a.aborted,K=o=>o instanceof Error&&o.message==="请求已取消",ke=o=>{if(!o)return"";const p=new Date(o<1e10?o*1e3:o),a=new Date;return p.toDateString()===a.toDateString()?p.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):p.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},Se=o=>new Date(o<1e10?o*1e3:o).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),Re=()=>{const[o,p]=i.useState([]),[a,n]=i.useState(""),[u,y]=i.useState({}),[h,Y]=i.useState(""),[I,k]=i.useState([]),[$,y0]=i.useState(""),[T,O0]=i.useState(!1),[A,u0]=i.useState(""),[D,O]=i.useState(null),[B,L]=i.useState(!0),[M,h0]=i.useState(!1),[J,_0]=i.useState(!1),[e0,b0]=i.useState(!1),[f0,t0]=i.useState(),[s0,a0]=i.useState({}),[i0,n0]=i.useState({}),[r0,l0]=i.useState(!1),[v0,k0]=i.useState(!1),[N,U]=i.useState(!1),[S0,j]=i.useState(""),[R0,E0]=i.useState("connecting"),[Q,c0]=i.useState(null),[W,o0]=i.useState(null),S=i.useRef(""),V=i.useRef(""),H=i.useRef(null),Z=i.useRef({accountID:"",chatID:""}),p0=i.useRef(!0),s=i.useRef(!1),x=i.useRef(null),v=i.useRef(new Set),R=i.useRef(0),F=i.useRef(null),P=i.useRef(0),I0=i.useRef(null),z=i.useRef(0),m0=i.useRef(null),g0=i.useRef(0),j0=i.useRef(null),E=i.useRef(0),G=i.useRef(null);i.useEffect(()=>{S.current=a},[a]),i.useEffect(()=>{V.current=h},[h]);const d0=i.useCallback(async t=>{var m;const r=++R.current;(m=F.current)==null||m.abort();const l=new AbortController;F.current=l;try{const c=await M0(t,void 0,{signal:l.signal},!0);if(!w(R.current,r,l.signal))return[];const g=c.sessions.map(d=>t===S.current&&d.chat_id===V.current?{...d,unread_count:0}:d);return y(d=>({...d,[t]:g})),a0(d=>({...d,[t]:c.next_cursor})),n0(d=>({...d,[t]:c.has_more})),g}catch(c){return w(R.current,r,l.signal)&&!K(c)&&j(c instanceof Error?c.message:"同步会话失败"),[]}},[]);i.useEffect(()=>{const t=new AbortController;return(async()=>{var l;L(!0);try{const[m,c]=await Promise.all([me({signal:t.signal}),z0({signal:t.signal})]),d=m.map(f=>{var q,H0;return{...f,runtime_state:((q=c[f.id])==null?void 0:q.state)||(f.enabled?"connecting":"disabled"),runtime_connected:((H0=c[f.id])==null?void 0:H0.connected)===!0}}).filter(f=>f.enabled),b=await Promise.all(d.map(async f=>[f.id,await M0(f.id,void 0,{signal:t.signal})]));if(t.signal.aborted)return;p(d),y(Object.fromEntries(b.map(([f,q])=>[f,q.sessions]))),a0(Object.fromEntries(b.map(([f,q])=>[f,q.next_cursor]))),n0(Object.fromEntries(b.map(([f,q])=>[f,q.has_more])));const C=window.localStorage.getItem("ydisks.chat.account.v1")||"",L0=d.some(f=>f.id===C)?C:((l=d[0])==null?void 0:l.id)||"";n(L0)}catch(m){t.signal.aborted||j(m instanceof Error?m.message:"加载聊天数据失败")}finally{t.signal.aborted||L(!1)}})(),(()=>t.abort())},[]),i.useEffect(()=>{let t=!1,r=0,l=null;const m=async()=>{l=new AbortController;try{const c=await z0({signal:l.signal,timeoutMs:1e4});t||p(g=>g.map(d=>{var b,C;return{...d,runtime_state:((b=c[d.id])==null?void 0:b.state)||d.runtime_state,runtime_connected:((C=c[d.id])==null?void 0:C.connected)??d.runtime_connected}}))}catch{}finally{t||(r=window.setTimeout(m,3e3))}};return r=window.setTimeout(m,3e3),(()=>{t=!0,window.clearTimeout(r),l==null||l.abort()})},[]),i.useEffect(()=>{if(!a)return;window.localStorage.setItem("ydisks.chat.account.v1",a);const t=u[a]||[];Y(r=>{var l;return t.some(m=>m.chat_id===r)?r:((l=t[0])==null?void 0:l.chat_id)||""})},[a,u]),i.useEffect(()=>{const t=Object.keys(u).length;if(B||o.length>0&&t===0)return;const r=Object.values(u).some(l=>l.some(m=>m.unread_count>0));le(r)},[o.length,B,u]),i.useEffect(()=>{!a||v.current.has(a)||(v.current.add(a),d0(a))},[a,d0]),i.useEffect(()=>{var l,m;if(!a||!h){P.current+=1,z.current+=1,(l=m0.current)==null||l.abort(),s.current=!1,k([]);return}const t=++P.current;(m=I0.current)==null||m.abort();const r=new AbortController;return I0.current=r,h0(!0),F0(a,h,void 0,void 0,{signal:r.signal}).then(c=>{if(!w(P.current,t,r.signal))return;const g=V0(c.messages,h);P0(a,h,g,{signal:r.signal}),k(c.messages),b0(c.has_more),t0(c.next_cursor),c.session&&y(d=>({...d,[a]:(d[a]||[]).map(b=>{var C;return b.chat_id===((C=c.session)==null?void 0:C.chat_id)?c.session:b})})),y(d=>({...d,[a]:(d[a]||[]).map(b=>b.chat_id===h?{...b,unread_count:0}:b)}))}).catch(c=>{w(P.current,t,r.signal)&&!K(c)&&j(c instanceof Error?c.message:"加载消息失败")}).finally(()=>{w(P.current,t,r.signal)&&h0(!1)}),(()=>r.abort())},[a,h]),i.useEffect(()=>{var t;(t=j0.current)==null||t.abort(),g0.current+=1},[a]),i.useEffect(()=>{var t;(t=G.current)==null||t.abort(),E.current+=1},[a,h]),i.useEffect(()=>{O(null)},[a,h]),i.useEffect(()=>{var t;z.current+=1,(t=m0.current)==null||t.abort(),s.current=!1},[a,h]),i.useEffect(()=>(()=>{var t,r,l,m,c;(t=F.current)==null||t.abort(),(r=I0.current)==null||r.abort(),z.current+=1,(l=m0.current)==null||l.abort(),(m=j0.current)==null||m.abort(),(c=G.current)==null||c.abort()}),[]),i.useEffect(()=>{const t=D;return(()=>{t&&URL.revokeObjectURL(t.url)})},[D]);const G0=i.useCallback(async()=>{var g,d;if(!a||!h||J||!e0)return;const t=H.current,r=(t==null?void 0:t.scrollHeight)||0,l=P.current,m=++z.current;(g=m0.current)==null||g.abort();const c=new AbortController;m0.current=c,s.current=!0,_0(!0),j("");try{const b=(d=I[0])==null?void 0:d.id,C=await F0(a,h,f0,b,{signal:c.signal});if(!w(P.current,l,c.signal)||m!==z.current)return;k(L0=>Oe(L0,C.messages)),b0(C.has_more),t0(C.next_cursor),requestAnimationFrame(()=>{m===z.current&&!c.signal.aborted&&t&&(t.scrollTop+=t.scrollHeight-r)})}catch(b){s.current=!1,K(b)||j(b instanceof Error?b.message:"加载历史消息失败")}finally{m===z.current&&_0(!1)}},[a,h,e0,f0,I,J]),A0=i.useCallback(t=>{const r=t.account_id;if(y(l=>{const m=l[r]||[];return m.some(g=>g.chat_id===t.chat_id)?{...l,[r]:m.map(g=>g.chat_id===t.chat_id?{...g,last_message:t.content,last_message_at:t.sent_at,unread_count:t.direction==="incoming"&&t.message_type!=="system"&&(S.current!==r||V.current!==t.chat_id)?g.unread_count+1:g.unread_count}:g).sort((g,d)=>d.last_message_at-g.last_message_at)}:(d0(r),l)}),S.current===r&&V.current===t.chat_id&&(k(l=>ve(T0(l,t),t)),t.direction==="incoming"&&t.message_type!=="system")){const l=V0([t],t.chat_id);P0(r,t.chat_id,l)}},[d0]);i.useEffect(()=>ce(r=>{if(r.type==="connection"){E0(r.state);return}A0(r.message)}),[A0]);const X0=i.useCallback(()=>{const t=H.current;if(!t)return;const r=t.scrollHeight-t.scrollTop-t.clientHeight;p0.current=r<=48},[]);i.useLayoutEffect(()=>{const t=Z.current.accountID!==a||Z.current.chatID!==h;Z.current={accountID:a,chatID:h},t&&(p0.current=!0);const r=H.current;if(r){if(s.current){s.current=!1;return}(M||p0.current)&&(r.scrollTop=r.scrollHeight)}},[a,h,I,M]);const K0=o.find(t=>t.id===a),w0=u[a]||[],_=w0.find(t=>t.chat_id===h),Y0=i.useMemo(()=>ye(w0,$,T),[w0,$,T]),$0=i.useCallback(t=>(u[t]||[]).reduce((r,l)=>r+l.unread_count,0),[u]),ee=i.useCallback(async()=>{var m;if(!a||r0||!i0[a])return;const t=++g0.current;(m=j0.current)==null||m.abort();const r=new AbortController;j0.current=r;const l=a;l0(!0),j("");try{const c=await M0(l,s0[l],{signal:r.signal},!0);if(!w(g0.current,t,r.signal))return;y(g=>({...g,[l]:c.sessions})),a0(g=>({...g,[l]:c.next_cursor})),n0(g=>({...g,[l]:c.has_more}))}catch(c){w(g0.current,t,r.signal)&&!K(c)&&j(c instanceof Error?c.message:"加载历史联系人失败")}finally{w(g0.current,t,r.signal)&&l0(!1)}},[a,s0,r0,i0]),N0=i.useCallback(async(t,r)=>{var c;if(!_||!a||N)return;const l=++E.current;(c=G.current)==null||c.abort();const m=new AbortController;G.current=m,U(!0),j("");try{const g=await oe({account_id:a,chat_id:_.chat_id,buyer_id:_.buyer_id,buyer_name:_.buyer_name,item_id:_.item_id,item_title:_.item_title,text:t},{signal:m.signal});if(!w(E.current,l,m.signal))return;u0(""),c0(null),k(d=>T0(d,g.message))}catch(g){w(E.current,l,m.signal)&&(r&&c0(t),K(g)||j(g instanceof Error?g.message:"消息发送失败"))}finally{w(E.current,l,m.signal)&&U(!1)}},[a,_,N]),C0=i.useCallback(async(t,r)=>{var c;if(!_||!a||N)return;const l=++E.current;(c=G.current)==null||c.abort();const m=new AbortController;G.current=m,U(!0),j("");try{const g=await pe({account_id:a,chat_id:_.chat_id,buyer_id:_.buyer_id,buyer_name:_.buyer_name,buyer_avatar_url:_.buyer_avatar_url,item_id:_.item_id,item_title:_.item_title,image:t},{signal:m.signal});if(!w(E.current,l,m.signal))return;o0(null),k(d=>T0(d,g.message))}catch(g){w(E.current,l,m.signal)&&(r&&o0(t),K(g)||j(g instanceof Error?g.message:"图片发送失败"))}finally{w(E.current,l,m.signal)&&(U(!1),x.current&&(x.current.value=""))}},[a,_,N]),te=i.useCallback(async()=>{const t=A.trim();!t||!_||!a||N||await N0(t,!0)},[a,A,_,N0,N]),D0=i.useCallback(async t=>{if(!(!t||!_||!a||N)){if(!t.type.startsWith("image/")){j("仅支持粘贴/发送图片文件");return}j(""),O({file:t,url:URL.createObjectURL(t)})}},[a,_,N]),se=i.useCallback(async t=>{const r=t.find(l=>l.type.startsWith("image/"));r&&await D0(r)},[D0]),ae=i.useCallback(()=>{O(null),x.current&&(x.current.value="")},[]),ie=i.useCallback(async()=>{if(!D||!_||!a||N)return;const t=D.file;O(null),await C0(t,!0)},[a,D,_,C0,N]),ne=i.useCallback(async()=>{Q?await N0(Q,!1):W&&await C0(W,!1)},[W,Q,C0,N0]);return{accounts:o,activeAccountID:a,activeSessions:w0,selectedSession:_,activeAccount:K0,messages:I,search:$,unreadOnly:T,draft:A,loading:B,messagesLoading:M,olderLoading:J,hasOlder:e0,contactsLoading:r0,hasMoreContacts:i0[a]===!0,emojiOpen:v0,sending:N,error:S0,liveState:R0,pendingImage:D,activeChatID:h,filteredSessions:Y0,scrollRef:H,imageInputRef:x,setActiveAccountID:n,setActiveChatID:Y,setSearch:y0,setUnreadOnly:O0,setDraft:u0,setEmojiOpen:k0,reloadSessions:d0,loadMoreContacts:ee,loadOlderMessages:G0,handleMessageScroll:X0,handleSend:te,handleImage:D0,handlePastedImages:se,confirmSendImage:ie,closeImagePreview:ae,retrySend:ne,retryAvailable:!!(Q||W),unreadForAccount:$0,emojiURL:we,xianyuEmojis:Z0,renderXianyuText:Ce,formatClock:ke,messageTime:Se}},Me=()=>{const{accounts:o,activeAccountID:p,activeChatID:a,activeAccount:n,selectedSession:u,filteredSessions:y,messages:h,search:Y,unreadOnly:I,draft:k,loading:$,messagesLoading:y0,olderLoading:T,hasOlder:O0,contactsLoading:A,hasMoreContacts:u0,emojiOpen:D,sending:O,error:B,liveState:L,pendingImage:M,scrollRef:h0,imageInputRef:J,setActiveAccountID:_0,setActiveChatID:e0,setSearch:b0,setUnreadOnly:f0,setDraft:t0,setEmojiOpen:s0,reloadSessions:a0,loadMoreContacts:i0,loadOlderMessages:n0,handleMessageScroll:r0,handleSend:l0,handleImage:v0,handlePastedImages:k0,confirmSendImage:N,closeImagePreview:U,retrySend:S0,retryAvailable:j,unreadForAccount:R0,emojiURL:E0,xianyuEmojis:Q,renderXianyuText:c0,formatClock:W,messageTime:o0}=Re(),S=x0.useMemo(()=>h.filter(s=>s.message_type==="image"),[h]),V=x0.useMemo(()=>S.map(s=>({src:s.content,alt:"聊天图片"})),[S]),[H,Z]=x0.useState(-1),p0=x0.useCallback(s=>{Z(S.findIndex(x=>x.message_key===s))},[S]);return $?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(X,{className:"h-8 w-8 animate-spin text-sky-500"})}):e.jsxs("section",{className:"flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat",children:[e.jsxs("header",{className:"border-b border-slate-200 bg-slate-50/70 px-5 pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-black tracking-tight text-slate-950",children:"在线聊天"}),e.jsx("p",{className:"mt-0.5 text-xs font-medium text-slate-500",children:"复用账号实时连接,消息按账号完全隔离"})]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${L==="online"?"bg-emerald-50 text-emerald-700":L==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[L==="online"?e.jsx(ge,{className:"h-3.5 w-3.5"}):e.jsx(de,{className:"h-3.5 w-3.5"}),L==="online"?"实时同步中":L==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:o.map(s=>{const x=s.id===p,v=R0(s.id),R=q0(v),F=s.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":x,onClick:(()=>_0(s.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${x?"border-sky-500 text-sky-700":"border-transparent text-slate-500 hover:text-slate-900"}`,children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${F?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:s.nickname||s.remark||s.id}),v>0&&e.jsx("span",{"aria-label":`未读消息 ${R} 条`,className:W0(v),children:R})]},s.id)})})]}),o.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(B0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-800",children:"暂无启用账号"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"先在账号管理中启用账号,聊天会话会自动出现。"})]}):e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40",children:[e.jsxs("div",{className:"space-y-3 border-b border-slate-200 p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(xe,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:Y,onChange:(s=>b0(s.target.value)),placeholder:"搜索用户、商品或消息",className:"h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:(()=>f0(s=>!s)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${I?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:I?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void a0(p)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(ue,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[y.map(s=>e.jsxs("button",{type:"button",onClick:(()=>e0(s.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${s.chat_id===a?"bg-white shadow-chat-active":"hover:bg-white/80"}`,children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500",children:s.buyer_avatar_url?e.jsx("img",{src:s.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(U0,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-extrabold text-slate-900",children:s.buyer_name||`用户 ${s.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:W(s.last_message_at)})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs text-slate-500",children:s.last_message||"暂无消息"}),s.unread_count>0&&e.jsx("span",{"aria-label":`未读消息 ${q0(s.unread_count)} 条`,className:`ml-auto ${W0(s.unread_count)}`,children:q0(s.unread_count)})]}),s.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",s.item_title]})]})]},s.chat_id)),y.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),u0&&!Y&&!I&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void i0()),disabled:A,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[A&&e.jsx(X,{className:"h-3.5 w-3.5 animate-spin"}),A?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:u?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-black text-slate-950",children:u.buyer_name||u.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",u.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(n==null?void 0:n.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(n==null?void 0:n.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:h0,onScroll:r0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:y0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(X,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[O0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void n0()),disabled:T,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[T&&e.jsx(X,{className:"h-3.5 w-3.5 animate-spin"}),T?"正在加载":"加载更早消息"]})}),h.map(s=>{const x=s.direction==="outgoing";return s.message_type==="system"?e.jsx("div",{className:"flex justify-center py-1",children:e.jsxs("div",{className:"max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500",children:[c0(s.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:o0(s.sent_at)})]})},s.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${x?"justify-end":"justify-start"}`,children:[!x&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:u.buyer_avatar_url?e.jsx("img",{src:u.buyer_avatar_url,alt:u.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(U0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${x?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:x?(n==null?void 0:n.nickname)||(n==null?void 0:n.remark)||"我":u.buyer_name||s.sender_name||u.buyer_id}),s.message_type==="image"?e.jsx("button",{type:"button",title:"点击预览大图",onClick:p0.bind(null,s.message_key),className:`block cursor-zoom-in overflow-hidden rounded-2xl border bg-white p-1 text-left shadow-sm ${x?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:s.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):s.message_type==="video"?e.jsx("video",{src:s.content,controls:!0,preload:"metadata",className:"max-h-80 max-w-full rounded-2xl bg-black"}):e.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${x?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:c0(s.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[o0(s.sent_at),x&&(s.status==="failed"?e.jsx(he,{className:"h-3 w-3 text-red-500","aria-label":"发送失败"}):s.read_status===2?e.jsx(_e,{className:"h-3 w-3 text-sky-500","aria-label":"对方已读"}):s.status==="sent"?e.jsx(J0,{className:"h-3 w-3 text-sky-500","aria-label":"已发送未读"}):e.jsx(J0,{className:"h-3 w-3","aria-label":"发送中"}))]})]}),x&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:n!=null&&n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(U0,{className:"m-2 h-5 w-5 text-sky-600"})})]},s.message_key)})]})}),B&&e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:[e.jsx("span",{children:B}),j&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void S0()),children:"重试发送"})]}),e.jsxs("div",{className:"relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:(()=>s0(s=>!s)),disabled:O||(n==null?void 0:n.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"闲鱼表情",children:e.jsx(be,{className:"h-5 w-5"})}),D&&e.jsxs("div",{className:"absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl",children:[e.jsx("div",{className:"mb-2 text-xs font-bold text-slate-500",children:"全部表情"}),e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto",children:Q.map(([s,x])=>e.jsx("button",{type:"button",title:`[${s}]`,onClick:(()=>{t0(v=>v+`[${s}]`),s0(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:E0(x),alt:`[${s}]`,className:"h-8 w-8 object-contain"})},s))})]})]}),e.jsx("input",{ref:J,type:"file",accept:"image/*",className:"hidden",onChange:(s=>{var x;return void v0((x=s.target.files)==null?void 0:x[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var s;return(s=J.current)==null?void 0:s.click()}),disabled:O||(n==null?void 0:n.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"发送图片(最大 10MB)",children:e.jsx(fe,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100",children:[e.jsx("textarea",{value:k,onChange:(s=>t0(s.target.value)),rows:2,maxLength:2e3,onKeyDown:(s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),l0())}),onPaste:(s=>{var R;const x=Array.from(((R=s.clipboardData)==null?void 0:R.files)||[]);x.find(F=>F.type.startsWith("image/"))&&(s.preventDefault(),k0(x))}),disabled:(n==null?void 0:n.runtime_state)!=="online",placeholder:(n==null?void 0:n.runtime_state)==="online"?"输入消息,Enter 发送,Shift + Enter 换行,Ctrl + V 粘贴图片":"账号离线,暂时无法发送",className:"max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed"}),e.jsx("button",{type:"button",onClick:(()=>void l0()),disabled:!k.trim()||O||(n==null?void 0:n.runtime_state)!=="online",className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none","aria-label":"发送消息",children:O?e.jsx(X,{className:"h-4 w-4 animate-spin"}):e.jsx(Q0,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(B0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-700",children:"选择一个用户开始聊天"}),e.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"该账号的新消息会实时出现在左侧列表。"})]})})]}),M&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 p-4",onClick:U,children:e.jsxs("div",{className:"flex max-h-full w-full max-w-2xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl",onClick:(s=>s.stopPropagation()),children:[e.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-slate-200 px-5 py-3",children:[e.jsx("div",{className:"text-sm font-black text-slate-900",children:"发送图片预览"}),e.jsx("button",{type:"button",title:"取消",onClick:U,className:"rounded-lg p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-700",children:e.jsx(je,{className:"h-5 w-5"})})]}),e.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-slate-100 p-4",children:e.jsx("img",{src:M.url,alt:"待发送图片预览",className:"max-h-[55vh] max-w-full rounded-xl object-contain"})}),e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-slate-200 px-5 py-3",children:[e.jsxs("div",{className:"min-w-0 truncate text-xs text-slate-500",children:[M.file.name||"粘贴的图片"," · ",(M.file.size/1024).toFixed(0)," KB"]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button",onClick:U,className:"rounded-xl px-4 py-2 text-sm font-bold text-slate-600 transition hover:bg-slate-100",children:"取消"}),e.jsxs("button",{type:"button",onClick:(()=>void N()),disabled:O||(n==null?void 0:n.runtime_state)!=="online",className:"flex items-center gap-2 rounded-xl bg-sky-500 px-4 py-2 text-sm font-bold text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:opacity-50",children:[O?e.jsx(X,{className:"h-4 w-4 animate-spin"}):e.jsx(Q0,{className:"h-4 w-4"}),"发送"]})]})]})]})}),e.jsx(re,{open:H>=0,index:Math.max(H,0),close:(()=>Z(-1)),slides:V})]})};export{Me as default}; diff --git a/internal/webui/static/assets/Dashboard-Ba2fUvQH.js b/internal/webui/static/assets/Dashboard-Ba2fUvQH.js deleted file mode 100644 index 73bd640..0000000 --- a/internal/webui/static/assets/Dashboard-Ba2fUvQH.js +++ /dev/null @@ -1 +0,0 @@ -import{j as e,a as c}from"./react-vendor-l-BBvuKH.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{j as de,k as ge,l as te,D as he,c as pe,P as be,m as se,E as fe,T as ye}from"./icons-vendor-Bgrth_9N.js";import{R as E,B as je,X as ae,Y as re,T as F,a as ve,C as U,A as Ne,b as we,c as _e,P as ne,d as le,L as ke}from"./charts-vendor-DlHaeEQJ.js";import{g as q,c as xe,o as De}from"./index-WrujSo30.js";import"./vendor-cRYyTeIw.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Ce=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(de,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(ve,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(U,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(Ne,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(we,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(_e,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},$e=async t=>q("/api/v1/analytics/dashboard",void 0,t),Re=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return xe(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Le=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=De(s,["data","result"])||{},o=xe(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.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}},Oe=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},Te=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})))||[]},Ae=(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),ze=(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]}))},Pe=(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)}))},We=(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)}%`},Ee=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",Fe=t=>Math.max(...t.map(a=>a.sales),1),P=(t,a,s)=>t===a&&!s.aborted,ce=t=>t instanceof Error&&t.message==="请求已取消",G=(t,a)=>t instanceof Error?t.message:a,Me=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,A]=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(()=>A(u=>u+1),[]);c.useEffect(()=>{const u=++S.current,h=new AbortController;return v(m=>({...m,overview:"loading",error:""})),Promise.all([$e({signal:h.signal}),Re(void 0,{signal:h.signal})]).then(([m,g])=>{P(S.current,u,h.signal)&&(b({stats:m,items:g,itemNames:Oe(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},{signal:g.signal}),ie({start_date:h.startDate,end_date:h.endDate},{signal:g.signal}),Le({start_date:u.startDate,end_date:u.endDate},{signal:g.signal})]).then(([p,w,Y])=>{P(R.current,m,g.signal)&&(I({analytics:p,previousAnalytics:w,validOrders:Y,dateRange:u}),v($=>({...$,range:"success"})))}).catch(p=>{!P(R.current,m,g.signal)||ce(p)||v(w=>({...w,range:"error",error:G(p,"经营数据加载失败")}))}),(()=>g.abort())},[n,a,d]);const C=c.useMemo(()=>o&&_?{...o,..._}:null,[o,_]),k=(o==null?void 0:o.itemNames)||{},x=(_==null?void 0:_.analytics)||null,z=c.useMemo(()=>x?Te(x):[],[x]),N=c.useMemo(()=>x?Ae(x,k):[],[x,k]),f=c.useMemo(()=>["rgb(var(--color-brand))","rgb(var(--color-brand-highlight))","rgb(var(--color-success-500))","rgb(var(--color-warning-500))","rgb(var(--color-accent-500))"],[]),O=c.useMemo(()=>x?ze(x,k,f):[],[x,f,k]),B=c.useMemo(()=>x?Pe(x,k,f):[],[x,f,k]),V=c.useMemo(()=>Fe(N),[N]);return{data:C,status:K,chartData:z,productSalesData:N,sourceData:O,categoryData:B,maxProductSales:V,trendPercent:We(x,(C==null?void 0:C.previousAnalytics)||null),selectedRangeLabel:Ee(L),refresh:D}},j=(t,a)=>`rgb(var(--color-${t}))`,qe=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},s={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${a[t]||a.cancelled}`,children:s[t]||t})},W=({title:t,value:a,icon:s,colorClass:l,trend:n})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${l} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${l} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(s,{className:`w-6 h-6 ${l.replace("bg-","text-")}`})}),n&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(ye,{className:"w-3 h-3"})," ",n]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),Ue=()=>{const[t,a]=c.useState("7days"),[s,l]=c.useState(""),[n,o]=c.useState(""),[b,_]=c.useState(""),[I,K]=c.useState(0),v=Me({range:t,customStartDate:s,customEndDate:n,customRangeVersion:I}),{data:d,status:A,chartData:R,productSalesData:S,sourceData:L,categoryData:D,maxProductSales:C,trendPercent:k,selectedRangeLabel:x,refresh:z}=v,N=(d==null?void 0:d.stats)||null,f=(d==null?void 0:d.analytics)||null,O=(d==null?void 0:d.validOrders.orders)||[],B=(d==null?void 0:d.validOrders.total)||0,V=(d==null?void 0:d.validOrders.truncated)||!1,u=A.range==="loading",h=A.error,m=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],g=r=>`¥${Number(r||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(h&&(!N||!f))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(ge,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:z,children:"重新加载"})]});if(!N||!f)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(te,{className:"w-8 h-8 animate-spin text-brand"})});const p=f.revenue_stats.total_orders||0,w=f.revenue_stats.total_amount||0,Y=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let $;try{$=ue(t,new Date,s,n)}catch{$={startDate:s,endDate:n}}const T=b.trim().toLowerCase(),J=O.filter(r=>{var y,Q,Z,ee;return((y=r.order_id)==null?void 0:y.toLowerCase().includes(T))||((Q=r.item_id)==null?void 0:Q.toLowerCase().includes(T))||((Z=r.item_title)==null?void 0:Z.toLowerCase().includes(T))||((ee=r.buyer_id)==null?void 0:ee.toLowerCase().includes(T))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:z,children:"重试"})]}),e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[Y.map(r=>e.jsx("button",{onClick:(()=>a(r.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${t===r.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:r.label},r.key)),t==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:s,onChange:(r=>l(r.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:n,onChange:(r=>o(r.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:(()=>K(r=>r+1)),className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(W,{title:"累计营收 (CNY)",value:`¥${f.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:he,colorClass:"bg-blue-400",trend:k||void 0}),e.jsx(W,{title:"活跃账号 / 总数",value:`${N.active_cookies} / ${N.total_cookies}`,icon:pe,colorClass:"bg-blue-500"}),e.jsx(W,{title:"订单数",value:f.revenue_stats.total_orders.toLocaleString(),icon:de,colorClass:"bg-blue-500"}),e.jsx(W,{title:"库存卡密余量",value:N.available_card_stock,icon:be,colorClass:"bg-purple-500"})]}),e.jsx(Ce,{chartData:R,selectedRangeLabel:x,totalAmount:w}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:S.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:S.map((r,y)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${y<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:y+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:r.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[r.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${Math.max(8,r.sales/C*100)}%`}})})]},`${r.name}-${y}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${p} 单`,children:L.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ne,{accessibilityLayer:!1,children:[e.jsx(le,{data:L,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:L.map((r,y)=>e.jsx(U,{fill:r.color},`cell-${y}`))}),e.jsx(F,{formatter:(r=>`${Number(r||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(ke,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(r=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:r}))})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:p}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),V&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",O.length," / ",B," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:b,onChange:(r=>_(r.target.value)),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:u?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(te,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):J.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(se,{className:"w-7 h-7 text-gray-300"})}),T?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",O.length," 单参与统计,但没有订单号、商品、买家匹配“",b,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",$.startDate," 至 ",$.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",f.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:J.map(r=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(se,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:r.item_title||r.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:r.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",r.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:r.buyer_id}),r.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:me(r.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",r.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(qe,{status:r.status||r.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${r.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(fe,{className:"w-4 h-4"})})})]},r.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),D.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${g(w)}`,children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ne,{accessibilityLayer:!1,children:[e.jsx(le,{data:D,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:D.map((r,y)=>e.jsx(U,{fill:r.color||m[y%m.length]},`cell-${y}`))}),e.jsx(F,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(r=>`¥${Number(r||0).toLocaleString()}`)})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:g(w)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:D.map(r=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:r.color||m[D.indexOf(r)%m.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:r.name,children:r.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",r.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[r.percentage,"%"]})]})]},r.name))})]})]})]})]})};export{qe as StatusBadge,Ue as default}; diff --git a/internal/webui/static/assets/Dashboard-CJrI6NVV.js b/internal/webui/static/assets/Dashboard-CJrI6NVV.js new file mode 100644 index 0000000..fe58df5 --- /dev/null +++ b/internal/webui/static/assets/Dashboard-CJrI6NVV.js @@ -0,0 +1 @@ +import{j as e,a as c}from"./react-vendor-l-BBvuKH.js";import{f as ge}from"./dateTime-DDi7rqpW.js";import{j as xe,k as he,l as se,D as pe,c as be,P as fe,m as ae,E as ye,T as je}from"./icons-vendor-Bgrth_9N.js";import{R as q,B as ve,X as re,Y as ne,T as W,a as Ne,C as X,A as we,b as _e,c as ke,P as le,d as oe,L as De}from"./charts-vendor-DlHaeEQJ.js";import{r as M,c as K}from"./index-CiBUw4Te.js";import{c as ue,o as Se}from"./contract-COFcZjyb.js";import"./vendor-cRYyTeIw.js";const F=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},J=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},H=(t,a)=>({startDate:F(J(t,-(a-1))),endDate:F(t)}),me=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?H(J(a,-1),1):H(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Ce=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=J(a,-1);return H(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,$e=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(xe,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(ve,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(re,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(ne,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(W,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(Ne,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(X,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(we,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(re,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(ne,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(_e,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(W,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(ke,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),ie=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Re=async t=>M(a=>K.GET("/api/v1/analytics/dashboard",{signal:a}),t),Le=async(t,a)=>{const s=await M(n=>K.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:n}),a);return ue(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ce=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:F(n),end_date:F(l)}}else s=t;return M(l=>K.GET("/api/v1/analytics/orders",{params:{query:{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()}},signal:l}),a)},Te=async(t,a)=>{const s=await M(u=>K.GET("/api/v1/analytics/orders/valid",{params:{query:{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()}},signal:u}),a),l=Se(s,["data","result"])||{},o=ue(s,["orders","data","items"]).map(u=>({...u,id:u.order_id,status:ie(u.status||u.order_status),order_status:ie(u.order_status),quantity:Number(u.quantity||1)}));return{orders:o,total:Number(l.total??o.length),truncated:l.truncated===!0}},Oe=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},Ae=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})))||[]},Ee=(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),ze=(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]}))},Pe=(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)}))},qe=(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)}%`},We=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",Fe=t=>Math.max(...t.map(a=>a.sales),1),z=(t,a,s)=>t===a&&!s.aborted,de=t=>t instanceof Error&&t.message==="请求已取消",U=(t,a)=>t instanceof Error?t.message:a,Me=t=>{const{range:a,customStartDate:s,customEndDate:l,customRangeVersion:n}=t,[o,u]=c.useState(null),[_,G]=c.useState(null),[I,v]=c.useState({overview:"idle",range:"idle",error:""}),[d,A]=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(()=>A(m=>m+1),[]);c.useEffect(()=>{const m=++S.current,p=new AbortController;return v(g=>({...g,overview:"loading",error:""})),Promise.all([Re({signal:p.signal}),Le(void 0,{signal:p.signal})]).then(([g,h])=>{z(S.current,m,p.signal)&&(u({stats:g,items:h,itemNames:Oe(h)}),v(b=>({...b,overview:"success"})))}).catch(g=>{!z(S.current,m,p.signal)||de(g)||v(h=>({...h,overview:"error",error:U(g,"概览加载失败")}))}),(()=>p.abort())},[d]),c.useEffect(()=>{let m;try{m=me(a,new Date,s,l)}catch(b){v(w=>({...w,range:"error",error:U(b,"日期范围无效")}));return}const p=Ce(m),g=++R.current,h=new AbortController;return v(b=>({...b,range:"loading",error:""})),Promise.all([ce({start_date:m.startDate,end_date:m.endDate},{signal:h.signal}),ce({start_date:p.startDate,end_date:p.endDate},{signal:h.signal}),Te({start_date:m.startDate,end_date:m.endDate},{signal:h.signal})]).then(([b,w,Y])=>{z(R.current,g,h.signal)&&(G({analytics:b,previousAnalytics:w,validOrders:Y,dateRange:m}),v($=>({...$,range:"success"})))}).catch(b=>{!z(R.current,g,h.signal)||de(b)||v(w=>({...w,range:"error",error:U(b,"经营数据加载失败")}))}),(()=>h.abort())},[n,a,d]);const C=c.useMemo(()=>o&&_?{...o,..._}:null,[o,_]),k=(o==null?void 0:o.itemNames)||{},x=(_==null?void 0:_.analytics)||null,E=c.useMemo(()=>x?Ae(x):[],[x]),N=c.useMemo(()=>x?Ee(x,k):[],[x,k]),f=c.useMemo(()=>["rgb(var(--color-brand))","rgb(var(--color-brand-highlight))","rgb(var(--color-success-500))","rgb(var(--color-warning-500))","rgb(var(--color-accent-500))"],[]),T=c.useMemo(()=>x?ze(x,k,f):[],[x,f,k]),B=c.useMemo(()=>x?Pe(x,k,f):[],[x,f,k]),V=c.useMemo(()=>Fe(N),[N]);return{data:C,status:I,chartData:E,productSalesData:N,sourceData:T,categoryData:B,maxProductSales:V,trendPercent:qe(x,(C==null?void 0:C.previousAnalytics)||null),selectedRangeLabel:We(L),refresh:D}},j=(t,a)=>`rgb(var(--color-${t}))`,Ke=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},s={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${a[t]||a.cancelled}`,children:s[t]||t})},P=({title:t,value:a,icon:s,colorClass:l,trend:n})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${l} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${l} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(s,{className:`w-6 h-6 ${l.replace("bg-","text-")}`})}),n&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(je,{className:"w-3 h-3"})," ",n]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),He=()=>{const[t,a]=c.useState("7days"),[s,l]=c.useState(""),[n,o]=c.useState(""),[u,_]=c.useState(""),[G,I]=c.useState(0),v=Me({range:t,customStartDate:s,customEndDate:n,customRangeVersion:G}),{data:d,status:A,chartData:R,productSalesData:S,sourceData:L,categoryData:D,maxProductSales:C,trendPercent:k,selectedRangeLabel:x,refresh:E}=v,N=(d==null?void 0:d.stats)||null,f=(d==null?void 0:d.analytics)||null,T=(d==null?void 0:d.validOrders.orders)||[],B=(d==null?void 0:d.validOrders.total)||0,V=(d==null?void 0:d.validOrders.truncated)||!1,m=A.range==="loading",p=A.error,g=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],h=r=>`¥${Number(r||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(p&&(!N||!f))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(he,{className:"w-8 h-8"}),e.jsx("span",{children:p}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:E,children:"重新加载"})]});if(!N||!f)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(se,{className:"w-8 h-8 animate-spin text-brand"})});const b=f.revenue_stats.total_orders||0,w=f.revenue_stats.total_amount||0,Y=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let $;try{$=me(t,new Date,s,n)}catch{$={startDate:s,endDate:n}}const O=u.trim().toLowerCase(),Q=T.filter(r=>{var y,Z,ee,te;return((y=r.order_id)==null?void 0:y.toLowerCase().includes(O))||((Z=r.item_id)==null?void 0:Z.toLowerCase().includes(O))||((ee=r.item_title)==null?void 0:ee.toLowerCase().includes(O))||((te=r.buyer_id)==null?void 0:te.toLowerCase().includes(O))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[p&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:p}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:E,children:"重试"})]}),e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[Y.map(r=>e.jsx("button",{onClick:(()=>a(r.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${t===r.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:r.label},r.key)),t==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:s,onChange:(r=>l(r.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:n,onChange:(r=>o(r.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:(()=>I(r=>r+1)),className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(P,{title:"累计营收 (CNY)",value:`¥${f.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:pe,colorClass:"bg-blue-400",trend:k||void 0}),e.jsx(P,{title:"活跃账号 / 总数",value:`${N.active_cookies} / ${N.total_cookies}`,icon:be,colorClass:"bg-blue-500"}),e.jsx(P,{title:"订单数",value:f.revenue_stats.total_orders.toLocaleString(),icon:xe,colorClass:"bg-blue-500"}),e.jsx(P,{title:"库存卡密余量",value:N.available_card_stock,icon:fe,colorClass:"bg-purple-500"})]}),e.jsx($e,{chartData:R,selectedRangeLabel:x,totalAmount:w}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:S.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:S.map((r,y)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${y<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:y+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:r.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[r.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${Math.max(8,r.sales/C*100)}%`}})})]},`${r.name}-${y}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${b} 单`,children:L.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(le,{accessibilityLayer:!1,children:[e.jsx(oe,{data:L,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:L.map((r,y)=>e.jsx(X,{fill:r.color},`cell-${y}`))}),e.jsx(W,{formatter:(r=>`${Number(r||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(De,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(r=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:r}))})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:b}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),V&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",T.length," / ",B," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:u,onChange:(r=>_(r.target.value)),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:m?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(se,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):Q.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(ae,{className:"w-7 h-7 text-gray-300"})}),O?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",T.length," 单参与统计,但没有订单号、商品、买家匹配“",u,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",$.startDate," 至 ",$.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",f.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:Q.map(r=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(ae,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:r.item_title||r.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:r.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",r.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:r.buyer_id}),r.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:ge(r.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",r.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(Ke,{status:r.status||r.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${r.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(ye,{className:"w-4 h-4"})})})]},r.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),D.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${h(w)}`,children:[e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(le,{accessibilityLayer:!1,children:[e.jsx(oe,{data:D,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:D.map((r,y)=>e.jsx(X,{fill:r.color||g[y%g.length]},`cell-${y}`))}),e.jsx(W,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(r=>`¥${Number(r||0).toLocaleString()}`)})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:h(w)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:D.map(r=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:r.color||g[D.indexOf(r)%g.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:r.name,children:r.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",r.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[r.percentage,"%"]})]})]},r.name))})]})]})]})]})};export{Ke as StatusBadge,He as default}; diff --git a/internal/webui/static/assets/ItemList-C0hxXhgx.js b/internal/webui/static/assets/ItemList-C0hxXhgx.js new file mode 100644 index 0000000..5551ee4 --- /dev/null +++ b/internal/webui/static/assets/ItemList-C0hxXhgx.js @@ -0,0 +1,2 @@ +import{j as e,a as r,b as we}from"./react-vendor-l-BBvuKH.js";import{r as q,c as B,A as bt}from"./index-CiBUw4Te.js";import{c as Qe}from"./contract-COFcZjyb.js";import{a3 as gt,U as $e,R as Se,N as De,a4 as Pe,a5 as _e,V as yt,y as ft,B as jt,a6 as Oe,a7 as vt,a8 as Nt,A as wt,d as _t,X as ye,o as kt,a9 as Ue,I as ze}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const Ke="ydisks-amap-js-api",Ct="c9b68d4ce9a2a97f22a4a439404488ca";let fe=null;const It=()=>Ct,St=()=>window.AMap?Promise.resolve(window.AMap):fe||(fe=new Promise((s,a)=>{const n=document.getElementById(Ke),d=n||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(G)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},G=window.setTimeout(()=>{u(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,d.id=Ke,d.async=!0,d.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(It())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,d.onerror=()=>{u(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},n||document.head.appendChild(d)}).catch(s=>{throw fe=null,s}),fe),ke=s=>Number.isFinite(s)&&s!==0,Pt=s=>{var u,f;const a=Number((u=s.location)==null?void 0:u.lng),n=Number((f=s.location)==null?void 0:f.lat),d={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:n,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!d.division_id||!d.province||!d.city||!d.poi_id||!d.poi_name||!ke(a)||!ke(n)||a<-180||a>180||n<-90||n>90?null:d},qt=async(s,a,n={})=>{if(!ke(s)||!ke(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const d=await St();return new Promise((u,f)=>{var $,M;let G=!1;const k=Math.max(1,n.timeoutMs??1e4),R=F=>{var p;G||(G=!0,globalThis.clearTimeout(W),(p=n.signal)==null||p.removeEventListener("abort",I),F())},I=()=>R(()=>f(new DOMException("aborted","AbortError"))),W=globalThis.setTimeout(()=>R(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if(($=n.signal)!=null&&$.aborted){I();return}(M=n.signal)==null||M.addEventListener("abort",I,{once:!0}),new d.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(F,p)=>{var x;if(G)return;if(F!=="complete"){if(F==="no_data"){R(()=>u([]));return}R(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const E=(((x=p==null?void 0:p.poiList)==null?void 0:x.pois)||[]).map(Pt).filter(j=>j!==null);R(()=>u(E))})})},Bt=async s=>q(a=>B.GET("/api/v1/accounts/details",{signal:a}),s),Je=async s=>q(a=>B.GET("/api/v1/automation-rules",{signal:a}),s),Et=(s,a,n)=>qt(s,a,n),qe=(s,a)=>{if(s instanceof bt)switch(s.code){case"stock_permission_missing":return"发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。";case"conflict":case"item_conflict":return"商品状态已发生变化,请刷新后重试。";case"external_result_unknown":case"manual_review_required":return"平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。";case"retryable":case"temporarily_unavailable":return"平台暂时不可用,请稍后重试。";default:return s.message||a}if(s instanceof Error)return s.message;const n=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof n=="string"?n:a},Be=s=>s===!0||s===1||s==="1",Ze=async(s,a)=>{const n=await q(u=>B.GET("/api/v1/items",{params:{query:{cookie_id:s}},signal:u}),a);return Qe(n,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:Be(u.is_multi_spec),is_multi_qty_ship:Be(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:Be(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Lt=async s=>q(a=>B.POST("/api/v1/items/get-all-from-account",{body:{cookie_id:s},signal:a})),At=async(s,a)=>q(n=>B.DELETE("/api/v1/items/{cookie_id}/{item_id}",{params:{path:{cookie_id:s,item_id:a}},signal:n})),Rt=async(s,a)=>q(n=>B.POST("/api/v1/items/{cookie_id}",{params:{path:{cookie_id:s}},body:a,signal:n})),Mt=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const n of s.images)a.append("images",n);return q(n=>B.POST("/api/v1/items/publish",{body:a,signal:n}))},Ft=async(s,a,n)=>q(d=>B.POST("/api/v1/items/publish-categories/recommend",{body:{cookie_id:s,keyword:a},signal:d}),n),Gt=async(s,a)=>{const n=new FormData;return n.set("file",s.file),s.imagesZip&&n.set("images_zip",s.imagesZip),s.defaultCookieId&&n.set("default_cookie_id",s.defaultCookieId),n.set("fallback_category_id",s.fallbackCategory.catId),n.set("fallback_category_name",s.fallbackCategory.catName),n.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),n.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&n.set("location",JSON.stringify(s.location)),n.set("publish_interval_seconds",String(s.publishIntervalSeconds??5)),q(d=>B.POST("/api/v1/items/publish-batches/preview",{body:n,signal:d}),a)},Tt=async(s,a)=>q(n=>B.POST("/api/v1/items/publish-batches",{body:{preview_id:s},signal:n}),a),oe=async(s,a)=>q(n=>B.GET("/api/v1/items/publish-batches/{batch_id}",{params:{path:{batch_id:s}},signal:n}),a),et=async(s=20,a)=>{const n=await q(d=>B.GET("/api/v1/items/publish-batches",{params:{query:{limit:s}},signal:d}),a);return Qe(n,["batches","data","items"])},Ve=async(s,a)=>q(n=>B.DELETE("/api/v1/items/publish-batches/{batch_id}",{params:{path:{batch_id:s}},signal:n}),a),$t=async(s,a)=>q(n=>B.POST("/api/v1/items/publish-batches/{batch_id}/cancel",{params:{path:{batch_id:s}},body:{},signal:n}),a),Dt=async(s,a)=>q(n=>B.POST("/api/v1/items/publish-batches/{batch_id}/retry-failed",{params:{path:{batch_id:s}},body:{},signal:n}),a),Ot=async(s,a,n)=>q(d=>B.PUT("/api/v1/items/{cookie_id}/{item_id}",{params:{path:{cookie_id:s,item_id:a}},body:n,signal:d})),Ut=s=>s.find(a=>a.status==="pending"||a.status==="running"||a.status==="canceling"),je=s=>s==="pending"||s==="running"||s==="canceling",zt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),Kt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!je(s.status)),Jt=(s,a)=>s===a,We=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:return s||"-"}},Ye=s=>{switch(s){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Zt=({phase:s})=>{const a=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:a.map(([n,d])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===n?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:d},n))})},Vt=s=>{const[a,n]=r.useState(!1),[d,u]=r.useState("upload"),[f,G]=r.useState(null),[k,R]=r.useState(null),[I,W]=r.useState(""),[U,$]=r.useState(!1),[M,F]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[p,E]=r.useState(null),[x,j]=r.useState(null),[S,Y]=r.useState(null),[H,X]=r.useState([]),[z,D]=r.useState(null),[Z,C]=r.useState(5),[le,b]=r.useState(!1),y=r.useRef(0),g=r.useRef(null),v=r.useCallback(()=>{var h;(h=g.current)==null||h.abort();const l=new AbortController;g.current=l;const i=++y.current;return{controller:l,requestGeneration:i}},[]),m=r.useCallback((l,i)=>l===y.current&&i===g.current&&!i.signal.aborted,[]);r.useEffect(()=>(()=>{var l;(l=g.current)==null||l.abort(),y.current+=1}),[]);const re=r.useCallback(async()=>{const l=v();u("upload"),E(null),j(null),G(null),R(null),W(""),F({catId:"",catName:"",channelCatId:"",tbCatId:""}),X([]),D(null),C(5),n(!0),b(!0);try{const i=await et(20,{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;const h=Ut(i);if(h!=null&&h.id){const L=await oe(h.id,{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;Y(L),j(L),C(L.publish_interval_seconds||5),u(je(L.status)?"running":"done")}}catch(i){if(!m(l.requestGeneration,l.controller))return;console.error("恢复最近批量铺货任务失败:",i)}finally{m(l.requestGeneration,l.controller)&&b(!1)}},[v,m]),Q=r.useCallback(async()=>{const l=I.trim();if(!s.selectedAccount){alert("请先选择默认发布账号");return}if(!l){alert("请输入类目关键词");return}const i=v();$(!0);try{const h=await Ft(s.selectedAccount,l,{signal:i.controller.signal});if(!m(i.requestGeneration,i.controller))return;const L=h.category;F({catId:L.cat_id,catName:L.cat_name,channelCatId:L.channel_cat_id,tbCatId:L.tb_cat_id||""})}catch(h){if(!m(i.requestGeneration,i.controller))return;console.error("获取推荐类目失败:",h),alert((h==null?void 0:h.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{m(i.requestGeneration,i.controller)&&$(!1)}},[I,v,m,s.selectedAccount]),K=r.useCallback(async()=>{if(!(S!=null&&S.id))return;const l=v();b(!0),n(!0);try{const i=await oe(S.id,{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;j(i),C(i.publish_interval_seconds||5),u(je(i.status)?"running":"done")}catch(i){if(!m(l.requestGeneration,l.controller))return;console.error("加载最近批量铺货结果失败:",i)}finally{m(l.requestGeneration,l.controller)&&b(!1)}},[v,m,S==null?void 0:S.id]),O=r.useCallback(async()=>{if(!f){alert("请先上传商品表格");return}if(!s.selectedAccount){alert("请先选择默认发布账号");return}const l=v();b(!0);try{const i=await Gt({file:f,imagesZip:k,defaultCookieId:s.selectedAccount,fallbackCategory:M,location:z||void 0,publishIntervalSeconds:Z},{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;E(i),j(null),u("preview")}catch(i){if(!m(l.requestGeneration,l.controller))return;console.error("批量铺货预检失败:",i),alert((i==null?void 0:i.message)||"预检失败,请检查表格和图片 zip")}finally{m(l.requestGeneration,l.controller)&&b(!1)}},[M,f,k,z,Z,v,m,s.selectedAccount]),ae=r.useCallback(async()=>{if(!(p!=null&&p.preview_id))return;if(!zt(p)){alert("没有可发布的商品行");return}const l=v();b(!0);try{const i=await Tt(p.preview_id,{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;const h=await oe(i.batch_id||p.preview_id,{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;j(h),Y(h),u(h.status==="running"?"running":"done")}catch(i){if(!m(l.requestGeneration,l.controller))return;console.error("启动批量铺货失败:",i),alert((i==null?void 0:i.message)||"启动发布任务失败")}finally{m(l.requestGeneration,l.controller)&&b(!1)}},[p,v,m]),de=r.useCallback(async()=>{if(!(x!=null&&x.id)||!confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。"))return;const l=v();b(!0);try{const i=await $t(x.id,{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;const h=await oe(x.id,{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;j(h),u((i==null?void 0:i.status)==="canceling"||h.status==="canceling"?"running":"done")}catch(i){if(!m(l.requestGeneration,l.controller))return;alert((i==null?void 0:i.message)||"取消失败")}finally{m(l.requestGeneration,l.controller)&&b(!1)}},[x==null?void 0:x.id,v,m]),ne=r.useCallback(async()=>{const l=p==null?void 0:p.preview_id,i=v();if(l&&d==="preview")try{await Ve(l,{signal:i.controller.signal})}catch(h){if(!m(i.requestGeneration,i.controller))return;console.error("清理批量铺货预检失败:",h)}m(i.requestGeneration,i.controller)&&(E(null),u("upload"))},[d,p==null?void 0:p.preview_id,v,m]),xe=r.useCallback(async()=>{var i;const l=p==null?void 0:p.preview_id;if((i=g.current)==null||i.abort(),y.current+=1,E(null),u("upload"),n(!1),l&&d==="preview")try{await Ve(l)}catch(h){console.error("关闭批量铺货弹窗时清理预检失败:",h)}},[d,p==null?void 0:p.preview_id]),me=r.useCallback(async()=>{if(!(x!=null&&x.id)||!Kt(x))return;const l=v();b(!0);try{if(await Dt(x.id,{signal:l.controller.signal}),!m(l.requestGeneration,l.controller))return;const i=await oe(x.id,{signal:l.controller.signal});if(!m(l.requestGeneration,l.controller))return;j(i),u("running")}catch(i){if(!m(l.requestGeneration,l.controller))return;alert((i==null?void 0:i.message)||"重试失败")}finally{m(l.requestGeneration,l.controller)&&b(!1)}},[x,v,m]);return r.useEffect(()=>{if(!a||!(x!=null&&x.id)||!je(x.status))return;const l=++y.current,i=new AbortController;let h=!1;const L=async()=>{if(!(h||i.signal.aborted)){h=!0;try{const N=await oe(x.id,{signal:i.signal});if(!Jt(l,y.current))return;j(N),Y(N),je(N.status)||(u("done"),await Promise.all([s.loadItems(),s.loadShippingRules()]))}catch(N){i.signal.aborted||console.error("刷新批量铺货进度失败:",N)}finally{h=!1}}},o=window.setInterval(()=>void L(),3e3);return(()=>{window.clearInterval(o),i.abort(),y.current+=1})},[x==null?void 0:x.id,x==null?void 0:x.status,s.loadItems,s.loadShippingRules,a]),{showBatchModal:a,setShowBatchModal:n,batchLoading:le,batchPhase:d,setBatchPhase:u,batchFile:f,setBatchFile:G,batchImagesZip:k,setBatchImagesZip:R,batchCategoryKeyword:I,setBatchCategoryKeyword:W,batchCategoryLoading:U,batchFallbackCategory:M,setBatchFallbackCategory:F,batchPreview:p,setBatchPreview:E,batchDetail:x,setBatchDetail:j,recentBatch:S,setRecentBatch:Y,batchLocations:H,batchLocation:z,setBatchLocations:X,setBatchLocation:D,batchPublishIntervalSeconds:Z,setBatchPublishIntervalSeconds:C,openBatchModal:re,handleRecommendBatchCategory:Q,openRecentBatchResult:K,handlePreviewBatch:O,handleStartBatch:ae,handleCancelBatch:de,abandonBatchPreview:ne,closeBatchModal:xe,handleRetryBatchFailed:me}},He=()=>({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),Xe=(s="")=>({cookie_id:s,title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),Wt=({selectedAccount:s,setSelectedAccount:a,setItems:n,loadItems:d,loadShippingRules:u,onConfigureDelivery:f,setBatchLocations:G,setBatchLocation:k})=>{const[R,I]=r.useState(!1),[W,U]=r.useState(!1),[$,M]=r.useState(!1),[F,p]=r.useState(!1),[E,x]=r.useState(!1),[j,S]=r.useState(!1),[Y,H]=r.useState([]),[X,z]=r.useState(null),[D,Z]=r.useState(null),[C,le]=r.useState({}),[b,y]=r.useState(He),[g,v]=r.useState(Xe),[m,re]=r.useState([]),Q=r.useRef(null),K=r.useRef(0);r.useEffect(()=>{if(!E||g.images.length===0){re([]);return}const o=g.images.map((N,A)=>({key:N.name+A,url:URL.createObjectURL(N)}));return re(o),(()=>o.forEach(N=>URL.revokeObjectURL(N.url)))},[g.images,E]);const O=r.useCallback(()=>{var o;(o=Q.current)==null||o.abort(),Q.current=null,K.current+=1,S(!1)},[]);r.useEffect(()=>O,[O]),r.useEffect(()=>{E||O()},[O,E]);const ae=r.useCallback(async()=>{if(!s)return alert("请先选择账号");I(!0);try{const o=await Lt(s);await d(),alert((o==null?void 0:o.message)||"商品同步完成")}catch(o){console.error("同步商品失败:",o),alert(qe(o,"同步失败,请重试"))}finally{I(!1)}},[d,s]),de=r.useCallback(o=>{Z(o),le({...o}),M(!0)},[]),ne=r.useCallback(async()=>{if(D)try{await Ot(D.cookie_id,D.item_id,{item_title:C.item_title||"",item_description:C.item_description||"",item_category:C.item_category||"",item_price:C.item_price||"",item_detail:C.item_detail||D.item_detail||""}),await d(),await u(),M(!1),Z(null)}catch(o){console.error("更新商品失败:",o),alert("更新失败,请重试")}},[C,d,u,D]),xe=r.useCallback(async o=>{if(confirm(`确认删除商品"${o.item_title}"吗?`))try{await At(o.cookie_id,o.item_id),n(N=>N.filter(A=>!(A.cookie_id===o.cookie_id&&A.item_id===o.item_id)))}catch(N){console.error("删除商品失败:",N),alert("删除失败,请重试")}},[n]),me=r.useCallback(async()=>{try{if(!b.cookie_id||!b.item_id){alert("请选择账号并填写商品ID");return}await Rt(b.cookie_id,{item_id:b.item_id,item_title:b.item_title,item_price:b.item_price,item_detail:b.item_image?JSON.stringify({item_image:b.item_image}):""}),await d(),p(!1),y(He())}catch(o){console.error("添加商品失败:",o),alert("添加失败,请重试")}},[b,d]),ve=r.useCallback(async()=>{if(!g.cookie_id)return alert("请选择发布账号");if(!g.title.trim())return alert("请填写商品标题");if(!g.price.trim())return alert("请填写商品价格");if(!g.quantity||Number(g.quantity)<=0)return alert("库存数量必须大于 0");if(g.images.length===0)return alert("至少上传 1 张商品图片");if(g.postage_mode==="fixed"&&!g.postage.trim())return alert("请填写一口价邮费");U(!0);try{const o=await Mt({...g,location:X||void 0});if(await d(),x(!1),v(Xe(s||"")),H([]),z(null),o!=null&&o.item_id){const N={id:o.item_id,cookie_id:g.cookie_id,item_id:o.item_id,item_title:o.item_title||g.title,item_price:o.item_price||g.price,item_image:o.item_image};f(N),alert("商品发布成功,ID: "+o.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(o){console.error("发布商品失败:",o),alert(qe(o,"发布失败,请重试"))}finally{U(!1)}},[d,f,g,X,s]),l=r.useCallback(()=>{const A=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","类目ID","类目名称","频道类目ID","淘宝类目ID","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","","","","","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","","","","","否","","否","","否","","",""]]].map(ue=>ue.map(he=>`"${String(he).replace(/"/g,'""')}"`).join(",")).join(` +`),ee=new Blob(["\uFEFF"+A],{type:"text/csv;charset=utf-8"}),T=URL.createObjectURL(ee),P=document.createElement("a");P.href=T,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(T)},[]),i=r.useCallback(()=>{y(o=>({...o,cookie_id:s||o.cookie_id})),p(!0)},[s]),h=r.useCallback(()=>{v(o=>({...o,cookie_id:s||o.cookie_id})),x(!0)},[s]),L=r.useCallback(async o=>{if(!(o?s:g.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");O();const A=new AbortController;Q.current=A;const ee=++K.current;S(!0);try{const T=await new Promise((ue,he)=>{const Ce=te=>ue(te),ie=te=>he(te);navigator.geolocation.getCurrentPosition(Ce,ie,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(A.signal.aborted||ee!==K.current)return;const P=await Et(T.coords.longitude,T.coords.latitude,{signal:A.signal});if(A.signal.aborted||ee!==K.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(G(P),k(P[0])):(H(P),z(P[0]))}catch(T){if(A.signal.aborted||ee!==K.current)return;if(typeof T=="object"&&T!==null&&"code"in T){const P=T;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(qe(T,"获取发货地失败"))}finally{ee===K.current&&(Q.current=null,S(!1))}},[O,g.cookie_id,s,k,G]);return{selectedAccount:s,setSelectedAccount:a,loading:R,publishing:W,showEditModal:$,setShowEditModal:M,showAddModal:F,setShowAddModal:p,showPublishModal:E,setShowPublishModal:x,locationLoading:j,publishLocations:Y,setPublishLocations:H,publishLocation:X,setPublishLocation:z,selectedItem:D,editForm:C,setEditForm:le,addForm:b,setAddForm:y,publishForm:g,setPublishForm:v,publishImagePreviews:m,handleSync:ae,handleEdit:de,handleSaveEdit:ne,handleDelete:xe,handleAddItem:me,handlePublishItem:ve,downloadPublishTemplate:l,openAddModal:i,openPublishModal:h,locateForPublish:L}},Yt=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},ss=({onConfigureDelivery:s})=>{const[a,n]=r.useState([]),[d,u]=r.useState([]),[f,G]=r.useState([]),[k,R]=r.useState(""),[I,W]=r.useState(""),U=r.useRef(0),$=r.useRef(0),M=r.useCallback(async()=>{const t=++U.current,c=await Ze();t===U.current&&n(c)},[]),F=r.useCallback(async()=>{const t=++$.current,c=await Je();t===$.current&&u(c)},[]),p=Vt({selectedAccount:k,loadItems:M,loadShippingRules:F}),{showBatchModal:E,batchLoading:x,batchPhase:j,batchFile:S,setBatchFile:Y,batchImagesZip:H,setBatchImagesZip:X,batchCategoryKeyword:z,setBatchCategoryKeyword:D,batchCategoryLoading:Z,batchFallbackCategory:C,setBatchFallbackCategory:le,batchPreview:b,batchDetail:y,recentBatch:g,setRecentBatch:v,batchLocations:m,batchLocation:re,batchPublishIntervalSeconds:Q,setBatchPublishIntervalSeconds:K,setBatchLocations:O,setBatchLocation:ae,openBatchModal:de,handleRecommendBatchCategory:ne,openRecentBatchResult:xe,handlePreviewBatch:me,handleStartBatch:ve,handleCancelBatch:l,abandonBatchPreview:i,closeBatchModal:h,handleRetryBatchFailed:L}=p,o=Wt({selectedAccount:k,setSelectedAccount:R,setItems:n,loadItems:M,loadShippingRules:F,onConfigureDelivery:s,setBatchLocations:O,setBatchLocation:ae}),{loading:N,publishing:A,showEditModal:ee,setShowEditModal:T,showAddModal:P,setShowAddModal:ue,showPublishModal:he,setShowPublishModal:Ce,locationLoading:ie,publishLocations:te,setPublishLocations:tt,publishLocation:st,setPublishLocation:Ee,selectedItem:Le,editForm:se,setEditForm:Ne,addForm:J,setAddForm:pe,publishForm:w,setPublishForm:V,publishImagePreviews:Ae,handleSync:at,handleEdit:lt,handleSaveEdit:rt,handleDelete:nt,handleAddItem:it,handlePublishItem:ct,downloadPublishTemplate:ot,openAddModal:dt,openPublishModal:xt,locateForPublish:Re}=o;r.useEffect(()=>{const t=new AbortController,c=++U.current,_=++$.current;let ge=!0;return Promise.all([Bt({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),et(20,{signal:t.signal})]).then(([ce,ut,ht,Te])=>{if(!ge||t.signal.aborted||c!==U.current||_!==$.current)return;G(ce),n(ut),u(ht);const pt=Te.find(Ie=>["running","canceling"].includes(Ie.status))||Te.find(Ie=>Ie.status!=="preview");v(pt||null)}).catch(ce=>{t.signal.aborted||console.error("加载商品配置失败:",ce)}),(()=>{ge=!1,t.abort()})},[]);const mt=t=>d.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id).length>0?d.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id):d.filter(c=>c.cookie_id===t.cookie_id&&!c.item_id),Me=r.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=r.useMemo(()=>I?a.filter(t=>t.cookie_id===I):a,[I,a]),be=t=>{const c=Me.get(t),_=(c==null?void 0:c.remark)||(c==null?void 0:c.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Ge=t=>{const c=Me.get(t);return(c==null?void 0:c.remark)||(c==null?void 0:c.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(gt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:(t=>W(t.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),f.map(t=>e.jsx("option",{value:t.id,children:be(t.id)},t.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx($e,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:k,onChange:(t=>R(t.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),f.map(t=>e.jsx("option",{value:t.id,children:be(t.id)},t.id))]})]})]}),e.jsxs("button",{onClick:at,disabled:N||!k,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Se,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:dt,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(De,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:xt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Pe,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void de()),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(_e,{className:"w-4 h-4"}),g&&["running","canceling"].includes(g.status)?"继续批量任务":"批量铺货"]}),g&&!["running","canceling"].includes(g.status)&&e.jsx("button",{onClick:(()=>void xe()),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Fe.map(t=>{const c=mt(t),_=c.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:(()=>lt(t)),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors",title:"编辑",children:e.jsx(yt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:(()=>nt(t)),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(ft,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[t.item_image?e.jsx("img",{src:t.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(jt,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:Yt(t.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:t.item_title}),e.jsxs("div",{className:"mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:Ge(t.cookie_id),children:[e.jsx($e,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:Ge(t.cookie_id)})]}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",t.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${_?"text-emerald-600":"text-amber-600"}`,children:[_?e.jsx(Oe,{className:"w-3 h-3"}):e.jsx(vt,{className:"w-3 h-3"}),_?`${c.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:(()=>s(t)),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${_?"bg-gray-900 text-white hover:bg-black":"bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{className:"w-3.5 h-3.5"}),_?"查看发货规则":"关联发货规则"]}),e.jsx(wt,{className:"w-3.5 h-3.5"})]})})]},`${t.cookie_id}-${t.item_id}`)}),Fe.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(_t,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),I?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),ee&&Le&&we.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",Le.item_id]})]}),e.jsx("button",{onClick:(()=>T(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ye,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:se.item_title||"",onChange:(t=>Ne({...se,item_title:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:se.item_price||"",onChange:(t=>Ne({...se,item_price:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:se.item_category||"",onChange:(t=>Ne({...se,item_category:t.target.value}))}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:se.item_description||"",onChange:(t=>Ne({...se,item_description:t.target.value}))})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:rt,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),P&&we.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),e.jsx("button",{onClick:(()=>ue(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ye,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"所属账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:J.cookie_id,onChange:(t=>pe({...J,cookie_id:t.target.value})),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(t=>e.jsx("option",{value:t.id,children:be(t.id)},t.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品 ID"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:J.item_id,onChange:(t=>pe({...J,item_id:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:J.item_price,onChange:(t=>pe({...J,item_price:t.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:J.item_title,onChange:(t=>pe({...J,item_title:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:J.item_image,onChange:(t=>pe({...J,item_image:t.target.value}))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:it,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),he&&we.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"820px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"发布商品到闲鱼"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。"})]}),e.jsx("button",{onClick:(()=>Ce(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ye,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6",children:"发布时必须填写库存。若账号没有库存发布能力,后端会返回明确的“库存权限不足”错误,不会误报为普通发布失败。"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:w.cookie_id,onChange:(t=>{V({...w,cookie_id:t.target.value}),tt([]),Ee(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(t=>e.jsx("option",{value:t.id,children:be(t.id)},t.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:会员月卡自动发货",value:w.title,onChange:(t=>V({...w,title:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"库存数量"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",type:"number",min:"1",placeholder:"必须大于 0",value:w.quantity,onChange:(t=>V({...w,quantity:t.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品描述"}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述会用于自动识别类目;留空时使用标题",value:w.description,onChange:(t=>V({...w,description:t.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"售价"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"99.00",value:w.price,onChange:(t=>V({...w,price:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"原价(可选)"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"129.00",value:w.original_price,onChange:(t=>V({...w,original_price:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"运费方式"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:w.postage_mode,onChange:(t=>V({...w,postage_mode:t.target.value})),children:[e.jsx("option",{value:"free",children:"包邮"}),e.jsx("option",{value:"distance",children:"按距离计费"}),e.jsx("option",{value:"fixed",children:"一口价邮费"}),e.jsx("option",{value:"none",children:"无需邮寄"})]})]})]}),w.postage_mode==="fixed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"一口价邮费"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 8.00",value:w.postage,onChange:(t=>V({...w,postage:t.target.value}))})]}),e.jsxs("div",{className:"rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。"})]}),e.jsxs("button",{type:"button",disabled:ie||!w.cookie_id,onClick:(()=>void Re(!1)),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(Ue,{className:"h-4 w-4"}),ie?"定位中...":"获取当前位置"]})]}),te.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,te.indexOf(st))),onChange:(t=>Ee(te[Number(t.target.value)]||null)),children:te.map((t,c)=>e.jsx("option",{value:String(c),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${c}`))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品图片(1-9 张)"}),e.jsxs("label",{className:"flex min-h-[120px] 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-emerald-300 hover:bg-emerald-50/50 transition-colors",children:[e.jsx(_e,{className:"w-8 h-8 text-emerald-600 mb-2"}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"选择图片"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:w.images.length?"已选择 "+w.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:(t=>V({...w,images:Array.from(t.target.files||[]).slice(0,9)}))})]}),Ae.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:Ae.map(t=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:t.url,alt:"",className:"w-full h-full object-cover"})},t.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:A,onClick:ct,className:"w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),A?"正在发布...":"发布到闲鱼"]})})]})}),document.body),E&&we.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"980px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量铺货"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。"})]}),e.jsx("button",{onClick:(()=>void h()),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(ye,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx(Zt,{phase:j}),j==="upload"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:"先下载模板,再按字段填写。"}),e.jsxs("div",{children:["图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 ",e.jsx("span",{className:"font-mono font-bold",children:"images/a.jpg;images/b.jpg"}),"。也支持直接填写图片 URL。"]})]}),e.jsx("button",{type:"button",onClick:ot,className:"shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700",children:"下载CSV模板"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"默认发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:k,onChange:(t=>{R(t.target.value),O([]),ae(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(t=>e.jsx("option",{value:t.id,children:be(t.id)},t.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-extrabold text-gray-900",children:["默认类目 ",e.jsx("span",{className:"font-medium text-gray-500",children:"(可为空)"})]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-amber-800",children:"填写后优先使用该类目;留空时由闲鱼根据每件商品自动识别。仍无法识别时,系统最终使用“电子资料”兜底。"})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs("label",{className:"relative flex-1",children:[e.jsx("span",{className:"sr-only",children:"类目关键词"}),e.jsx(ze,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3",placeholder:"输入关键词,例如:课程资料、设计素材",value:z,onChange:(t=>D(t.target.value)),onKeyDown:(t=>{t.key==="Enter"&&(t.preventDefault(),ne())})})]}),e.jsxs("button",{type:"button",disabled:!k||!z.trim()||Z,onClick:(()=>void ne()),className:"ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50",children:[e.jsx(ze,{className:"h-4 w-4"}),Z?"匹配中...":"获取类目"]})]}),C.catId?e.jsxs("div",{className:"flex min-h-[46px] items-center justify-between gap-3 border-t border-amber-200 pt-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold text-gray-900",children:[e.jsx(Oe,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:C.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",C.catId," · 频道 ",C.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:(()=>le({catId:"",catName:"",channelCatId:"",tbCatId:""})),className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",children:e.jsx(ye,{className:"h-4 w-4"})})]}):null]}),e.jsxs("div",{className:"rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"批次发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。"})]}),e.jsxs("button",{type:"button",disabled:ie||!k,onClick:(()=>void Re(!0)),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(Ue,{className:"h-4 w-4"}),ie?"定位中...":"获取当前位置"]})]}),m.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,m.indexOf(re))),onChange:(t=>ae(m[Number(t.target.value)]||null)),children:m.map((t,c)=>e.jsx("option",{value:String(c),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${c}`))})]}),e.jsx("div",{className:"rounded-xl border border-violet-200 bg-violet-50 p-4 space-y-2",children:e.jsxs("label",{className:"flex items-center justify-between gap-4",htmlFor:"batch-publish-interval",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-extrabold text-gray-900",children:"商品发布强制间隔"}),e.jsx("span",{className:"mt-1 block text-xs text-violet-800",children:"图片会提前上传,只有最终发布请求之间至少等待该时间。"})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("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:Q,onChange:(t=>K(Math.min(3600,Math.max(1,Number(t.target.value)||1))))}),e.jsx("span",{className:"text-sm font-bold text-violet-900",children:"秒"})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("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",children:[e.jsx(_e,{className:"w-9 h-9 text-blue-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传商品表格"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:S?S.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:(t=>{var c;return Y(((c=t.target.files)==null?void 0:c[0])||null)})})]}),e.jsxs("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-emerald-300 hover:bg-emerald-50 transition-colors",children:[e.jsx(_e,{className:"w-9 h-9 text-emerald-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传图片 zip(可选)"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:H?H.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:(t=>{var c;return X(((c=t.target.files)==null?void 0:c[0])||null)})})]})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"字段说明"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。"})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950",children:[e.jsx("div",{className:"text-sm font-extrabold",children:"“付款后发送的卡密”怎么填"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101"}),e.jsx("p",{className:"mt-1 leading-5",children:"从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:2"}),e.jsx("p",{className:"mt-1 leading-5",children:"每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:1:0;102:2:3"}),e.jsx("p",{className:"mt-1 leading-5",children:"先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。"})]})]}),e.jsxs("p",{className:"mt-3 leading-5 text-blue-800",children:["每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 ",e.jsx("code",{className:"font-bold",children:";"})," 隔开。"]})]}),e.jsx("div",{className:"overflow-x-auto rounded-xl border border-gray-100 bg-white",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"字段"}),e.jsx("th",{className:"px-3 py-2",children:"什么时候填写"}),e.jsx("th",{className:"px-3 py-2",children:"填写方法"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 text-gray-700",children:[["账号ID","需要覆盖默认账号时填写","上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行"],["标题","每个商品都要填","填写买家能看到的商品标题"],["描述","可以留空","留空时会使用商品标题作为描述"],["价格","每个商品都要填","只填数字,例如 19.90"],["原价","可以留空","需要展示划线原价时填写,例如 29.90"],["库存","可以留空","留空按 1 件处理;填写时必须大于 0"],["邮费模式","可以留空","留空表示包邮;包邮填 free,固定邮费填 fixed"],["邮费","邮费模式填 fixed 时填写","只填数字,例如 8.00"],["图片","每个商品都要填","填写 zip 内图片路径或图片网址;多张图片用英文分号隔开"],["类目ID","需要指定当前行默认类目时填写","必须和“类目名称、频道类目ID”同时填写;优先于自动识别"],["类目名称","填写了“类目ID”时必填","填写该 ID 对应的准确类目名称"],["频道类目ID","覆盖类目时必填","必须填写闲鱼返回的准确频道类目 ID"],["淘宝类目ID","按闲鱼返回填写","“电子资料”无淘宝类目 ID,保持为空"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([t,c,_])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:t}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${c==="每个商品都要填"?"text-red-600":c==="可以留空"?"text-gray-500":"text-amber-700"}`,children:c}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:_})]},t))})]})})]})]}),j==="preview"&&b&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总行数"}),e.jsx("div",{className:"text-2xl font-extrabold text-gray-900 mt-1",children:b.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"可发布"}),e.jsx("div",{className:"text-2xl font-extrabold text-emerald-700 mt-1",children:b.valid})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"有问题"}),e.jsx("div",{className:"text-2xl font-extrabold text-red-700 mt-1",children:b.invalid})]})]}),e.jsx("div",{className:"max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"价格/库存"}),e.jsx("th",{className:"px-4 py-3",children:"类目策略"}),e.jsx("th",{className:"px-4 py-3",children:"图片"}),e.jsx("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:b.rows.map(t=>{var c,_,ge,ce;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${t.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:t.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:t.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",t.price||"-"," / ",t.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((c=t.category)==null?void 0:c.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((_=t.category)==null?void 0:_.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((ge=t.images)==null?void 0:ge.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((ce=t.errors)==null?void 0:ce.join(";"))||"-"})]},t.row_no)})})]})})]}),(j==="running"||j==="done")&&y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`rounded-2xl p-4 border ${Ye(y.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:We(y.status)})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总数"}),e.jsx("div",{className:"text-xl font-extrabold text-gray-900 mt-1",children:y.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:y.success})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"失败"}),e.jsx("div",{className:"text-xl font-extrabold text-red-700 mt-1",children:y.failed})]}),e.jsxs("div",{className:"rounded-2xl bg-blue-50 p-4 border border-blue-100",children:[e.jsx("div",{className:"text-xs font-bold text-blue-700",children:"等待"}),e.jsx("div",{className:"text-xl font-extrabold text-blue-700 mt-1",children:y.pending})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"类目策略"}),e.jsx("th",{className:"px-4 py-3",children:"商品ID"}),e.jsx("th",{className:"px-4 py-3",children:"错误原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:y.rows.map(t=>{var c,_;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${Ye(t.status)}`,children:We(t.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:t.title}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((c=t.category)==null?void 0:c.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((_=t.category)==null?void 0:_.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:t.item_url?e.jsx("a",{href:t.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:t.item_id}):t.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:t.error_message||"-"})]},t.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[j==="upload"&&e.jsxs("button",{disabled:x||!S||!k,onClick:me,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Se,{className:`w-4 h-4 ${x?"animate-spin":""}`}),x?"正在预检...":"开始预检"]}),j==="preview"&&b&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:x,onClick:(()=>void i()),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"返回修改"}),e.jsxs("button",{disabled:x||b.valid<=0,onClick:ve,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Pe,{className:"w-4 h-4"}),x?"启动中...":`确认发布 ${b.valid} 个商品`]})]}),(j==="running"||j==="done")&&y&&e.jsxs("div",{className:"flex gap-3 w-full",children:[y.status==="running"?e.jsx("button",{disabled:x,onClick:l,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):y.status==="canceling"?e.jsx("button",{disabled:!0,className:"flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold",children:"正在保存远端结果并安全取消…"}):e.jsx("button",{onClick:(()=>window.open(`/api/v1/items/publish-batches/${y.id}/result.csv`,"_blank")),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"下载结果"}),y.retryable>0&&!["running","canceling"].includes(y.status)&&e.jsxs("button",{disabled:x,onClick:L,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Se,{className:`w-4 h-4 ${x?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(y.status)&&e.jsx("button",{onClick:(()=>{h(),M(),F()}),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"完成"})]})]})]})}),document.body)]})};export{ss as default}; diff --git a/internal/webui/static/assets/ItemList-CH6EVxKe.js b/internal/webui/static/assets/ItemList-CH6EVxKe.js deleted file mode 100644 index 63217c9..0000000 --- a/internal/webui/static/assets/ItemList-CH6EVxKe.js +++ /dev/null @@ -1,2 +0,0 @@ -import{j as e,a as r,b as we}from"./react-vendor-l-BBvuKH.js";import{g as je,c as Qe,b as ce,d as et,e as tt,A as yt,p as ft}from"./index-WrujSo30.js";import{a3 as jt,U as De,R as Se,N as Te,a4 as Pe,a5 as _e,V as vt,y as Nt,B as wt,a6 as Ue,a7 as _t,a8 as kt,A as Ct,d as It,X as be,o as St,a9 as ze,I as Oe}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const Ke="ydisks-amap-js-api",Pt="c9b68d4ce9a2a97f22a4a439404488ca";let ye=null;const Bt=()=>Pt,qt=()=>window.AMap?Promise.resolve(window.AMap):ye||(ye=new Promise((s,l)=>{const i=document.getElementById(Ke),m=i||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(R)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),l(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},R=window.setTimeout(()=>{u(),l(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,m.id=Ke,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Bt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),l(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},i||document.head.appendChild(m)}).catch(s=>{throw ye=null,s}),ye),ke=s=>Number.isFinite(s)&&s!==0,Lt=s=>{var u,f;const l=Number((u=s.location)==null?void 0:u.lng),i=Number((f=s.location)==null?void 0:f.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:l,latitude:i,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!ke(l)||!ke(i)||l<-180||l>180||i<-90||i>90?null:m},At=async(s,l,i={})=>{if(!ke(s)||!ke(l)||s<-180||s>180||l<-90||l>90)throw new Error("经纬度无效");const m=await qt();return new Promise((u,f)=>{var G,E;let R=!1;const k=Math.max(1,i.timeoutMs??1e4),A=M=>{var p;R||(R=!0,globalThis.clearTimeout(Z),(p=i.signal)==null||p.removeEventListener("abort",I),M())},I=()=>A(()=>f(new DOMException("aborted","AbortError"))),Z=globalThis.setTimeout(()=>A(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if((G=i.signal)!=null&&G.aborted){I();return}(E=i.signal)==null||E.addEventListener("abort",I,{once:!0}),new m.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,l],1e3,(M,p)=>{var d;if(R)return;if(M!=="complete"){if(M==="no_data"){A(()=>u([]));return}A(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const B=(((d=p==null?void 0:p.poiList)==null?void 0:d.pois)||[]).map(Lt).filter(j=>j!==null);A(()=>u(B))})})},Et=async s=>je("/api/v1/accounts/details",void 0,s),Je=async s=>je("/api/v1/automation-rules",void 0,s),Mt=(s,l,i)=>At(s,l,i),Be=(s,l)=>{if(s instanceof yt)switch(s.code){case"stock_permission_missing":return"发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。";case"conflict":case"item_conflict":return"商品状态已发生变化,请刷新后重试。";case"external_result_unknown":case"manual_review_required":return"平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。";case"retryable":case"temporarily_unavailable":return"平台暂时不可用,请稍后重试。";default:return s.message||l}if(s instanceof Error)return s.message;const i=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof i=="string"?i:l},qe=s=>s===!0||s===1||s==="1",Ze=async(s,l)=>{const i=await je("/api/v1/items",void 0,l);return Qe(i,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Rt=async s=>ce("/api/v1/items/get-all-from-account",{cookie_id:s}),Ft=async(s,l)=>tt(`/api/v1/items/${s}/${l}`),Gt=async(s,l)=>ce(`/api/v1/items/${s}`,l),$t=async s=>{const l=new FormData;l.set("cookie_id",s.cookie_id),l.set("title",s.title),l.set("description",s.description),l.set("price",s.price),l.set("original_price",s.original_price||""),l.set("quantity",String(s.quantity)),l.set("postage_mode",s.postage_mode),l.set("postage",s.postage||""),s.location&&l.set("location",JSON.stringify(s.location));for(const i of s.images)l.append("images",i);return et("/api/v1/items/publish",l)},Dt=async(s,l,i)=>ce("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:l},i),Tt=async(s,l)=>{const i=new FormData;return i.set("file",s.file),s.imagesZip&&i.set("images_zip",s.imagesZip),s.defaultCookieId&&i.set("default_cookie_id",s.defaultCookieId),i.set("fallback_category_id",s.fallbackCategory.catId),i.set("fallback_category_name",s.fallbackCategory.catName),i.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),i.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&i.set("location",JSON.stringify(s.location)),i.set("publish_interval_seconds",String(s.publishIntervalSeconds??5)),et("/api/v1/items/publish-batches/preview",i,l)},Ut=async(s,l)=>ce("/api/v1/items/publish-batches",{preview_id:s},l),ie=async(s,l)=>je(`/api/v1/items/publish-batches/${s}`,void 0,l),st=async(s=20,l)=>{const i=await je("/api/v1/items/publish-batches",{limit:s},l);return Qe(i,["batches","data","items"])},Ve=async(s,l)=>tt(`/api/v1/items/publish-batches/${s}`,void 0,l),zt=async(s,l)=>ce(`/api/v1/items/publish-batches/${s}/cancel`,{},l),Ot=async(s,l)=>ce(`/api/v1/items/publish-batches/${s}/retry-failed`,{},l),Kt=async(s,l,i)=>ft(`/api/v1/items/${s}/${l}`,i),Jt=s=>s.find(l=>l.status==="pending"||l.status==="running"||l.status==="canceling"),fe=s=>s==="pending"||s==="running"||s==="canceling",Zt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),Vt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!fe(s.status)),Wt=(s,l)=>s===l,We=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:return s||"-"}},Ye=s=>{switch(s){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Yt=({phase:s})=>{const l=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:l.map(([i,m])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===i?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:m},i))})},Ht=s=>{const[l,i]=r.useState(!1),[m,u]=r.useState("upload"),[f,R]=r.useState(null),[k,A]=r.useState(null),[I,Z]=r.useState(""),[T,G]=r.useState(!1),[E,M]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[p,B]=r.useState(null),[d,j]=r.useState(null),[S,V]=r.useState(null),[W,Y]=r.useState([]),[U,$]=r.useState(null),[K,C]=r.useState(5),[se,g]=r.useState(!1),y=r.useRef(0),b=r.useRef(null),v=r.useCallback(()=>{var h;(h=b.current)==null||h.abort();const a=new AbortController;b.current=a;const n=++y.current;return{controller:a,requestGeneration:n}},[]),x=r.useCallback((a,n)=>a===y.current&&n===b.current&&!n.signal.aborted,[]);r.useEffect(()=>(()=>{var a;(a=b.current)==null||a.abort(),y.current+=1}),[]);const ae=r.useCallback(async()=>{const a=v();u("upload"),B(null),j(null),R(null),A(null),Z(""),M({catId:"",catName:"",channelCatId:"",tbCatId:""}),Y([]),$(null),C(5),i(!0),g(!0);try{const n=await st(20,{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;const h=Jt(n);if(h!=null&&h.id){const q=await ie(h.id,{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;V(q),j(q),C(q.publish_interval_seconds||5),u(fe(q.status)?"running":"done")}}catch(n){if(!x(a.requestGeneration,a.controller))return;console.error("恢复最近批量铺货任务失败:",n)}finally{x(a.requestGeneration,a.controller)&&g(!1)}},[v,x]),H=r.useCallback(async()=>{const a=I.trim();if(!s.selectedAccount){alert("请先选择默认发布账号");return}if(!a){alert("请输入类目关键词");return}const n=v();G(!0);try{const h=await Dt(s.selectedAccount,a,{signal:n.controller.signal});if(!x(n.requestGeneration,n.controller))return;const q=h.category;M({catId:q.cat_id,catName:q.cat_name,channelCatId:q.channel_cat_id,tbCatId:q.tb_cat_id||""})}catch(h){if(!x(n.requestGeneration,n.controller))return;console.error("获取推荐类目失败:",h),alert((h==null?void 0:h.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{x(n.requestGeneration,n.controller)&&G(!1)}},[I,v,x,s.selectedAccount]),z=r.useCallback(async()=>{if(!(S!=null&&S.id))return;const a=v();g(!0),i(!0);try{const n=await ie(S.id,{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;j(n),C(n.publish_interval_seconds||5),u(fe(n.status)?"running":"done")}catch(n){if(!x(a.requestGeneration,a.controller))return;console.error("加载最近批量铺货结果失败:",n)}finally{x(a.requestGeneration,a.controller)&&g(!1)}},[v,x,S==null?void 0:S.id]),D=r.useCallback(async()=>{if(!f){alert("请先上传商品表格");return}if(!s.selectedAccount){alert("请先选择默认发布账号");return}const a=v();g(!0);try{const n=await Tt({file:f,imagesZip:k,defaultCookieId:s.selectedAccount,fallbackCategory:E,location:U||void 0,publishIntervalSeconds:K},{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;B(n),j(null),u("preview")}catch(n){if(!x(a.requestGeneration,a.controller))return;console.error("批量铺货预检失败:",n),alert((n==null?void 0:n.message)||"预检失败,请检查表格和图片 zip")}finally{x(a.requestGeneration,a.controller)&&g(!1)}},[E,f,k,U,K,v,x,s.selectedAccount]),te=r.useCallback(async()=>{if(!(p!=null&&p.preview_id))return;if(!Zt(p)){alert("没有可发布的商品行");return}const a=v();g(!0);try{const n=await Ut(p.preview_id,{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;const h=await ie(n.batch_id||p.preview_id,{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;j(h),V(h),u(h.status==="running"?"running":"done")}catch(n){if(!x(a.requestGeneration,a.controller))return;console.error("启动批量铺货失败:",n),alert((n==null?void 0:n.message)||"启动发布任务失败")}finally{x(a.requestGeneration,a.controller)&&g(!1)}},[p,v,x]),oe=r.useCallback(async()=>{if(!(d!=null&&d.id)||!confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。"))return;const a=v();g(!0);try{const n=await zt(d.id,{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;const h=await ie(d.id,{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;j(h),u((n==null?void 0:n.status)==="canceling"||h.status==="canceling"?"running":"done")}catch(n){if(!x(a.requestGeneration,a.controller))return;alert((n==null?void 0:n.message)||"取消失败")}finally{x(a.requestGeneration,a.controller)&&g(!1)}},[d==null?void 0:d.id,v,x]),le=r.useCallback(async()=>{const a=p==null?void 0:p.preview_id,n=v();if(a&&m==="preview")try{await Ve(a,{signal:n.controller.signal})}catch(h){if(!x(n.requestGeneration,n.controller))return;console.error("清理批量铺货预检失败:",h)}x(n.requestGeneration,n.controller)&&(B(null),u("upload"))},[m,p==null?void 0:p.preview_id,v,x]),de=r.useCallback(async()=>{var n;const a=p==null?void 0:p.preview_id;if((n=b.current)==null||n.abort(),y.current+=1,B(null),u("upload"),i(!1),a&&m==="preview")try{await Ve(a)}catch(h){console.error("关闭批量铺货弹窗时清理预检失败:",h)}},[m,p==null?void 0:p.preview_id]),xe=r.useCallback(async()=>{if(!(d!=null&&d.id)||!Vt(d))return;const a=v();g(!0);try{if(await Ot(d.id,{signal:a.controller.signal}),!x(a.requestGeneration,a.controller))return;const n=await ie(d.id,{signal:a.controller.signal});if(!x(a.requestGeneration,a.controller))return;j(n),u("running")}catch(n){if(!x(a.requestGeneration,a.controller))return;alert((n==null?void 0:n.message)||"重试失败")}finally{x(a.requestGeneration,a.controller)&&g(!1)}},[d,v,x]);return r.useEffect(()=>{if(!l||!(d!=null&&d.id)||!fe(d.status))return;const a=++y.current,n=new AbortController;let h=!1;const q=async()=>{if(!(h||n.signal.aborted)){h=!0;try{const N=await ie(d.id,{signal:n.signal});if(!Wt(a,y.current))return;j(N),V(N),fe(N.status)||(u("done"),await Promise.all([s.loadItems(),s.loadShippingRules()]))}catch(N){n.signal.aborted||console.error("刷新批量铺货进度失败:",N)}finally{h=!1}}},o=window.setInterval(()=>void q(),3e3);return(()=>{window.clearInterval(o),n.abort(),y.current+=1})},[d==null?void 0:d.id,d==null?void 0:d.status,s.loadItems,s.loadShippingRules,l]),{showBatchModal:l,setShowBatchModal:i,batchLoading:se,batchPhase:m,setBatchPhase:u,batchFile:f,setBatchFile:R,batchImagesZip:k,setBatchImagesZip:A,batchCategoryKeyword:I,setBatchCategoryKeyword:Z,batchCategoryLoading:T,batchFallbackCategory:E,setBatchFallbackCategory:M,batchPreview:p,setBatchPreview:B,batchDetail:d,setBatchDetail:j,recentBatch:S,setRecentBatch:V,batchLocations:W,batchLocation:U,setBatchLocations:Y,setBatchLocation:$,batchPublishIntervalSeconds:K,setBatchPublishIntervalSeconds:C,openBatchModal:ae,handleRecommendBatchCategory:H,openRecentBatchResult:z,handlePreviewBatch:D,handleStartBatch:te,handleCancelBatch:oe,abandonBatchPreview:le,closeBatchModal:de,handleRetryBatchFailed:xe}},He=()=>({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),Xe=(s="")=>({cookie_id:s,title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),Xt=({selectedAccount:s,setSelectedAccount:l,setItems:i,loadItems:m,loadShippingRules:u,onConfigureDelivery:f,setBatchLocations:R,setBatchLocation:k})=>{const[A,I]=r.useState(!1),[Z,T]=r.useState(!1),[G,E]=r.useState(!1),[M,p]=r.useState(!1),[B,d]=r.useState(!1),[j,S]=r.useState(!1),[V,W]=r.useState([]),[Y,U]=r.useState(null),[$,K]=r.useState(null),[C,se]=r.useState({}),[g,y]=r.useState(He),[b,v]=r.useState(Xe),[x,ae]=r.useState([]),H=r.useRef(null),z=r.useRef(0);r.useEffect(()=>{if(!B||b.images.length===0){ae([]);return}const o=b.images.map((N,L)=>({key:N.name+L,url:URL.createObjectURL(N)}));return ae(o),(()=>o.forEach(N=>URL.revokeObjectURL(N.url)))},[b.images,B]);const D=r.useCallback(()=>{var o;(o=H.current)==null||o.abort(),H.current=null,z.current+=1,S(!1)},[]);r.useEffect(()=>D,[D]),r.useEffect(()=>{B||D()},[D,B]);const te=r.useCallback(async()=>{if(!s)return alert("请先选择账号");I(!0);try{const o=await Rt(s);await m(),alert((o==null?void 0:o.message)||"商品同步完成")}catch(o){console.error("同步商品失败:",o),alert(Be(o,"同步失败,请重试"))}finally{I(!1)}},[m,s]),oe=r.useCallback(o=>{K(o),se({...o}),E(!0)},[]),le=r.useCallback(async()=>{if($)try{await Kt($.cookie_id,$.item_id,{item_title:C.item_title||"",item_description:C.item_description||"",item_category:C.item_category||"",item_price:C.item_price||"",item_detail:C.item_detail||$.item_detail||""}),await m(),await u(),E(!1),K(null)}catch(o){console.error("更新商品失败:",o),alert("更新失败,请重试")}},[C,m,u,$]),de=r.useCallback(async o=>{if(confirm(`确认删除商品"${o.item_title}"吗?`))try{await Ft(o.cookie_id,o.item_id),i(N=>N.filter(L=>!(L.cookie_id===o.cookie_id&&L.item_id===o.item_id)))}catch(N){console.error("删除商品失败:",N),alert("删除失败,请重试")}},[i]),xe=r.useCallback(async()=>{try{if(!g.cookie_id||!g.item_id){alert("请选择账号并填写商品ID");return}await Gt(g.cookie_id,{item_id:g.item_id,item_title:g.item_title,item_price:g.item_price,item_detail:g.item_image?JSON.stringify({item_image:g.item_image}):""}),await m(),p(!1),y(He())}catch(o){console.error("添加商品失败:",o),alert("添加失败,请重试")}},[g,m]),ve=r.useCallback(async()=>{if(!b.cookie_id)return alert("请选择发布账号");if(!b.title.trim())return alert("请填写商品标题");if(!b.price.trim())return alert("请填写商品价格");if(!b.quantity||Number(b.quantity)<=0)return alert("库存数量必须大于 0");if(b.images.length===0)return alert("至少上传 1 张商品图片");if(b.postage_mode==="fixed"&&!b.postage.trim())return alert("请填写一口价邮费");T(!0);try{const o=await $t({...b,location:Y||void 0});if(await m(),d(!1),v(Xe(s||"")),W([]),U(null),o!=null&&o.item_id){const N={id:o.item_id,cookie_id:b.cookie_id,item_id:o.item_id,item_title:o.item_title||b.title,item_price:o.item_price||b.price,item_image:o.item_image};f(N),alert("商品发布成功,ID: "+o.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(o){console.error("发布商品失败:",o),alert(Be(o,"发布失败,请重试"))}finally{T(!1)}},[m,f,b,Y,s]),a=r.useCallback(()=>{const L=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","类目ID","类目名称","频道类目ID","淘宝类目ID","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","","","","","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","","","","","否","","否","","否","","",""]]].map(ue=>ue.map(me=>`"${String(me).replace(/"/g,'""')}"`).join(",")).join(` -`),X=new Blob(["\uFEFF"+L],{type:"text/csv;charset=utf-8"}),F=URL.createObjectURL(X),P=document.createElement("a");P.href=F,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(F)},[]),n=r.useCallback(()=>{y(o=>({...o,cookie_id:s||o.cookie_id})),p(!0)},[s]),h=r.useCallback(()=>{v(o=>({...o,cookie_id:s||o.cookie_id})),d(!0)},[s]),q=r.useCallback(async o=>{if(!(o?s:b.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");D();const L=new AbortController;H.current=L;const X=++z.current;S(!0);try{const F=await new Promise((ue,me)=>{const Ce=Q=>ue(Q),re=Q=>me(Q);navigator.geolocation.getCurrentPosition(Ce,re,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(L.signal.aborted||X!==z.current)return;const P=await Mt(F.coords.longitude,F.coords.latitude,{signal:L.signal});if(L.signal.aborted||X!==z.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(R(P),k(P[0])):(W(P),U(P[0]))}catch(F){if(L.signal.aborted||X!==z.current)return;if(typeof F=="object"&&F!==null&&"code"in F){const P=F;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(Be(F,"获取发货地失败"))}finally{X===z.current&&(H.current=null,S(!1))}},[D,b.cookie_id,s,k,R]);return{selectedAccount:s,setSelectedAccount:l,loading:A,publishing:Z,showEditModal:G,setShowEditModal:E,showAddModal:M,setShowAddModal:p,showPublishModal:B,setShowPublishModal:d,locationLoading:j,publishLocations:V,setPublishLocations:W,publishLocation:Y,setPublishLocation:U,selectedItem:$,editForm:C,setEditForm:se,addForm:g,setAddForm:y,publishForm:b,setPublishForm:v,publishImagePreviews:x,handleSync:te,handleEdit:oe,handleSaveEdit:le,handleDelete:de,handleAddItem:xe,handlePublishItem:ve,downloadPublishTemplate:a,openAddModal:n,openPublishModal:h,locateForPublish:q}},Qt=s=>{const l=String(s||"").trim();return l?/^[¥¥]/.test(l)?l:`¥${l}`:"-"},ls=({onConfigureDelivery:s})=>{const[l,i]=r.useState([]),[m,u]=r.useState([]),[f,R]=r.useState([]),[k,A]=r.useState(""),[I,Z]=r.useState(""),T=r.useRef(0),G=r.useRef(0),E=r.useCallback(async()=>{const t=++T.current,c=await Ze();t===T.current&&i(c)},[]),M=r.useCallback(async()=>{const t=++G.current,c=await Je();t===G.current&&u(c)},[]),p=Ht({selectedAccount:k,loadItems:E,loadShippingRules:M}),{showBatchModal:B,batchLoading:d,batchPhase:j,batchFile:S,setBatchFile:V,batchImagesZip:W,setBatchImagesZip:Y,batchCategoryKeyword:U,setBatchCategoryKeyword:$,batchCategoryLoading:K,batchFallbackCategory:C,setBatchFallbackCategory:se,batchPreview:g,batchDetail:y,recentBatch:b,setRecentBatch:v,batchLocations:x,batchLocation:ae,batchPublishIntervalSeconds:H,setBatchPublishIntervalSeconds:z,setBatchLocations:D,setBatchLocation:te,openBatchModal:oe,handleRecommendBatchCategory:le,openRecentBatchResult:de,handlePreviewBatch:xe,handleStartBatch:ve,handleCancelBatch:a,abandonBatchPreview:n,closeBatchModal:h,handleRetryBatchFailed:q}=p,o=Xt({selectedAccount:k,setSelectedAccount:A,setItems:i,loadItems:E,loadShippingRules:M,onConfigureDelivery:s,setBatchLocations:D,setBatchLocation:te}),{loading:N,publishing:L,showEditModal:X,setShowEditModal:F,showAddModal:P,setShowAddModal:ue,showPublishModal:me,setShowPublishModal:Ce,locationLoading:re,publishLocations:Q,setPublishLocations:at,publishLocation:lt,setPublishLocation:Le,selectedItem:Ae,editForm:ee,setEditForm:Ne,addForm:O,setAddForm:he,publishForm:w,setPublishForm:J,publishImagePreviews:Ee,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:ut,openPublishModal:mt,locateForPublish:Me}=o;r.useEffect(()=>{const t=new AbortController,c=++T.current,_=++G.current;let ge=!0;return Promise.all([Et({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),st(20,{signal:t.signal})]).then(([ne,pt,gt,$e])=>{if(!ge||t.signal.aborted||c!==T.current||_!==G.current)return;R(ne),i(pt),u(gt);const bt=$e.find(Ie=>["running","canceling"].includes(Ie.status))||$e.find(Ie=>Ie.status!=="preview");v(bt||null)}).catch(ne=>{t.signal.aborted||console.error("加载商品配置失败:",ne)}),(()=>{ge=!1,t.abort()})},[]);const ht=t=>m.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id).length>0?m.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id):m.filter(c=>c.cookie_id===t.cookie_id&&!c.item_id),Re=r.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=r.useMemo(()=>I?l.filter(t=>t.cookie_id===I):l,[I,l]),pe=t=>{const c=Re.get(t),_=(c==null?void 0:c.remark)||(c==null?void 0:c.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Ge=t=>{const c=Re.get(t);return(c==null?void 0:c.remark)||(c==null?void 0:c.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(jt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:(t=>Z(t.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),f.map(t=>e.jsx("option",{value:t.id,children:pe(t.id)},t.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(De,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:k,onChange:(t=>A(t.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),f.map(t=>e.jsx("option",{value:t.id,children:pe(t.id)},t.id))]})]})]}),e.jsxs("button",{onClick:rt,disabled:N||!k,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Se,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ut,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Te,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:mt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Pe,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void oe()),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(_e,{className:"w-4 h-4"}),b&&["running","canceling"].includes(b.status)?"继续批量任务":"批量铺货"]}),b&&!["running","canceling"].includes(b.status)&&e.jsx("button",{onClick:(()=>void de()),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Fe.map(t=>{const c=ht(t),_=c.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:(()=>nt(t)),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors",title:"编辑",children:e.jsx(vt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:(()=>ct(t)),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[t.item_image?e.jsx("img",{src:t.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(wt,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:Qt(t.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:t.item_title}),e.jsxs("div",{className:"mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:Ge(t.cookie_id),children:[e.jsx(De,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:Ge(t.cookie_id)})]}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",t.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${_?"text-emerald-600":"text-amber-600"}`,children:[_?e.jsx(Ue,{className:"w-3 h-3"}):e.jsx(_t,{className:"w-3 h-3"}),_?`${c.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:(()=>s(t)),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${_?"bg-gray-900 text-white hover:bg-black":"bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(kt,{className:"w-3.5 h-3.5"}),_?"查看发货规则":"关联发货规则"]}),e.jsx(Ct,{className:"w-3.5 h-3.5"})]})})]},`${t.cookie_id}-${t.item_id}`)}),Fe.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(It,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),I?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),X&&Ae&&we.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",Ae.item_id]})]}),e.jsx("button",{onClick:(()=>F(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(be,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:ee.item_title||"",onChange:(t=>Ne({...ee,item_title:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:ee.item_price||"",onChange:(t=>Ne({...ee,item_price:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:ee.item_category||"",onChange:(t=>Ne({...ee,item_category:t.target.value}))}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:ee.item_description||"",onChange:(t=>Ne({...ee,item_description:t.target.value}))})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:it,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(St,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),P&&we.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),e.jsx("button",{onClick:(()=>ue(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(be,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"所属账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:O.cookie_id,onChange:(t=>he({...O,cookie_id:t.target.value})),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(t=>e.jsx("option",{value:t.id,children:pe(t.id)},t.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品 ID"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:O.item_id,onChange:(t=>he({...O,item_id:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:O.item_price,onChange:(t=>he({...O,item_price:t.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:O.item_title,onChange:(t=>he({...O,item_title:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:O.item_image,onChange:(t=>he({...O,item_image:t.target.value}))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:ot,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Te,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),me&&we.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"820px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"发布商品到闲鱼"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。"})]}),e.jsx("button",{onClick:(()=>Ce(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(be,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6",children:"发布时必须填写库存。若账号没有库存发布能力,后端会返回明确的“库存权限不足”错误,不会误报为普通发布失败。"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:w.cookie_id,onChange:(t=>{J({...w,cookie_id:t.target.value}),at([]),Le(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(t=>e.jsx("option",{value:t.id,children:pe(t.id)},t.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:会员月卡自动发货",value:w.title,onChange:(t=>J({...w,title:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"库存数量"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",type:"number",min:"1",placeholder:"必须大于 0",value:w.quantity,onChange:(t=>J({...w,quantity:t.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品描述"}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述会用于自动识别类目;留空时使用标题",value:w.description,onChange:(t=>J({...w,description:t.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"售价"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"99.00",value:w.price,onChange:(t=>J({...w,price:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"原价(可选)"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"129.00",value:w.original_price,onChange:(t=>J({...w,original_price:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"运费方式"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:w.postage_mode,onChange:(t=>J({...w,postage_mode:t.target.value})),children:[e.jsx("option",{value:"free",children:"包邮"}),e.jsx("option",{value:"distance",children:"按距离计费"}),e.jsx("option",{value:"fixed",children:"一口价邮费"}),e.jsx("option",{value:"none",children:"无需邮寄"})]})]})]}),w.postage_mode==="fixed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"一口价邮费"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 8.00",value:w.postage,onChange:(t=>J({...w,postage:t.target.value}))})]}),e.jsxs("div",{className:"rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。"})]}),e.jsxs("button",{type:"button",disabled:re||!w.cookie_id,onClick:(()=>void Me(!1)),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(ze,{className:"h-4 w-4"}),re?"定位中...":"获取当前位置"]})]}),Q.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,Q.indexOf(lt))),onChange:(t=>Le(Q[Number(t.target.value)]||null)),children:Q.map((t,c)=>e.jsx("option",{value:String(c),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${c}`))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品图片(1-9 张)"}),e.jsxs("label",{className:"flex min-h-[120px] 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-emerald-300 hover:bg-emerald-50/50 transition-colors",children:[e.jsx(_e,{className:"w-8 h-8 text-emerald-600 mb-2"}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"选择图片"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:w.images.length?"已选择 "+w.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:(t=>J({...w,images:Array.from(t.target.files||[]).slice(0,9)}))})]}),Ee.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:Ee.map(t=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:t.url,alt:"",className:"w-full h-full object-cover"})},t.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:L,onClick:dt,className:"w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),L?"正在发布...":"发布到闲鱼"]})})]})}),document.body),B&&we.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"980px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量铺货"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。"})]}),e.jsx("button",{onClick:(()=>void h()),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(be,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx(Yt,{phase:j}),j==="upload"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:"先下载模板,再按字段填写。"}),e.jsxs("div",{children:["图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 ",e.jsx("span",{className:"font-mono font-bold",children:"images/a.jpg;images/b.jpg"}),"。也支持直接填写图片 URL。"]})]}),e.jsx("button",{type:"button",onClick:xt,className:"shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700",children:"下载CSV模板"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"默认发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:k,onChange:(t=>{A(t.target.value),D([]),te(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(t=>e.jsx("option",{value:t.id,children:pe(t.id)},t.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-extrabold text-gray-900",children:["默认类目 ",e.jsx("span",{className:"font-medium text-gray-500",children:"(可为空)"})]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-amber-800",children:"填写后优先使用该类目;留空时由闲鱼根据每件商品自动识别。仍无法识别时,系统最终使用“电子资料”兜底。"})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs("label",{className:"relative flex-1",children:[e.jsx("span",{className:"sr-only",children:"类目关键词"}),e.jsx(Oe,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3",placeholder:"输入关键词,例如:课程资料、设计素材",value:U,onChange:(t=>$(t.target.value)),onKeyDown:(t=>{t.key==="Enter"&&(t.preventDefault(),le())})})]}),e.jsxs("button",{type:"button",disabled:!k||!U.trim()||K,onClick:(()=>void le()),className:"ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50",children:[e.jsx(Oe,{className:"h-4 w-4"}),K?"匹配中...":"获取类目"]})]}),C.catId?e.jsxs("div",{className:"flex min-h-[46px] items-center justify-between gap-3 border-t border-amber-200 pt-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold text-gray-900",children:[e.jsx(Ue,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:C.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",C.catId," · 频道 ",C.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:(()=>se({catId:"",catName:"",channelCatId:"",tbCatId:""})),className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",children:e.jsx(be,{className:"h-4 w-4"})})]}):null]}),e.jsxs("div",{className:"rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"批次发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。"})]}),e.jsxs("button",{type:"button",disabled:re||!k,onClick:(()=>void Me(!0)),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(ze,{className:"h-4 w-4"}),re?"定位中...":"获取当前位置"]})]}),x.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,x.indexOf(ae))),onChange:(t=>te(x[Number(t.target.value)]||null)),children:x.map((t,c)=>e.jsx("option",{value:String(c),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${c}`))})]}),e.jsx("div",{className:"rounded-xl border border-violet-200 bg-violet-50 p-4 space-y-2",children:e.jsxs("label",{className:"flex items-center justify-between gap-4",htmlFor:"batch-publish-interval",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-extrabold text-gray-900",children:"商品发布强制间隔"}),e.jsx("span",{className:"mt-1 block text-xs text-violet-800",children:"图片会提前上传,只有最终发布请求之间至少等待该时间。"})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("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:H,onChange:(t=>z(Math.min(3600,Math.max(1,Number(t.target.value)||1))))}),e.jsx("span",{className:"text-sm font-bold text-violet-900",children:"秒"})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("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",children:[e.jsx(_e,{className:"w-9 h-9 text-blue-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传商品表格"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:S?S.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:(t=>{var c;return V(((c=t.target.files)==null?void 0:c[0])||null)})})]}),e.jsxs("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-emerald-300 hover:bg-emerald-50 transition-colors",children:[e.jsx(_e,{className:"w-9 h-9 text-emerald-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传图片 zip(可选)"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:W?W.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:(t=>{var c;return Y(((c=t.target.files)==null?void 0:c[0])||null)})})]})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"字段说明"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。"})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950",children:[e.jsx("div",{className:"text-sm font-extrabold",children:"“付款后发送的卡密”怎么填"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101"}),e.jsx("p",{className:"mt-1 leading-5",children:"从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:2"}),e.jsx("p",{className:"mt-1 leading-5",children:"每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:1:0;102:2:3"}),e.jsx("p",{className:"mt-1 leading-5",children:"先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。"})]})]}),e.jsxs("p",{className:"mt-3 leading-5 text-blue-800",children:["每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 ",e.jsx("code",{className:"font-bold",children:";"})," 隔开。"]})]}),e.jsx("div",{className:"overflow-x-auto rounded-xl border border-gray-100 bg-white",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"字段"}),e.jsx("th",{className:"px-3 py-2",children:"什么时候填写"}),e.jsx("th",{className:"px-3 py-2",children:"填写方法"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 text-gray-700",children:[["账号ID","需要覆盖默认账号时填写","上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行"],["标题","每个商品都要填","填写买家能看到的商品标题"],["描述","可以留空","留空时会使用商品标题作为描述"],["价格","每个商品都要填","只填数字,例如 19.90"],["原价","可以留空","需要展示划线原价时填写,例如 29.90"],["库存","可以留空","留空按 1 件处理;填写时必须大于 0"],["邮费模式","可以留空","留空表示包邮;包邮填 free,固定邮费填 fixed"],["邮费","邮费模式填 fixed 时填写","只填数字,例如 8.00"],["图片","每个商品都要填","填写 zip 内图片路径或图片网址;多张图片用英文分号隔开"],["类目ID","需要指定当前行默认类目时填写","必须和“类目名称、频道类目ID”同时填写;优先于自动识别"],["类目名称","填写了“类目ID”时必填","填写该 ID 对应的准确类目名称"],["频道类目ID","覆盖类目时必填","必须填写闲鱼返回的准确频道类目 ID"],["淘宝类目ID","按闲鱼返回填写","“电子资料”无淘宝类目 ID,保持为空"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([t,c,_])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:t}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${c==="每个商品都要填"?"text-red-600":c==="可以留空"?"text-gray-500":"text-amber-700"}`,children:c}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:_})]},t))})]})})]})]}),j==="preview"&&g&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总行数"}),e.jsx("div",{className:"text-2xl font-extrabold text-gray-900 mt-1",children:g.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"可发布"}),e.jsx("div",{className:"text-2xl font-extrabold text-emerald-700 mt-1",children:g.valid})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"有问题"}),e.jsx("div",{className:"text-2xl font-extrabold text-red-700 mt-1",children:g.invalid})]})]}),e.jsx("div",{className:"max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"价格/库存"}),e.jsx("th",{className:"px-4 py-3",children:"类目策略"}),e.jsx("th",{className:"px-4 py-3",children:"图片"}),e.jsx("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:g.rows.map(t=>{var c,_,ge,ne;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${t.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:t.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:t.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",t.price||"-"," / ",t.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((c=t.category)==null?void 0:c.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((_=t.category)==null?void 0:_.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((ge=t.images)==null?void 0:ge.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((ne=t.errors)==null?void 0:ne.join(";"))||"-"})]},t.row_no)})})]})})]}),(j==="running"||j==="done")&&y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`rounded-2xl p-4 border ${Ye(y.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:We(y.status)})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总数"}),e.jsx("div",{className:"text-xl font-extrabold text-gray-900 mt-1",children:y.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:y.success})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"失败"}),e.jsx("div",{className:"text-xl font-extrabold text-red-700 mt-1",children:y.failed})]}),e.jsxs("div",{className:"rounded-2xl bg-blue-50 p-4 border border-blue-100",children:[e.jsx("div",{className:"text-xs font-bold text-blue-700",children:"等待"}),e.jsx("div",{className:"text-xl font-extrabold text-blue-700 mt-1",children:y.pending})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"类目策略"}),e.jsx("th",{className:"px-4 py-3",children:"商品ID"}),e.jsx("th",{className:"px-4 py-3",children:"错误原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:y.rows.map(t=>{var c,_;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${Ye(t.status)}`,children:We(t.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:t.title}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((c=t.category)==null?void 0:c.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((_=t.category)==null?void 0:_.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:t.item_url?e.jsx("a",{href:t.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:t.item_id}):t.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:t.error_message||"-"})]},t.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[j==="upload"&&e.jsxs("button",{disabled:d||!S||!k,onClick:xe,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Se,{className:`w-4 h-4 ${d?"animate-spin":""}`}),d?"正在预检...":"开始预检"]}),j==="preview"&&g&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:d,onClick:(()=>void n()),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"返回修改"}),e.jsxs("button",{disabled:d||g.valid<=0,onClick:ve,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Pe,{className:"w-4 h-4"}),d?"启动中...":`确认发布 ${g.valid} 个商品`]})]}),(j==="running"||j==="done")&&y&&e.jsxs("div",{className:"flex gap-3 w-full",children:[y.status==="running"?e.jsx("button",{disabled:d,onClick:a,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):y.status==="canceling"?e.jsx("button",{disabled:!0,className:"flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold",children:"正在保存远端结果并安全取消…"}):e.jsx("button",{onClick:(()=>window.open(`/api/v1/items/publish-batches/${y.id}/result.csv`,"_blank")),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"下载结果"}),y.retryable>0&&!["running","canceling"].includes(y.status)&&e.jsxs("button",{disabled:d,onClick:q,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Se,{className:`w-4 h-4 ${d?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(y.status)&&e.jsx("button",{onClick:(()=>{h(),E(),M()}),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"完成"})]})]})]})}),document.body)]})};export{ls as default}; diff --git a/internal/webui/static/assets/Notifications-BCUsqoS1.js b/internal/webui/static/assets/Notifications-BCUsqoS1.js new file mode 100644 index 0000000..eef4f4d --- /dev/null +++ b/internal/webui/static/assets/Notifications-BCUsqoS1.js @@ -0,0 +1 @@ +import{j as e,b as _e,a as d}from"./react-vendor-l-BBvuKH.js";import{ai as te,ah as ae,aj as je,u as Q,e as I,L as z,w as Ne,y as ve,t as V,X as ne,z as re,F as le,o as we,R as ke,N as Se}from"./icons-vendor-Bgrth_9N.js";import{r as R,c as B}from"./index-CiBUw4Te.js";import"./vendor-cRYyTeIw.js";const Y=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],H=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},oe=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=Y.some(r=>String(s[r]??"").trim()!=="");return{...s,use_custom_smtp:t?H(s.use_custom_smtp,!1):a}},ie=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const r of Y)String(a[r]??"").trim()===""&&t[r]!==void 0&&(a[r]=t[r]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=H(a.smtp_use_tls,!0),a.smtp_use_ssl=H(a.smtp_use_ssl,!1),a},ce=s=>{const t=oe(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const r of Y)a[r]=t[r];return a},F={bark:{label:"Bark",icon:I,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:je,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:ae,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:te,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},de=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],ee=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Ce=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=de.find(r=>r.value===t))==null?void 0:a.label)||t}).join("、"),Te=(s,t)=>{const a=s.type==="email"?oe({...s.config||{}}):null,r=a?a.use_custom_smtp===!0?ie(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:r,event_types:s.event_types||[]}},Pe=s=>{const a=F[s.type].fields.find(r=>r.required&&!String(s.config[r.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!s.name.trim())return"请填写渠道名称";if(s.type==="email"){const r=ce(s.config);if(r.use_custom_smtp){const w=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([b])=>!String(r[b]||"").trim());if(w)return`请填写 ${w[1]}`}}return""},Ee=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?ce(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),g=(s,t)=>s===t,D=(s,t)=>s instanceof Error&&s.message?s.message:t,Me=({channels:s,testingId:t,onEdit:a,onDelete:r,onToggleEnabled:h,onTest:w})=>{const b=l=>s.find(o=>o.id===l.currentTarget.dataset.channelId)||null,j=l=>{const o=b(l);o&&h(o)},S=l=>{const o=b(l);o&&w(o)},E=l=>{const o=b(l);o&&a(o)},_=l=>{const o=b(l);o&&r(o)},M=l=>{const o=F[l.type]||F.webhook,P=o.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(P,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:l.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:o.label}),!l.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:o.fields.map(x=>{var k;return(k=l.config)==null?void 0:k[x.key]}).filter(Boolean).map((x,k)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},k))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Ce(l.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":l.id,onClick:j,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${l.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:l.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":l.id,onClick:S,disabled:t===l.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[t===l.id?e.jsx(z,{className:"w-3 h-3 animate-spin"}):e.jsx(ae,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":l.id,onClick:E,className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(Ne,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":l.id,onClick:_,className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(ve,{className:"w-4 h-4"})})]})]},l.id)};return s.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(I,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:s.map(M)})},qe=({selectedEvents:s,onToggleEvent:t})=>{const a=r=>{const h=r.currentTarget.dataset.event;h&&t(h)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:de.map(r=>{const h=s.includes(r.value);return e.jsxs("button",{type:"button","data-event":r.value,onClick:a,className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${h?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${h?"bg-brand border-brand":"border-gray-300"}`,children:h&&e.jsx(V,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${h?"text-brand":"text-gray-800"}`,children:r.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:r.description})]},r.value)})})]})},Le=({showModal:s,editing:t,form:a,setForm:r,smtp:h,showChannelSmtpPassword:w,setShowChannelSmtpPassword:b,saving:j,onClose:S,onSave:E})=>{const _=F[a.type],M=n=>r(p=>({...p,name:n.target.value})),l=n=>{const p=n.currentTarget.dataset.type;p&&r(N=>({...N,type:p,config:{}}))},o=n=>{const p=n.currentTarget.dataset.field;p&&r(N=>({...N,config:{...N.config,[p]:n.target.value}}))},P=()=>r(n=>({...n,config:n.config.use_custom_smtp===!0?{...n.config,use_custom_smtp:!1}:ie(n.config,h)})),x=n=>r(p=>({...p,config:{...p.config,smtp_use_tls:n.target.checked,smtp_use_ssl:n.target.checked?!1:p.config.smtp_use_ssl}})),k=n=>r(p=>({...p,config:{...p.config,smtp_use_ssl:n.target.checked,smtp_use_tls:n.target.checked?!1:p.config.smtp_use_tls}})),J=n=>r(p=>({...p,event_types:p.event_types.includes(n)?p.event_types.filter(N=>N!==n):[...p.event_types,n]})),U=()=>r(n=>({...n,enabled:!n.enabled})),X=()=>b(n=>!n),G=(n,p)=>e.jsx("li",{children:n},p);return s?_e.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},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:t?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:S,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:a.name,onChange:M,placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys(F).map(n=>{const p=F[n],N=p.icon,q=a.type===n;return e.jsxs("button",{"data-type":n,type:"button",onClick:l,className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${q?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(N,{className:`w-5 h-5 ${q?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${q?"text-brand":"text-gray-600"}`,children:p.label})]},n)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",_.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:_.guide.steps.map(G)}),_.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:_.guide.urlFormat})]}),_.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",_.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:_.fields.map(n=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[n.label,n.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":n.key,type:n.type==="password"?"password":n.type==="number"?"number":"text",value:String(a.config[n.key]||""),onChange:o,placeholder:n.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),n.help&&e.jsx("p",{className:"text-xs text-gray-500",children:n.help})]},n.key))}),a.type==="email"&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"SMTP 来源"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-gray-500",children:a.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:P,className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${a.config.use_custom_smtp===!0?"bg-brand":"bg-gray-300"}`,"aria-label":"使用独立 SMTP",children:e.jsx("span",{className:`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${a.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),a.config.use_custom_smtp===!0&&e.jsxs("div",{className:"space-y-4 border-t border-blue-100 bg-white/80 p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 服务器 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:String(a.config.smtp_server||""),onChange:o,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 端口 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_port",type:"number",value:String(a.config.smtp_port||587),onChange:o,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["登录邮箱 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:String(a.config.smtp_user||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["密码 / 授权码 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{"data-field":"smtp_password",type:w?"text":"password",value:String(a.config.smtp_password||""),onChange:o,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:X,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:w?e.jsx(re,{className:"w-4 h-4"}):e.jsx(le,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:String(a.config.smtp_from_name||""),onChange:o,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["发件邮箱地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:String(a.config.smtp_from_address||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_tls!==!1,onChange:x}),"STARTTLS(常用于 587)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_ssl===!0,onChange:k}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(qe,{selectedEvents:a.event_types,onToggleEvent:J}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:U,className:`relative w-11 h-6 rounded-full transition-colors ${a.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${a.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),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:S,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:E,disabled:j,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[j?e.jsx(z,{className:"w-4 h-4 animate-spin"}):e.jsx(V,{className:"w-4 h-4"}),j?"保存中...":"保存"]})]})]})}),document.body):null},Re=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:r,setShowPassword:h,onSave:w})=>{const b=l=>{const o=l.currentTarget.dataset.field;o&&t(P=>({...P,[o]:l.target.value}))},j=l=>{t(o=>({...o,smtp_port:parseInt(l.target.value,10)||587}))},S=l=>{t(o=>({...o,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:o.smtp_use_ssl}))},E=l=>{t(o=>({...o,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:o.smtp_use_tls}))},_=l=>{t(o=>({...o,smtp_password:l.target.value}))},M=()=>h(l=>!l);return e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(te,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 服务器"}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:typeof s.smtp_server=="string"?s.smtp_server:"",onChange:b,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:typeof s.smtp_port=="number"?s.smtp_port:587,onChange:j,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:typeof s.smtp_user=="string"?s.smtp_user:"",onChange:b,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:r?"text":"password",value:typeof s.smtp_password=="string"?s.smtp_password:"",onChange:_,placeholder:s.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:M,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:r?e.jsx(re,{className:"w-4 h-4"}):e.jsx(le,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:typeof s.smtp_from_name=="string"?s.smtp_from_name:"",onChange:b,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:typeof s.smtp_from_address=="string"?s.smtp_from_address:typeof s.smtp_user=="string"?s.smtp_user:"",onChange:b,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_tls!==!1,onChange:S}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_ssl===!0,onChange:E}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:w,disabled:a,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a?e.jsx(z,{className:"w-4 h-4 animate-spin"}):e.jsx(we,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},Be=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)},pe=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Ae=s=>{const t={},a=s.type==="ding_talk"?"dingtalk":s.type==="lark"?"feishu":s.type;return{id:String(s.id),name:s.name,type:a,config:t,event_types:Be(s.event_types),enabled:s.enabled}},Oe=async s=>({success:!0,data:(await R(a=>B.GET("/api/v1/notifications/channels",{signal:a}),s)).map(Ae)}),Fe=async(s,t)=>R(a=>B.POST("/api/v1/notifications/channels",{body:{name:s.name,type:s.type,config:JSON.stringify(s.config),event_types:pe(s.event_types),enabled:s.enabled},signal:a}),t),se=async(s,t,a)=>{const r={name:t.name,type:t.type,config:t.config===void 0?void 0:JSON.stringify(t.config),event_types:t.event_types===void 0?void 0:pe(t.event_types),enabled:t.enabled};return R(h=>B.PUT("/api/v1/notifications/channels/{channel_id}",{params:{path:{channel_id:s}},body:r,signal:h}),a)},$e=async(s,t)=>R(a=>B.DELETE("/api/v1/notifications/channels/{channel_id}",{params:{path:{channel_id:s}},signal:a}),t),De=async(s,t)=>R(a=>B.POST("/api/v1/notifications/channels/{channel_id}/test",{params:{path:{channel_id:s}},signal:a}),t),Ue=s=>{const t={...s};if("renewal_log_retention_days"in t){const a=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(a)?a:10}return t},We=async s=>{const t=await R(a=>B.GET("/api/v1/settings/system",{signal:a}),s);return Ue(t.data||t.settings||t)},Ie=async(s,t)=>R(a=>B.PUT("/api/v1/settings/system",{body:s,signal:a}),t),ze=s=>{const[t,a]=d.useState([]),[r,h]=d.useState(!0),[w,b]=d.useState(!1),[j,S]=d.useState(null),[E,_]=d.useState(!1),[M,l]=d.useState(""),[o,P]=d.useState(null),[x,k]=d.useState({}),[J,U]=d.useState(!1),[X,G]=d.useState(!1),[n,p]=d.useState(!1),[N,q]=d.useState(ee),$=d.useRef(0),K=d.useRef(null),C=d.useRef(0),A=d.useRef(null),y=d.useRef(0),T=d.useRef(null),O=d.useRef(null),f=d.useCallback((i,c)=>{P({type:i,text:c}),O.current!==null&&window.clearTimeout(O.current),O.current=window.setTimeout(()=>{O.current=null,P(null)},3e3)},[]),L=d.useCallback(async()=>{var m;const i=++$.current;(m=K.current)==null||m.abort();const c=new AbortController;K.current=c,h(!0);try{const u=await Oe({signal:c.signal});if(!g(i,$.current))return;a(u.data||[])}catch(u){g(i,$.current)&&!c.signal.aborted&&console.error("加载通知渠道失败",u)}finally{g(i,$.current)&&h(!1)}},[]),Z=d.useCallback(async()=>{var m;const i=++C.current;(m=A.current)==null||m.abort();const c=new AbortController;A.current=c;try{const u=await We({signal:c.signal});g(i,C.current)&&k(u||{})}catch(u){g(i,C.current)&&!c.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var i;return L(),s?Z():(C.current+=1,(i=A.current)==null||i.abort(),k({})),(()=>{var c,m;$.current+=1,(c=K.current)==null||c.abort(),C.current+=1,(m=A.current)==null||m.abort()})},[s,L,Z]),d.useEffect(()=>(()=>{O.current!==null&&window.clearTimeout(O.current)}),[]);const me=d.useCallback(()=>{S(null),q(ee()),p(!1),b(!0)},[]),ue=d.useCallback(i=>{S(i),q(Te(i,x)),p(!1),b(!0)},[x]),xe=d.useCallback(()=>{var i;y.current+=1,(i=T.current)==null||i.abort(),_(!1),b(!1)},[]),ge=d.useCallback(async()=>{var u;const i=Pe(N);if(i){f("error",i);return}const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m,_(!0);try{const v=Ee(N);if(j?await se(j.id,v,{signal:m.signal}):await Fe(v,{signal:m.signal}),!g(c,y.current)||(b(!1),await L(),!g(c,y.current)))return;f("success",j?"已更新":"已创建")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",D(v,"保存失败"))}finally{g(c,y.current)&&_(!1)}},[j,N,L,f]),he=d.useCallback(async i=>{var u;if(!confirm(`确认删除渠道「${i.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await $e(i.id,{signal:m.signal}),!g(c,y.current)||(await L(),!g(c,y.current)))return;f("success","已删除")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",D(v,"删除失败"))}},[L,f]),be=d.useCallback(async i=>{var u;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await se(i.id,{enabled:!i.enabled},{signal:m.signal}),!g(c,y.current))return;a(v=>v.map(W=>W.id===i.id?{...W,enabled:!W.enabled}:W))}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",D(v,"切换失败"))}},[f]),ye=d.useCallback(async i=>{var u;l(i.id);const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{await De(i.id,{signal:m.signal}),g(c,y.current)&&f("success","测试通知已发送,请检查对应渠道")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",D(v,"发送失败"))}finally{g(c,y.current)&&l("")}},[f]),fe=d.useCallback(async()=>{var m;const i=++C.current;(m=A.current)==null||m.abort();const c=new AbortController;A.current=c,U(!0);try{const u={smtp_server:x.smtp_server||"",smtp_port:x.smtp_port||587,smtp_user:x.smtp_user||"",smtp_from_name:x.smtp_from_name||"",smtp_from_address:x.smtp_from_address||x.smtp_user||"",smtp_use_tls:x.smtp_use_tls!==!1,smtp_use_ssl:x.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(x,"smtp_password")&&(u.smtp_password=x.smtp_password),await Ie(u,{signal:c.signal}),g(i,C.current)&&f("success","SMTP 配置已保存")}catch(u){g(i,C.current)&&!c.signal.aborted&&f("error",D(u,"保存失败"))}finally{g(i,C.current)&&U(!1)}},[f,x]);return{channels:t,loading:r,showModal:w,editing:j,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:J,showSmtpPassword:X,showChannelSmtpPassword:n,form:N,setForm:q,setSmtp:k,setShowSmtpPassword:G,setShowChannelSmtpPassword:p,loadChannels:L,openCreate:me,openEdit:ue,closeModal:xe,showToast:f,handleSave:ge,handleDelete:he,handleToggleEnabled:be,handleTest:ye,handleSaveSmtp:fe}},Qe=({isAdmin:s=!1})=>{const t=ze(s);return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:t.loadChannels,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(ke,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:t.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(Se,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(I,{className:"w-5 h-5 text-brand mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),t.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(z,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(Me,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Re,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx(Le,{showModal:t.showModal,editing:t.editing,form:t.form,setForm:t.setForm,smtp:t.smtp,showChannelSmtpPassword:t.showChannelSmtpPassword,setShowChannelSmtpPassword:t.setShowChannelSmtpPassword,saving:t.saving,onClose:t.closeModal,onSave:t.handleSave}),t.toast&&e.jsxs("div",{className:`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${t.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[t.toast.type==="success"?e.jsx(V,{className:"w-4 h-4"}):e.jsx(ne,{className:"w-4 h-4"}),t.toast.text]})]})};export{Qe as default}; diff --git a/internal/webui/static/assets/Notifications-DHwrazHy.js b/internal/webui/static/assets/Notifications-DHwrazHy.js deleted file mode 100644 index 80b336c..0000000 --- a/internal/webui/static/assets/Notifications-DHwrazHy.js +++ /dev/null @@ -1 +0,0 @@ -import{j as e,b as _e,a as d}from"./react-vendor-l-BBvuKH.js";import{ai as ee,ah as se,aj as Ne,u as K,e as W,L as I,w as ve,y as ke,t as Q,X as te,z as ae,F as ne,o as we,R as Se,N as Ce}from"./icons-vendor-Bgrth_9N.js";import{g as le,p as re,b as oe,e as Te}from"./index-WrujSo30.js";import"./vendor-cRYyTeIw.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//这是测试推送内容","URL 路径里 那一段就是 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",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:ee,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},pe=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],Y=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Pe=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=pe.find(n=>n.value===t))==null?void 0:a.label)||t}).join("、"),Ee=(s,t)=>{const a=s.type==="email"?ie({...s.config||{}}):null,n=a?a.use_custom_smtp===!0?ce(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:n,event_types:s.event_types||[]}},Me=s=>{const a=B[s.type].fields.find(n=>n.required&&!String(s.config[n.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!s.name.trim())return"请填写渠道名称";if(s.type==="email"){const n=de(s.config);if(n.use_custom_smtp){const k=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([h])=>!String(n[h]||"").trim());if(k)return`请填写 ${k[1]}`}}return""},qe=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?de(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),g=(s,t)=>s===t,F=(s,t)=>s instanceof Error&&s.message?s.message:t,Le=({channels:s,testingId:t,onEdit:a,onDelete:n,onToggleEnabled:b,onTest:k})=>{const h=r=>s.find(o=>o.id===r.currentTarget.dataset.channelId)||null,_=r=>{const o=h(r);o&&b(o)},S=r=>{const o=h(r);o&&k(o)},E=r=>{const o=h(r);o&&a(o)},j=r=>{const o=h(r);o&&n(o)},M=r=>{const o=B[r.type]||B.webhook,P=o.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(P,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:r.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:o.label}),!r.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:o.fields.map(x=>{var w;return(w=r.config)==null?void 0:w[x.key]}).filter(Boolean).map((x,w)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},w))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Pe(r.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":r.id,onClick:_,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${r.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:r.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":r.id,onClick:S,disabled:t===r.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[t===r.id?e.jsx(I,{className:"w-3 h-3 animate-spin"}):e.jsx(se,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":r.id,onClick:E,className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(ve,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":r.id,onClick:j,className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(ke,{className:"w-4 h-4"})})]})]},r.id)};return s.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(W,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:s.map(M)})},Re=({selectedEvents:s,onToggleEvent:t})=>{const a=n=>{const b=n.currentTarget.dataset.event;b&&t(b)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:pe.map(n=>{const b=s.includes(n.value);return e.jsxs("button",{type:"button","data-event":n.value,onClick:a,className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${b?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${b?"bg-brand border-brand":"border-gray-300"}`,children:b&&e.jsx(Q,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:n.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:n.description})]},n.value)})})]})},Ae=({showModal:s,editing:t,form:a,setForm:n,smtp:b,showChannelSmtpPassword:k,setShowChannelSmtpPassword:h,saving:_,onClose:S,onSave:E})=>{const j=B[a.type],M=l=>n(p=>({...p,name:l.target.value})),r=l=>{const p=l.currentTarget.dataset.type;p&&n(N=>({...N,type:p,config:{}}))},o=l=>{const p=l.currentTarget.dataset.field;p&&n(N=>({...N,config:{...N.config,[p]:l.target.value}}))},P=()=>n(l=>({...l,config:l.config.use_custom_smtp===!0?{...l.config,use_custom_smtp:!1}:ce(l.config,b)})),x=l=>n(p=>({...p,config:{...p.config,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:p.config.smtp_use_ssl}})),w=l=>n(p=>({...p,config:{...p.config,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:p.config.smtp_use_tls}})),U=l=>n(p=>({...p,event_types:p.event_types.includes(l)?p.event_types.filter(N=>N!==l):[...p.event_types,l]})),O=()=>n(l=>({...l,enabled:!l.enabled})),z=()=>h(l=>!l),J=(l,p)=>e.jsx("li",{children:l},p);return s?_e.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},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:t?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:S,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(te,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:a.name,onChange:M,placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys(B).map(l=>{const p=B[l],N=p.icon,q=a.type===l;return e.jsxs("button",{"data-type":l,type:"button",onClick:r,className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${q?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(N,{className:`w-5 h-5 ${q?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${q?"text-brand":"text-gray-600"}`,children:p.label})]},l)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",j.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:j.guide.steps.map(J)}),j.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:j.guide.urlFormat})]}),j.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",j.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:j.fields.map(l=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[l.label,l.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":l.key,type:l.type==="password"?"password":l.type==="number"?"number":"text",value:String(a.config[l.key]||""),onChange:o,placeholder:l.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),l.help&&e.jsx("p",{className:"text-xs text-gray-500",children:l.help})]},l.key))}),a.type==="email"&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"SMTP 来源"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-gray-500",children:a.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:P,className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${a.config.use_custom_smtp===!0?"bg-brand":"bg-gray-300"}`,"aria-label":"使用独立 SMTP",children:e.jsx("span",{className:`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${a.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),a.config.use_custom_smtp===!0&&e.jsxs("div",{className:"space-y-4 border-t border-blue-100 bg-white/80 p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 服务器 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:String(a.config.smtp_server||""),onChange:o,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 端口 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_port",type:"number",value:String(a.config.smtp_port||587),onChange:o,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["登录邮箱 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:String(a.config.smtp_user||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["密码 / 授权码 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{"data-field":"smtp_password",type:k?"text":"password",value:String(a.config.smtp_password||""),onChange:o,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:z,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:k?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(ne,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:String(a.config.smtp_from_name||""),onChange:o,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["发件邮箱地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:String(a.config.smtp_from_address||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_tls!==!1,onChange:x}),"STARTTLS(常用于 587)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_ssl===!0,onChange:w}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Re,{selectedEvents:a.event_types,onToggleEvent:U}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:O,className:`relative w-11 h-6 rounded-full transition-colors ${a.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${a.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),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:S,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:E,disabled:_,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[_?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(Q,{className:"w-4 h-4"}),_?"保存中...":"保存"]})]})]})}),document.body):null},Be=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:n,setShowPassword:b,onSave:k})=>{const h=r=>{const o=r.currentTarget.dataset.field;o&&t(P=>({...P,[o]:r.target.value}))},_=r=>{t(o=>({...o,smtp_port:parseInt(r.target.value,10)||587}))},S=r=>{t(o=>({...o,smtp_use_tls:r.target.checked,smtp_use_ssl:r.target.checked?!1:o.smtp_use_ssl}))},E=r=>{t(o=>({...o,smtp_use_ssl:r.target.checked,smtp_use_tls:r.target.checked?!1:o.smtp_use_tls}))},j=r=>{t(o=>({...o,smtp_password:r.target.value}))},M=()=>b(r=>!r);return e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(ee,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 服务器"}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:s.smtp_server||"",onChange:h,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:s.smtp_port||587,onChange:_,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:s.smtp_user||"",onChange:h,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:n?"text":"password",value:s.smtp_password||"",onChange:j,placeholder:s.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:M,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:n?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(ne,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:s.smtp_from_name||"",onChange:h,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:s.smtp_from_address||s.smtp_user||"",onChange:h,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_tls!==!1,onChange:S}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_ssl===!0,onChange:E}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:k,disabled:a,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(we,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},$e=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)},me=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Fe=s=>{const t={},a=s.type==="ding_talk"?"dingtalk":s.type==="lark"?"feishu":s.type;return{id:String(s.id),name:s.name,type:a,config:t,event_types:$e(s.event_types),enabled:s.enabled}},Oe=async s=>{const t=await le("/api/v1/notifications/channels",void 0,s);return{success:!0,data:(Array.isArray(t)?t:t.data||t.channels||[]).map(Fe)}},De=async(s,t)=>oe("/api/v1/notifications/channels",{...s,config:JSON.stringify(s.config),event_types:me(s.event_types)},t),Z=async(s,t,a)=>{const n={...t};return"config"in t&&(n.config=JSON.stringify(t.config)),"event_types"in t&&(n.event_types=me(t.event_types)),re(`/api/v1/notifications/channels/${s}`,n,a)},We=async(s,t)=>Te(`/api/v1/notifications/channels/${s}`,void 0,t),Ie=async(s,t)=>oe(`/api/v1/notifications/channels/${s}/test`,{},t),Ue=s=>{const t={...s};if("renewal_log_retention_days"in t){const a=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(a)?a:10}return t},ze=async s=>{const t=await le("/api/v1/settings/system",void 0,s);return Ue(t.data||t.settings||t)},Je=async(s,t)=>re("/api/v1/settings/system",s,t),Xe=s=>{const[t,a]=d.useState([]),[n,b]=d.useState(!0),[k,h]=d.useState(!1),[_,S]=d.useState(null),[E,j]=d.useState(!1),[M,r]=d.useState(""),[o,P]=d.useState(null),[x,w]=d.useState({}),[U,O]=d.useState(!1),[z,J]=d.useState(!1),[l,p]=d.useState(!1),[N,q]=d.useState(Y),$=d.useRef(0),X=d.useRef(null),C=d.useRef(0),R=d.useRef(null),y=d.useRef(0),T=d.useRef(null),A=d.useRef(null),f=d.useCallback((i,c)=>{P({type:i,text:c}),A.current!==null&&window.clearTimeout(A.current),A.current=window.setTimeout(()=>{A.current=null,P(null)},3e3)},[]),L=d.useCallback(async()=>{var m;const i=++$.current;(m=X.current)==null||m.abort();const c=new AbortController;X.current=c,b(!0);try{const u=await Oe({signal:c.signal});if(!g(i,$.current))return;a(u.data||[])}catch(u){g(i,$.current)&&!c.signal.aborted&&console.error("加载通知渠道失败",u)}finally{g(i,$.current)&&b(!1)}},[]),V=d.useCallback(async()=>{var m;const i=++C.current;(m=R.current)==null||m.abort();const c=new AbortController;R.current=c;try{const u=await ze({signal:c.signal});g(i,C.current)&&w(u||{})}catch(u){g(i,C.current)&&!c.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var i;return L(),s?V():(C.current+=1,(i=R.current)==null||i.abort(),w({})),(()=>{var c,m;$.current+=1,(c=X.current)==null||c.abort(),C.current+=1,(m=R.current)==null||m.abort()})},[s,L,V]),d.useEffect(()=>(()=>{A.current!==null&&window.clearTimeout(A.current)}),[]);const ue=d.useCallback(()=>{S(null),q(Y()),p(!1),h(!0)},[]),xe=d.useCallback(i=>{S(i),q(Ee(i,x)),p(!1),h(!0)},[x]),ge=d.useCallback(()=>{var i;y.current+=1,(i=T.current)==null||i.abort(),j(!1),h(!1)},[]),he=d.useCallback(async()=>{var u;const i=Me(N);if(i){f("error",i);return}const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m,j(!0);try{const v=qe(N);if(_?await Z(_.id,v,{signal:m.signal}):await De(v,{signal:m.signal}),!g(c,y.current)||(h(!1),await L(),!g(c,y.current)))return;f("success",_?"已更新":"已创建")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",F(v,"保存失败"))}finally{g(c,y.current)&&j(!1)}},[_,N,L,f]),be=d.useCallback(async i=>{var u;if(!confirm(`确认删除渠道「${i.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await We(i.id,{signal:m.signal}),!g(c,y.current)||(await L(),!g(c,y.current)))return;f("success","已删除")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",F(v,"删除失败"))}},[L,f]),ye=d.useCallback(async i=>{var u;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await Z(i.id,{enabled:!i.enabled},{signal:m.signal}),!g(c,y.current))return;a(v=>v.map(D=>D.id===i.id?{...D,enabled:!D.enabled}:D))}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",F(v,"切换失败"))}},[f]),fe=d.useCallback(async i=>{var u;r(i.id);const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{await Ie(i.id,{signal:m.signal}),g(c,y.current)&&f("success","测试通知已发送,请检查对应渠道")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",F(v,"发送失败"))}finally{g(c,y.current)&&r("")}},[f]),je=d.useCallback(async()=>{var m;const i=++C.current;(m=R.current)==null||m.abort();const c=new AbortController;R.current=c,O(!0);try{const u={smtp_server:x.smtp_server||"",smtp_port:x.smtp_port||587,smtp_user:x.smtp_user||"",smtp_from_name:x.smtp_from_name||"",smtp_from_address:x.smtp_from_address||x.smtp_user||"",smtp_use_tls:x.smtp_use_tls!==!1,smtp_use_ssl:x.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(x,"smtp_password")&&(u.smtp_password=x.smtp_password),await Je(u,{signal:c.signal}),g(i,C.current)&&f("success","SMTP 配置已保存")}catch(u){g(i,C.current)&&!c.signal.aborted&&f("error",F(u,"保存失败"))}finally{g(i,C.current)&&O(!1)}},[f,x]);return{channels:t,loading:n,showModal:k,editing:_,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:U,showSmtpPassword:z,showChannelSmtpPassword:l,form:N,setForm:q,setSmtp:w,setShowSmtpPassword:J,setShowChannelSmtpPassword:p,loadChannels:L,openCreate:ue,openEdit:xe,closeModal:ge,showToast:f,handleSave:he,handleDelete:be,handleToggleEnabled:ye,handleTest:fe,handleSaveSmtp:je}},Ve=({isAdmin:s=!1})=>{const t=Xe(s);return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:t.loadChannels,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Se,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:t.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(W,{className:"w-5 h-5 text-brand mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),t.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(I,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(Le,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Be,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx(Ae,{showModal:t.showModal,editing:t.editing,form:t.form,setForm:t.setForm,smtp:t.smtp,showChannelSmtpPassword:t.showChannelSmtpPassword,setShowChannelSmtpPassword:t.setShowChannelSmtpPassword,saving:t.saving,onClose:t.closeModal,onSave:t.handleSave}),t.toast&&e.jsxs("div",{className:`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${t.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[t.toast.type==="success"?e.jsx(Q,{className:"w-4 h-4"}):e.jsx(te,{className:"w-4 h-4"}),t.toast.text]})]})};export{Ve as default}; diff --git a/internal/webui/static/assets/OrderList-B4B8_a2q.js b/internal/webui/static/assets/OrderList-B4B8_a2q.js new file mode 100644 index 0000000..2c5e4e3 --- /dev/null +++ b/internal/webui/static/assets/OrderList-B4B8_a2q.js @@ -0,0 +1 @@ +import{j as e,b as H,a as r}from"./react-vendor-l-BBvuKH.js";import{f as ee}from"./dateTime-DDi7rqpW.js";import{U as ne,I as ie,X as K,J as oe,R as Y,N as ce,O as se,m as te,E as de,F as xe,V as me,y as ue,h as he,g as pe,o as ge}from"./icons-vendor-Bgrth_9N.js";import{r as M,c as I}from"./index-CiBUw4Te.js";import{o as be,c as ye}from"./contract-COFcZjyb.js";import"./vendor-cRYyTeIw.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:{},a=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:a.map(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 格式"},z=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:a,onAccountFilterChange:u,accounts:p,accountName:x,searchText:g,onSearchChange:N})=>{const j=i=>t(i.currentTarget.dataset.status||"all"),h=i=>u(i.target.value),v=i=>N(i.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:fe.map(i=>e.jsx("button",{"data-status":i.key,onClick:j,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===i.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:i.label},i.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ne,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:h,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:"全部账号"}),p.map(i=>e.jsx("option",{value:i.id,children:x(i.id)},i.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:g,onChange:v,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=x=>{var g;s.setImportFile(((g=x.target.files)==null?void 0:g[0])||null)},a=()=>s.closeImportModal(),u=()=>void s.handleImportOrders(),p=()=>void s.handleRetryImport();return s.showImportModal?H.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(K,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:p,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.importResult.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:Ne(s.importResult).map((x,g)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${g}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:a,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:u,disabled:!s.importFile||s.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:s.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Oe=180,ae=5e3,Re=async s=>(await M(a=>I.GET("/api/v1/accounts/details",{signal:a}),s)).map(a=>({id:a.id,enabled:a.enabled,auto_confirm:a.auto_confirm,remark:a.remark,pause_duration:a.pause_duration,paused_until:a.paused_until,paused:a.paused,username:a.username,show_browser:a.show_browser,nickname:a.nickname,avatar_url:a.avatar_url,profile_error:a.profile_error})),Me=async(s,t)=>M(a=>I.GET("/api/v1/items",{params:{query:{cookie_id:s}},signal:a}),t),re=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Ie=async(s,t,a=1,u=20,p,x)=>{const g={page:a,page_size:u};s&&(g.cookie_id=s),t&&t!=="all"&&(g.status=t),p!=null&&p.trim()&&(g.search=p.trim());const j=await M(n=>I.GET("/api/v1/orders",{params:{query:g},signal:n}),x),h=be(j,["data","result"])||{},i=(Array.isArray(h.orders)?h.orders:ye(h.data,["data","orders","items"])).map(n=>({...n,id:n.order_id,order_status:re(n.order_status),status:re(n.status||n.order_status),quantity:Number(n.quantity||1)}));return{success:!0,data:i,total:h.total||i.length,page:h.page||a,page_size:h.page_size||u,total_pages:h.total_pages||1}},Fe=async(s,t)=>M(a=>I.PUT("/api/v1/orders/{order_id}",{params:{path:{order_id:s}},body:t,signal:a})),De=async s=>M(t=>I.DELETE("/api/v1/orders/{order_id}",{params:{path:{order_id:s}},signal:t})),Te=async(s,t,a)=>{const u=new FormData;s&&u.append("cookie_id",s),t&&u.append("status",t);const p=await M(h=>I.POST("/api/v1/orders/refresh",{body:u,signal:h}),a),x=Oe,g=500;let N=0;try{for(;NI.GET("/api/v1/orders/refresh/{job_id}",{params:{path:{job_id:p.job_id}},signal:i}),a);if(h.status==="succeeded"&&h.result)return h.result;if(h.status==="failed"||h.status==="cancelled")throw new Error(h.error_message||"订单刷新任务失败");const v=g;await new Promise((i,n)=>{const S=()=>{globalThis.clearTimeout(T),n(new Error("请求已取消"))},T=globalThis.setTimeout(()=>{var k;(k=a==null?void 0:a.signal)==null||k.removeEventListener("abort",S),i()},v);a!=null&&a.signal&&(a.signal.aborted?S():a.signal.addEventListener("abort",S,{once:!0}))}),N+=1}}finally{}const j=await Ae(p.job_id);if(j.status==="succeeded"&&j.result)return j.result;throw j.status==="failed"?new Error(j.error_message||"订单刷新任务失败"):new Error("订单刷新任务等待超时,已请求取消")},Ae=async s=>{try{await Pe(s,{timeoutMs:ae})}catch{}return M(t=>I.GET("/api/v1/orders/refresh/{job_id}",{params:{path:{job_id:s}},signal:t}),{timeoutMs:ae})},Pe=async(s,t)=>M(a=>I.DELETE("/api/v1/orders/refresh/{job_id}",{params:{path:{job_id:s}},signal:a}),t),Le=async s=>M(t=>I.POST("/api/v1/orders/{order_id}/refresh",{params:{path:{order_id:s}},signal:t})),$e=async(s,t)=>{const a=await M(u=>I.POST("/api/v1/orders/manual-ship",{body:{order_ids:s,ship_mode:t},signal:u}));return Z(a)},qe=async(s,t)=>{if(s instanceof FormData){const p=await M(x=>I.POST("/api/v1/orders/import",{body:s,signal:x}),t);return Z(p)}const u=await M(p=>I.POST("/api/v1/orders/import",{body:s,signal:p}),t);return Z(u)},Z=s=>({partial_failure:s.partial_failure,message:s.message,total:s.total,success_count:s.success_count,failed_count:s.failed_count,results:(s.results||[]).map(t=>({...t,status:t.status==="failed"||t.status==="succeeded"||t.status==="reconciliation_required"?t.status:void 0}))}),ze=(s={pageSize:20})=>{const[t,a]=r.useState([]),[u,p]=r.useState([]),[x,g]=r.useState([]),[N,j]=r.useState("all"),[h,v]=r.useState(""),[i,n]=r.useState(""),[S,T]=r.useState(""),[k,E]=r.useState(1),[_,$]=r.useState(1),[F,o]=r.useState(!1),w=r.useRef(0),y=r.useRef(null),D=r.useRef(null),P=r.useCallback(async()=>{var f;const d=++w.current;(f=y.current)==null||f.abort();const m=new AbortController;y.current=m,o(!0);try{const O=await Ie(h||void 0,N,k,s.pageSize,S,{signal:m.signal});if(!z(d,w.current))return;a(O.data),$(O.total_pages)}catch(O){z(d,w.current)&&!m.signal.aborted&&console.error("加载订单失败:",O)}finally{z(d,w.current)&&o(!1)}},[h,S,N,s.pageSize,k]);r.useEffect(()=>{const d=window.setTimeout(()=>{E(1),T(i.trim())},300);return(()=>window.clearTimeout(d))},[i]),r.useEffect(()=>(P(),(()=>{var d;w.current+=1,(d=y.current)==null||d.abort()})),[P]),r.useEffect(()=>{var m;const d=new AbortController;return(m=D.current)==null||m.abort(),D.current=d,Promise.all([Re({signal:d.signal}),Me(void 0,{signal:d.signal})]).then(([f,O])=>{d.signal.aborted||(g(f),p(O))}).catch(f=>{d.signal.aborted||console.error("加载订单辅助数据失败:",f)}),(()=>d.abort())},[]);const C=r.useMemo(()=>new Map(x.map(d=>[d.id,d])),[x]),A=r.useMemo(()=>{const d={};return u.forEach(m=>{m.item_id&&(d[`${m.cookie_id}:${m.item_id}`]=m.item_title||m.item_id)}),d},[u]),U=r.useCallback(d=>{const m=C.get(d),f=(m==null?void 0:m.remark)||(m==null?void 0:m.nickname);return f?`${f} · ${d.slice(0,6)}`:`账号 ${d.slice(0,8)}`},[C]),V=r.useCallback(d=>{const m=C.get(d);return(m==null?void 0:m.remark)||(m==null?void 0:m.nickname)||"未命名账号"},[C]),G=r.useCallback((d,m,f)=>{if(f!=null&&f.trim())return f;const O=A[`${d}:${m}`];if(O)return O;const R=u.find(B=>{if(!f||!B.item_title)return!1;const J=f.toLowerCase(),q=B.item_title.toLowerCase();return q.includes(J)||J.includes(q)});return(R==null?void 0:R.item_title)||"未知商品"},[A,u]);return{orders:t,items:u,accounts:x,filter:N,setFilter:j,accountFilter:h,setAccountFilter:v,searchText:i,setSearchText:n,page:k,setPage:E,totalPages:_,loading:F,loadOrders:P,accountName:U,accountNickname:V,getItemNameById:G}},Ge=s=>{const[t,a]=r.useState(!1),[u,p]=r.useState(null),[x,g]=r.useState(null),[N,j]=r.useState(!1),[h,v]=r.useState(""),i=r.useRef(0),n=r.useRef(null);r.useEffect(()=>(()=>{var _;i.current+=1,(_=n.current)==null||_.abort()}),[]);const S=r.useCallback(()=>{p(null),g(null),v(""),a(!0)},[]),T=r.useCallback(()=>{var _;i.current+=1,(_=n.current)==null||_.abort(),j(!1),a(!1),p(null),g(null),v("")},[]),k=r.useCallback(async()=>{var w;if(!_e(u,N))return;const _=u;if(!_)return;const $=ke(_);if($){v($);return}const F=++i.current;(w=n.current)==null||w.abort();const o=new AbortController;n.current=o,j(!0),g(null),v("");try{const y=new FormData;y.append("file",_);const D=je(await qe(y,{signal:o.signal}));if(!z(F,i.current))return;g(D),p(null),await s(),D.failed_count===0&&z(F,i.current)&&(alert(`订单导入成功,共 ${D.success_count} 条`),a(!1),g(null))}catch(y){z(F,i.current)&&!o.signal.aborted&&v(Ce(y,"导入失败,请检查文件格式"))}finally{z(F,i.current)&&j(!1)}},[u,N,s]),E=r.useCallback(async()=>{await k()},[k]);return{showImportModal:t,importFile:u,setImportFile:p,importResult:x,importing:N,importError:h,openImportModal:S,closeImportModal:T,handleImportOrders:k,handleRetryImport:E}},X=(s,t)=>s instanceof Error?s.message:t,Be=({orders:s,page:t,accountFilter:a,filter:u,setPage:p,loadOrders:x})=>{const[g,N]=r.useState(!1),[j,h]=r.useState(null),[v,i]=r.useState(!1),[n,S]=r.useState(null),[T,k]=r.useState(!1),[E,_]=r.useState(""),[$,F]=r.useState(!1),[o,w]=r.useState(null),[y,D]=r.useState(null),[P,C]=r.useState(null),A=r.useRef(0),U=r.useCallback(async()=>{const c=++A.current;try{const b=await Te(a||void 0,u);if(c!==A.current||(await x(),c!==A.current))return;b.message&&alert(b.message)}catch(b){if(c!==A.current)return;console.error("同步订单失败:",b),alert(X(b,"同步失败,请重试"))}},[a,u,x]),V=r.useCallback(c=>{_(c),w(null),k(!0)},[]),G=r.useCallback(async c=>{var b;F(!0),w(null);try{const L=(b=(await $e([E],c)).results)==null?void 0:b[0];L!=null&&L.success?(w({success:!0,message:L.message}),x()):w({success:!1,message:(L==null?void 0:L.message)||"发货失败"})}catch(W){w({success:!1,message:X(W,"请求失败")})}finally{F(!1)}},[x,E]),d=r.useCallback(c=>{h(c),N(!0)},[]),m=r.useCallback(c=>{S({...c}),i(!0)},[]),f=r.useCallback(c=>{S(b=>b&&{...b,...c})},[]),O=r.useCallback(async()=>{if(n!=null&&n.order_id)try{const c={};n.status!==void 0&&(c.order_status=n.status),n.buyer_id!==void 0&&(c.buyer_id=n.buyer_id),n.amount!==void 0&&(c.amount=n.amount),n.receiver_name!==void 0&&(c.receiver_name=n.receiver_name),n.receiver_phone!==void 0&&(c.receiver_phone=n.receiver_phone),n.receiver_address!==void 0&&(c.receiver_address=n.receiver_address),n.item_id!==void 0&&(c.item_id=n.item_id),n.quantity!==void 0&&(c.quantity=n.quantity),n.item_title!==void 0&&(c.item_title=n.item_title),await Fe(n.order_id,c),i(!1),S(null),await x()}catch(c){console.error("更新订单失败:",c),alert("更新失败,请重试")}},[n,x]),R=r.useCallback(async c=>{D(c);try{const b=await Le(c);b.success?await x():alert(b.message||"同步失败")}catch(b){console.error("同步订单失败:",b),alert(X(b,"同步失败,请重试"))}finally{D(null)}},[x]),B=r.useCallback(async c=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){C(c);try{await De(c),s.length===1&&t>1?p(b=>b-1):await x()}catch(b){console.error("删除订单失败:",b),alert(X(b,"删除失败,请重试")),await x()}finally{C(null)}}},[x,s.length,t,p]),J=r.useCallback(()=>N(!1),[]),q=r.useCallback(()=>i(!1),[]),Q=r.useCallback(()=>{k(!1),w(null)},[]);return{showDetailModal:g,selectedOrder:j,showEditModal:v,editingOrder:n,showShipModal:T,shipOrderId:E,shipLoading:$,shipResult:o,syncingOrderId:y,deletingOrderId:P,handleSync:U,handleShip:V,executeShip:G,handleViewDetail:d,handleEdit:m,handleSaveEdit:O,updateEditingOrder:f,handleSyncSingle:R,handleDelete:B,closeDetailModal:J,closeEditModal:q,closeShipModal:Q}},le=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},a={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:a[s]||s})},He=()=>{const s=ze(),t=Ge(s.loadOrders),{orders:a,accounts:u,filter:p,setFilter:x,accountFilter:g,setAccountFilter:N,searchText:j,setSearchText:h,page:v,setPage:i,totalPages:n,loading:S,loadOrders:T,accountName:k,accountNickname:E,getItemNameById:_}=s,$=Be({orders:a,page:v,accountFilter:g,filter:p,setPage:i,loadOrders:T}),{showDetailModal:F,selectedOrder:o,showEditModal:w,editingOrder:y,showShipModal:D,shipLoading:P,shipResult:C,syncingOrderId:A,deletingOrderId:U,handleSync:V,handleShip:G,executeShip:d,handleViewDetail:m,handleEdit:f,handleSaveEdit:O,updateEditingOrder:R,handleSyncSingle:B,handleDelete:J,closeDetailModal:q,closeEditModal:Q,closeShipModal:c}=$,b=l=>{x(l),i(1),h("")},W=l=>{N(l),i(1)},L=l=>{h(l),i(1)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:T,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(Y,{className:`w-5 h-5 ${S?"animate-spin":""}`})}),e.jsxs("button",{onClick:t.openImportModal,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(ce,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:V,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(se,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Se,{filter:p,onFilterChange:b,accountFilter:g,onAccountFilterChange:W,accounts:u,accountName:k,searchText:j,onSearchChange:L}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:a.map(l=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:l.item_image?e.jsx("img",{src:l.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(te,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:_(l.cookie_id,l.item_id,l.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:E(l.cookie_id),children:[e.jsx(ne,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:E(l.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",l.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",l.quantity," • ",ee(l.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:l.buyer_id}),l.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:l.receiver_name})]}),l.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:l.receiver_phone})]}),l.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:l.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:l.amount?`¥${l.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(le,{status:l.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[l.status==="pending_ship"&&e.jsx("button",{onClick:(()=>G(l.order_id)),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${l.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(de,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>m(l)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(xe,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>f(l)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(me,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>B(l.order_id)),disabled:A===l.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(Y,{className:`w-4 h-4 ${A===l.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>J(l.order_id)),disabled:U===l.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(ue,{className:"w-4 h-4"})})]})]},l.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",v," 页 / 共 ",n," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:v<=1,onClick:(()=>i(l=>l-1)),"aria-label":"上一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(he,{className:"w-5 h-5"})}),e.jsx("button",{disabled:v>=n,onClick:(()=>i(l=>l+1)),"aria-label":"下一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(pe,{className:"w-5 h-5"})})]})]})]}),F&&o&&H.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:q,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(K,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:o.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:E(o.cookie_id),children:E(o.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(le,{status:o.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:o.amount?`¥${o.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:o.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:ee(o.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[o.item_image&&e.jsx("img",{src:o.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:_(o.cookie_id,o.item_id,o.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",o.item_id]}),o.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",o.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:o.buyer_id})]}),o.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:o.receiver_name})]}),o.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:o.receiver_phone})]}),o.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:o.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:q,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),o.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{q(),G(o.order_id)}),className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),e.jsx(Ee,{...t}),D&&H.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},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(K,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:(()=>d("status_only")),disabled:P,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(se,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:(()=>d("full_delivery")),disabled:P,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(te,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),P&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(Y,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),C&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${C.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[C.success?"✓ ":"✗ ",C.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:c,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:C!=null&&C.success?"完成":"取消"})})]})}),document.body),w&&y&&H.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:Q,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(K,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:y.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:y.status,onChange:(l=>R({status:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:y.buyer_id,onChange:(l=>R({buyer_id:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:y.amount,onChange:(l=>R({amount:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:y.receiver_name||"",onChange:(l=>R({receiver_name:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:y.receiver_phone||"",onChange:(l=>R({receiver_phone:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:y.receiver_address||"",onChange:(l=>R({receiver_address:l.target.value})),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:y.item_title||"",onChange:(l=>R({item_title:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Q,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:O,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ge,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{He as default}; diff --git a/internal/webui/static/assets/OrderList-CXbMt2fz.js b/internal/webui/static/assets/OrderList-CXbMt2fz.js deleted file mode 100644 index 98c64c9..0000000 --- a/internal/webui/static/assets/OrderList-CXbMt2fz.js +++ /dev/null @@ -1 +0,0 @@ -import{j as e,b as X,a}from"./react-vendor-l-BBvuKH.js";import{f as Z}from"./dateTime-DDi7rqpW.js";import{U as re,I as ie,X as H,J as ce,R as K,N as oe,O as ee,m as se,E as de,F as xe,V as me,y as ue,h as he,g as ge,o as pe}from"./icons-vendor-Bgrth_9N.js";import{g as U,o as be,c as ye,d as le,b as Y,p as fe,e as ne}from"./index-WrujSo30.js";import"./vendor-cRYyTeIw.js";const ve=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},i=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:i.map(Ne)}},Ne=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},we=s=>(s==null?void 0:s.results.filter(_e))||[],_e=s=>!s.success,ke=(s,t)=>s!==null&&!t,Ce=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Se=(s,t)=>s instanceof Error&&s.message?s.message:t,Ee=({filter:s,onFilterChange:t,accountFilter:i,onAccountFilterChange:u,accounts:b,accountName:m,searchText:h,onSearchChange:N})=>{const g=l=>t(l.currentTarget.dataset.status||"all"),f=l=>u(l.target.value),y=l=>N(l.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:ve.map(l=>e.jsx("button",{"data-status":l.key,onClick:g,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===l.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:l.label},l.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(re,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:i,onChange:f,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),b.map(l=>e.jsx("option",{value:l.id,children:m(l.id)},l.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:h,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const t=m=>{var h;s.setImportFile(((h=m.target.files)==null?void 0:h[0])||null)},i=()=>s.closeImportModal(),u=()=>void s.handleImportOrders(),b=()=>void s.handleRetryImport();return s.showImportModal?X.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:i,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:b,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.importResult.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:we(s.importResult).map((m,h)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:m.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:m.message||"导入失败"})]},`${m.order_id}-${h}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:i,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:u,disabled:!s.importFile||s.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:s.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Me=180,te=5e3,Ie=async s=>U("/api/v1/accounts/details",void 0,s),Fe=async(s,t)=>U("/api/v1/items",void 0,t),Re=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},De=async(s,t,i=1,u=20,b,m)=>{const h={page:i,page_size:u};s&&(h.cookie_id=s),t&&t!=="all"&&(h.status=t),b!=null&&b.trim()&&(h.search=b.trim());const N=await U("/api/v1/orders",h,m),g=be(N,["data","result"])||{},y=(Array.isArray(g.orders)?g.orders:ye(g.data,["data","orders","items"])).map(l=>({...l,id:l.id||l.order_id,status:Re(l.status||l.order_status),quantity:Number(l.quantity||1)}));return{success:!0,data:y,total:g.total||y.length,page:g.page||i,page_size:g.page_size||u,total_pages:g.total_pages||1}},$e=async(s,t)=>fe(`/api/v1/orders/${s}`,t),Ae=async s=>ne(`/api/v1/orders/${s}`),Le=async(s,t,i)=>{const u=new FormData;s&&u.append("cookie_id",s),t&&u.append("status",t);const b=await le("/api/v1/orders/refresh",u,i),m=Me,h=500;let N=0;try{for(;N{const S=()=>{globalThis.clearTimeout(R),n(new Error("请求已取消"))},R=globalThis.setTimeout(()=>{var k;(k=i==null?void 0:i.signal)==null||k.removeEventListener("abort",S),l()},y);i!=null&&i.signal&&(i.signal.aborted?S():i.signal.addEventListener("abort",S,{once:!0}))}),N+=1}}finally{}const g=await Pe(b.job_id);if(g.status==="succeeded"&&g.result)return g.result;throw g.status==="failed"?new Error(g.error_message||"订单刷新任务失败"):new Error("订单刷新任务等待超时,已请求取消")},Pe=async s=>{try{await Te(s,{timeoutMs:te})}catch{}return U(`/api/v1/orders/refresh/${s}`,void 0,{timeoutMs:te})},Te=async(s,t)=>ne(`/api/v1/orders/refresh/${s}`,void 0,t),qe=async s=>Y(`/api/v1/orders/${s}/refresh`),ze=async(s,t)=>Y("/api/v1/orders/manual-ship",{order_ids:s,ship_mode:t}),Be=async(s,t)=>s instanceof FormData?le("/api/v1/orders/import",s,t):Y("/api/v1/orders/import",s,t),Je=(s={pageSize:20})=>{const[t,i]=a.useState([]),[u,b]=a.useState([]),[m,h]=a.useState([]),[N,g]=a.useState("all"),[f,y]=a.useState(""),[l,n]=a.useState(""),[S,R]=a.useState(""),[k,E]=a.useState(1),[_,L]=a.useState(1),[I,c]=a.useState(!1),w=a.useRef(0),v=a.useRef(null),F=a.useRef(null),$=a.useCallback(async()=>{var j;const d=++w.current;(j=v.current)==null||j.abort();const x=new AbortController;v.current=x,c(!0);try{const O=await De(f||void 0,N,k,s.pageSize,S,{signal:x.signal});if(!T(d,w.current))return;i(O.data),L(O.total_pages)}catch(O){T(d,w.current)&&!x.signal.aborted&&console.error("加载订单失败:",O)}finally{T(d,w.current)&&c(!1)}},[f,S,N,s.pageSize,k]);a.useEffect(()=>{const d=window.setTimeout(()=>{E(1),R(l.trim())},300);return(()=>window.clearTimeout(d))},[l]),a.useEffect(()=>($(),(()=>{var d;w.current+=1,(d=v.current)==null||d.abort()})),[$]),a.useEffect(()=>{var x;const d=new AbortController;return(x=F.current)==null||x.abort(),F.current=d,Promise.all([Ie({signal:d.signal}),Fe(void 0,{signal:d.signal})]).then(([j,O])=>{d.signal.aborted||(h(j),b(O))}).catch(j=>{d.signal.aborted||console.error("加载订单辅助数据失败:",j)}),(()=>d.abort())},[]);const C=a.useMemo(()=>new Map(m.map(d=>[d.id,d])),[m]),D=a.useMemo(()=>{const d={};return u.forEach(x=>{x.item_id&&(d[`${x.cookie_id}:${x.item_id}`]=x.item_title||x.item_id)}),d},[u]),J=a.useCallback(d=>{const x=C.get(d),j=(x==null?void 0:x.remark)||(x==null?void 0:x.nickname);return j?`${j} · ${d.slice(0,6)}`:`账号 ${d.slice(0,8)}`},[C]),G=a.useCallback(d=>{const x=C.get(d);return(x==null?void 0:x.remark)||(x==null?void 0:x.nickname)||"未命名账号"},[C]),q=a.useCallback((d,x,j)=>{if(j!=null&&j.trim())return j;const O=D[`${d}:${x}`];if(O)return O;const M=u.find(z=>{if(!j||!z.item_title)return!1;const B=j.toLowerCase(),P=z.item_title.toLowerCase();return P.includes(B)||B.includes(P)});return(M==null?void 0:M.item_title)||"未知商品"},[D,u]);return{orders:t,items:u,accounts:m,filter:N,setFilter:g,accountFilter:f,setAccountFilter:y,searchText:l,setSearchText:n,page:k,setPage:E,totalPages:_,loading:I,loadOrders:$,accountName:J,accountNickname:G,getItemNameById:q}},Ge=s=>{const[t,i]=a.useState(!1),[u,b]=a.useState(null),[m,h]=a.useState(null),[N,g]=a.useState(!1),[f,y]=a.useState(""),l=a.useRef(0),n=a.useRef(null);a.useEffect(()=>(()=>{var _;l.current+=1,(_=n.current)==null||_.abort()}),[]);const S=a.useCallback(()=>{b(null),h(null),y(""),i(!0)},[]),R=a.useCallback(()=>{var _;l.current+=1,(_=n.current)==null||_.abort(),g(!1),i(!1),b(null),h(null),y("")},[]),k=a.useCallback(async()=>{var w;if(!ke(u,N))return;const _=u;if(!_)return;const L=Ce(_);if(L){y(L);return}const I=++l.current;(w=n.current)==null||w.abort();const c=new AbortController;n.current=c,g(!0),h(null),y("");try{const v=new FormData;v.append("file",_);const F=je(await Be(v,{signal:c.signal}));if(!T(I,l.current))return;h(F),b(null),await s(),F.failed_count===0&&T(I,l.current)&&(alert(`订单导入成功,共 ${F.success_count} 条`),i(!1),h(null))}catch(v){T(I,l.current)&&!c.signal.aborted&&y(Se(v,"导入失败,请检查文件格式"))}finally{T(I,l.current)&&g(!1)}},[u,N,s]),E=a.useCallback(async()=>{await k()},[k]);return{showImportModal:t,importFile:u,setImportFile:b,importResult:m,importing:N,importError:f,openImportModal:S,closeImportModal:R,handleImportOrders:k,handleRetryImport:E}},W=(s,t)=>s instanceof Error?s.message:t,Ue=({orders:s,page:t,accountFilter:i,filter:u,setPage:b,loadOrders:m})=>{const[h,N]=a.useState(!1),[g,f]=a.useState(null),[y,l]=a.useState(!1),[n,S]=a.useState(null),[R,k]=a.useState(!1),[E,_]=a.useState(""),[L,I]=a.useState(!1),[c,w]=a.useState(null),[v,F]=a.useState(null),[$,C]=a.useState(null),D=a.useRef(0),J=a.useCallback(async()=>{const o=++D.current;try{const p=await Le(i||void 0,u);if(o!==D.current||(await m(),o!==D.current))return;p.message&&alert(p.message)}catch(p){if(o!==D.current)return;console.error("同步订单失败:",p),alert(W(p,"同步失败,请重试"))}},[i,u,m]),G=a.useCallback(o=>{_(o),w(null),k(!0)},[]),q=a.useCallback(async o=>{var p;I(!0),w(null);try{const A=(p=(await ze([E],o)).results)==null?void 0:p[0];A!=null&&A.success?(w({success:!0,message:A.message}),m()):w({success:!1,message:(A==null?void 0:A.message)||"发货失败"})}catch(Q){w({success:!1,message:W(Q,"请求失败")})}finally{I(!1)}},[m,E]),d=a.useCallback(o=>{f(o),N(!0)},[]),x=a.useCallback(o=>{S({...o}),l(!0)},[]),j=a.useCallback(o=>{S(p=>p&&{...p,...o})},[]),O=a.useCallback(async()=>{if(n!=null&&n.order_id)try{const o={};n.status!==void 0&&(o.order_status=n.status),n.buyer_id!==void 0&&(o.buyer_id=n.buyer_id),n.amount!==void 0&&(o.amount=n.amount),n.receiver_name!==void 0&&(o.receiver_name=n.receiver_name),n.receiver_phone!==void 0&&(o.receiver_phone=n.receiver_phone),n.receiver_address!==void 0&&(o.receiver_address=n.receiver_address),n.item_id!==void 0&&(o.item_id=n.item_id),n.quantity!==void 0&&(o.quantity=n.quantity),n.item_title!==void 0&&(o.item_title=n.item_title),await $e(n.order_id,o),l(!1),S(null),await m()}catch(o){console.error("更新订单失败:",o),alert("更新失败,请重试")}},[n,m]),M=a.useCallback(async o=>{F(o);try{const p=await qe(o);p.success?await m():alert(p.message||"同步失败")}catch(p){console.error("同步订单失败:",p),alert(W(p,"同步失败,请重试"))}finally{F(null)}},[m]),z=a.useCallback(async o=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){C(o);try{await Ae(o),s.length===1&&t>1?b(p=>p-1):await m()}catch(p){console.error("删除订单失败:",p),alert(W(p,"删除失败,请重试")),await m()}finally{C(null)}}},[m,s.length,t,b]),B=a.useCallback(()=>N(!1),[]),P=a.useCallback(()=>l(!1),[]),V=a.useCallback(()=>{k(!1),w(null)},[]);return{showDetailModal:h,selectedOrder:g,showEditModal:y,editingOrder:n,showShipModal:R,shipOrderId:E,shipLoading:L,shipResult:c,syncingOrderId:v,deletingOrderId:$,handleSync:J,handleShip:G,executeShip:q,handleViewDetail:d,handleEdit:x,handleSaveEdit:O,updateEditingOrder:j,handleSyncSingle:M,handleDelete:z,closeDetailModal:B,closeEditModal:P,closeShipModal:V}},ae=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},i={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:i[s]||s})},Ke=()=>{const s=Je(),t=Ge(s.loadOrders),{orders:i,accounts:u,filter:b,setFilter:m,accountFilter:h,setAccountFilter:N,searchText:g,setSearchText:f,page:y,setPage:l,totalPages:n,loading:S,loadOrders:R,accountName:k,accountNickname:E,getItemNameById:_}=s,L=Ue({orders:i,page:y,accountFilter:h,filter:b,setPage:l,loadOrders:R}),{showDetailModal:I,selectedOrder:c,showEditModal:w,editingOrder:v,showShipModal:F,shipLoading:$,shipResult:C,syncingOrderId:D,deletingOrderId:J,handleSync:G,handleShip:q,executeShip:d,handleViewDetail:x,handleEdit:j,handleSaveEdit:O,updateEditingOrder:M,handleSyncSingle:z,handleDelete:B,closeDetailModal:P,closeEditModal:V,closeShipModal:o}=L,p=r=>{m(r),l(1),f("")},Q=r=>{N(r),l(1)},A=r=>{f(r),l(1)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:R,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(K,{className:`w-5 h-5 ${S?"animate-spin":""}`})}),e.jsxs("button",{onClick:t.openImportModal,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(oe,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:G,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(ee,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Ee,{filter:b,onFilterChange:p,accountFilter:h,onAccountFilterChange:Q,accounts:u,accountName:k,searchText:g,onSearchChange:A}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:i.map(r=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:r.item_image?e.jsx("img",{src:r.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(se,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:_(r.cookie_id,r.item_id,r.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:E(r.cookie_id),children:[e.jsx(re,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:E(r.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",r.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",r.quantity," • ",Z(r.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:r.buyer_id}),r.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:r.receiver_name})]}),r.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:r.receiver_phone})]}),r.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:r.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:r.amount?`¥${r.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(ae,{status:r.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[r.status==="pending_ship"&&e.jsx("button",{onClick:(()=>q(r.order_id)),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${r.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(de,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>x(r)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(xe,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>j(r)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(me,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>z(r.order_id)),disabled:D===r.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(K,{className:`w-4 h-4 ${D===r.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>B(r.order_id)),disabled:J===r.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(ue,{className:"w-4 h-4"})})]})]},r.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",y," 页 / 共 ",n," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:y<=1,onClick:(()=>l(r=>r-1)),"aria-label":"上一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(he,{className:"w-5 h-5"})}),e.jsx("button",{disabled:y>=n,onClick:(()=>l(r=>r+1)),"aria-label":"下一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(ge,{className:"w-5 h-5"})})]})]})]}),I&&c&&X.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:P,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:c.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:E(c.cookie_id),children:E(c.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(ae,{status:c.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:c.amount?`¥${c.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:c.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:Z(c.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[c.item_image&&e.jsx("img",{src:c.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:_(c.cookie_id,c.item_id,c.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",c.item_id]}),c.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",c.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:c.buyer_id})]}),c.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:c.receiver_name})]}),c.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:c.receiver_phone})]}),c.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:c.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:P,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),c.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{P(),q(c.order_id)}),className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),e.jsx(Oe,{...t}),F&&X.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},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:o,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:(()=>d("status_only")),disabled:$,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(ee,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:(()=>d("full_delivery")),disabled:$,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(se,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),$&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(K,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),C&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${C.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[C.success?"✓ ":"✗ ",C.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:o,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:C!=null&&C.success?"完成":"取消"})})]})}),document.body),w&&v&&X.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:V,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:v.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:v.status,onChange:(r=>M({status:r.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:v.buyer_id,onChange:(r=>M({buyer_id:r.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:v.amount,onChange:(r=>M({amount:r.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:v.receiver_name||"",onChange:(r=>M({receiver_name:r.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:v.receiver_phone||"",onChange:(r=>M({receiver_phone:r.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:v.receiver_address||"",onChange:(r=>M({receiver_address:r.target.value})),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:v.item_title||"",onChange:(r=>M({item_title:r.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:V,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:O,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(pe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{Ke as default}; diff --git a/internal/webui/static/assets/Rules-4H5_byLi.js b/internal/webui/static/assets/Rules-4H5_byLi.js deleted file mode 100644 index aff5e6c..0000000 --- a/internal/webui/static/assets/Rules-4H5_byLi.js +++ /dev/null @@ -1 +0,0 @@ -import{j as e,a as o,b as Fe}from"./react-vendor-l-BBvuKH.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,u as wt,n as et,I as kt,a1 as Ct,X as ke,V as ze,y as Ce,h as St,g as Rt,a6 as At,ag as $t,o as tt,ah as Mt}from"./icons-vendor-Bgrth_9N.js";import{g as Z,o as Ae,c as Ge,p as Ke,b as fe,e as Ue}from"./index-WrujSo30.js";import"./vendor-cRYyTeIw.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Dt=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Ft=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ge(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSize:y=10}={})=>{const A=await Z("/api/v1/automation-rules",{page:r,page_size:y,cookie_id:t||void 0,trigger_type:a||void 0,enabled:i,search:(u==null?void 0:u.trim())||void 0}),C=Ae(A,["data","result"])||{},m=ct(Ge(A,["data","rules","items"]));return{success:!0,data:m,total:Number(C.total??m.length),page:Number(C.page??r),page_size:Number(C.page_size??y),total_pages:Number(C.total_pages??(m.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(C.trigger_counts||{}).map(([I,T])=>[I,Number(T)]))}},zt=(t,a)=>{if(t!=="order_paid")return a.map((r,y)=>({...r,sort_order:r.sort_order||y+1}));const i=a.filter(r=>r.action_type==="send_card").map((r,y)=>({...r,sort_order:y+1})),u=a.filter(r=>r.action_type!=="send_card"&&r.action_type!=="confirm_shipment");return[...i,...u.map((r,y)=>({...r,sort_order:i.length+y+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:i.length+u.length+1}]},st=async t=>{const a=t.trigger_type||"order_paid",u=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[a]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),r=(t.actions||[]).filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment"),y=t.variants&&t.variants.length>0?[...t.variants.map((m,I)=>({action_type:"send_card",card_id:m.card_id,delivery_count:m.delivery_count||1,enabled:m.enabled!==!1,sort_order:I+1,delay_seconds:m.delay_seconds||0,config_json:JSON.stringify({spec_name:m.spec_name||"",spec_value:m.spec_value||"",delay_override:m.delay_override===!0})})),...r]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],A=zt(a,y),C={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||u||"自动化规则",trigger_type:a,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:A.map((m,I)=>({action_type:m.action_type,card_id:m.card_id||0,delivery_count:m.delivery_count||1,message_template:m.message_template||"",delay_seconds:m.delay_seconds||0,config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:m.sort_order||I+1}))};return t.id?Ke(`/api/v1/automation-rules/${t.id}`,C):fe("/api/v1/automation-rules",C)},Et=async t=>Ue(`/api/v1/automation-rules/${t}`),Ot=async()=>{const t=await Z("/api/v1/automation-issues"),a=Ae(t,["data","result"])||{};return{runs:Array.isArray(a==null?void 0:a.runs)?a.runs:[],pending_tasks:Array.isArray(a==null?void 0:a.pending_tasks)?a.pending_tasks:[]}},qt=async(t,a)=>fe(`/api/v1/automation-runs/${t}/resolve`,{resolution:a}),Vt=async(t,a)=>fe(`/api/v1/automation-pending-tasks/${t}/resolve`,{resolution:a}),Bt=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Jt=async t=>{const a=await Z(`/api/v1/reply-rules/${t}/typed`);return Ge(a,["data","items","rules"]).map(Bt)},Gt=async t=>t?(await Jt(t)).map(i=>({id:i.id,keyword:i.keyword||"",reply_content:i.reply||"",match_type:"fuzzy",enabled:!0,item_id:i.item_id||"",type:i.type==="image"?"image":"text",image_url:i.image_url||""})):[],Kt=async(t,a)=>{const i=t.type||"text",u={keyword:t.keyword||"",reply:i==="text"&&t.reply_content||"",item_id:t.item_id||"",type:i,image_url:i==="image"&&t.image_url||""};return t.id?Ke(`/api/v1/reply-rules/${a}/typed/${t.id}`,u):fe(`/api/v1/reply-rules/${a}/items`,u)},Ut=async(t,a)=>Ue(`/api/v1/reply-rules/${a}/typed/${t}`),at=async()=>{const t=await Z("/api/v1/default-replies");return Ae(t,["data","replies","items"])||{}},Wt=async t=>{const a=await Z(`/api/v1/default-replies/${t}`),i=Ae(a,["data","result"])||{};return{cookie_id:t,enabled:i.enabled||!1,reply_content:i.reply_content||"",reply_once:i.reply_once||!1,reply_image_url:i.reply_image_url||""}},Zt=async(t,a)=>Ke(`/api/v1/default-replies/${t}`,{enabled:a.enabled??!1,reply_content:a.reply_content||"",reply_once:a.reply_once??!1,reply_image_url:a.reply_image_url||""}),Xt=async t=>Ue(`/api/v1/default-replies/${t}`),Qt=async t=>fe(`/api/v1/default-replies/${t}/clear-records`,{}),Oe=()=>({submitting:!1,result:"idle"}),qe=t=>t.submitting?t:{submitting:!0,result:"idle"},Ve=(t,a)=>({...t,submitting:!1,result:a?"success":"failure"}),rt=t=>t+1,Be=(t,a,i,u)=>t===a&&i===u,Yt=t=>{const[a,i]=o.useState([]),[u,r]=o.useState({runs:[],pending_tasks:[]}),[y,A]=o.useState([]),[C,m]=o.useState({}),[I,T]=o.useState([]),[J,w]=o.useState([]),[G,D]=o.useState([]),[v,X]=o.useState(!1),q=o.useRef(0),re=o.useRef(0),[Q,K]=o.useState(0),[le,Y]=o.useState(0),[V,H]=o.useState({}),U=o.useCallback(async()=>{const P=Promise.all([Dt(),ot(),dt(),at()]),[_,j,F,ee]=await P;T(_),w(j),D(F),m(ee),t.setSelectedAccountId(ne=>{var E;return ne||((E=_[0])==null?void 0:E.id)||""})},[t.setSelectedAccountId]),n=o.useCallback(async()=>{var ee;const P=rt(q.current);q.current=P;const _=Ot().catch(ne=>(console.warn("加载自动化异常列表失败,不阻断规则展示",ne),null)),j=await Tt({cookieId:t.selectedAccountId||void 0,triggerType:t.automationTriggerFilter,enabled:t.automationStatusFilter==="all"?void 0:t.automationStatusFilter==="enabled",search:t.debouncedAutomationSearch,page:t.automationPage,pageSize:t.automationPageSize});if(!Be(P,q.current,t.selectedAccountId,t.selectedAccountId))return;i(j.data),K(j.total),Y(j.total_pages),H(j.trigger_counts||{}),j.page!==t.automationPage&&((ee=t.onAutomationPageChange)==null||ee.call(t,j.page));const F=await _;Be(P,q.current,t.selectedAccountId,t.selectedAccountId)&&F&&r(F)},[t.automationPage,t.automationPageSize,t.automationStatusFilter,t.automationTriggerFilter,t.debouncedAutomationSearch,t.onAutomationPageChange,t.selectedAccountId]),$=o.useCallback(async()=>{const P=rt(re.current);re.current=P;const _=t.selectedAccountId;if(A([]),!_)return;const j=await Gt(_);Be(P,re.current,_,t.selectedAccountId)&&A(j)},[t.selectedAccountId]),R=o.useCallback(async()=>{m(await at())},[]),z=o.useCallback(async()=>{X(!0);try{t.activeTab==="automation"?await n():t.activeTab==="reply"?await $():await R()}finally{X(!1)}},[n,R,$,t.activeTab]);return{automationRules:a,automationIssues:u,replyRules:y,defaultReplies:C,accounts:I,cards:J,items:G,automationTotal:Q,automationTotalPages:le,automationTriggerCounts:V,loading:v,setLoading:X,setAutomationRules:i,setCards:w,setItems:D,loadReferenceData:U,loadAutomationRules:n,loadReplyRules:$,loadDefaultReplies:R,refresh:z}},ae={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Nt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:vt},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:it}},Se=["order_paid","buyer_reviewed","review_missing_timeout"],Ht="亲,商品使用满意的话,麻烦给个评价,谢谢~",he=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),mt=t=>{if(!t)return{};try{const a=JSON.parse(t);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return{}}},ce=(t,a={})=>{const i=mt(t);return JSON.stringify({after_shipped_hours:Number(i.after_shipped_hours||72),repeat_interval_hours:Number(i.repeat_interval_hours||24),max_attempts:Number(i.max_attempts||1),...a})},ye=(t,a)=>{var u;const i=((u=ae[t])==null?void 0:u.label)||"自动化规则";return a?`${i} - ${a}`:i},lt=t=>{const a=(t||"").trim();return a?Object.values(ae).some(i=>a===i.label||a.startsWith(`${i.label} -`)):!0},_e=(t,a=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:Ht,enabled:!0,sort_order:1}];const i={action_type:"send_card",card_id:a,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[i,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[i]},es=t=>{var i,u;if(t.trigger_type==="review_missing_timeout")return((u=(i=t.actions)==null?void 0:i.find(r=>r.action_type==="send_text"))==null?void 0:u.message_template)||"发送求评价文案";const a=(t.actions||[]).filter(r=>r.action_type==="send_card");return a.length?a.map(r=>r.card_name||`卡密 ${r.card_id}`).join(" / "):"未配置卡密库存"},nt=(t,a=!1)=>{const i={blue:a?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:a?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:a?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return i[t]||i.blue},ts=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Re=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",ss=t=>t===!0||t===1||t==="1",as=({selectedAccountId:t,setSelectedAccountId:a,setActiveTab:i,items:u,setAutomationRules:r,setCards:y,setItems:A,setLoading:C,loadAutomationRules:m,loadReferenceData:I,loadReplyRules:T,loadDefaultReplies:J,initialDeliveryTarget:w,onDeliveryTargetHandled:G})=>{var xe;const[D,v]=o.useState(!1),[X,q]=o.useState(!1),[re,Q]=o.useState(!1),[K,le]=o.useState(Oe),[Y,V]=o.useState(Oe),[H,U]=o.useState(Oe),[n,$]=o.useState(null),[R,z]=o.useState(null),[M,P]=o.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),_=o.useMemo(()=>n!=null&&n.cookie_id&&n.item_id?u.find(l=>l.cookie_id===n.cookie_id&&l.item_id===n.item_id):void 0,[n==null?void 0:n.cookie_id,n==null?void 0:n.item_id,u]),j=ss(_==null?void 0:_.is_multi_spec),F=(n==null?void 0:n.trigger_type)||"order_paid",ee=ae[F],ne=mt(n==null?void 0:n.config_json),E=(xe=n==null?void 0:n.variants)!=null&&xe.length?n.variants:[he()],W=o.useCallback((l="order_paid",d=t,b="")=>{const p=u.find(N=>N.cookie_id===d&&N.item_id===b),h=(p==null?void 0:p.item_title)||b;return{name:ye(l,h),trigger_type:l,cookie_id:d,item_id:b,item_title:(p==null?void 0:p.item_title)||"",item_keyword:h,card_group_id:0,priority:100,enabled:!0,config_json:l==="review_missing_timeout"?ce():"{}",actions:_e(l),variants:l==="review_missing_timeout"?[]:[he()]}},[u,t]),ue=o.useCallback(l=>{var b,p;const d=l.trigger_type||"order_paid";$({...l,trigger_type:d,config_json:d==="review_missing_timeout"?ce(l.config_json):l.config_json||"{}",actions:(b=l.actions)!=null&&b.length?l.actions.map(h=>({...h})):_e(d,l.card_group_id),variants:(p=l.variants)!=null&&p.length?l.variants.map(h=>({...h})):d==="review_missing_timeout"?[]:[he()]}),v(!0)},[]);o.useEffect(()=>{if(!w)return;let l=!1;return(async()=>{i("automation"),a(w.cookieId),C(!0);try{const[b,p,h]=await Promise.all([Ft(),dt(),ot().catch(f=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",f),[]))]);if(l)return;r(b),A(p),y(h);const N=b.find(f=>f.cookie_id===w.cookieId&&f.item_id===w.itemId&&f.trigger_type==="order_paid");if(N)ue(N);else{const f=p.find(B=>B.cookie_id===w.cookieId&&B.item_id===w.itemId);$({...W("order_paid",w.cookieId,w.itemId),item_title:(f==null?void 0:f.item_title)||"",item_keyword:(f==null?void 0:f.item_title)||w.itemId,name:ye("order_paid",(f==null?void 0:f.item_title)||w.itemId)}),v(!0)}}catch(b){console.error("打开商品自动化规则失败",b),alert("无法加载该商品的自动化规则")}finally{l||(C(!1),G==null||G())}})(),(()=>{l=!0})},[W,w,G,ue,i,r,y,A,C,a]);const $e=o.useCallback((l="order_paid")=>{if(!t){alert("请先选择账号");return}$(W(l)),v(!0)},[W,t]),je=o.useCallback(l=>{var p,h,N,f,B;if(!n)return;const d=((h=(p=n.variants)==null?void 0:p.find(se=>se.card_id))==null?void 0:h.card_id)||((f=(N=n.actions)==null?void 0:N.find(se=>se.action_type==="send_card"))==null?void 0:f.card_id)||n.card_group_id||0,b=(_==null?void 0:_.item_title)||n.item_title||n.item_id||"";$({...n,trigger_type:l,name:lt(n.name)?ye(l,b):n.name,card_group_id:d,config_json:l==="review_missing_timeout"?ce(n.config_json):"{}",actions:_e(l,d),variants:l==="review_missing_timeout"?[]:(B=n.variants)!=null&&B.length?n.variants:[{...he(),card_id:d}]})},[n,_]),Me=o.useCallback(l=>{if(!n)return;const d=u.find(p=>p.cookie_id===(n.cookie_id||t)&&p.item_id===l),b=(d==null?void 0:d.item_title)||l;$({...n,item_id:l,item_title:(d==null?void 0:d.item_title)||"",item_keyword:b,name:lt(n.name)?ye(F,b):n.name})},[F,n,u,t]),pe=o.useCallback((l,d)=>{var p;if(!n)return;const b=E.map((h,N)=>N===l?{...h,...d}:h);$({...n,variants:b,card_group_id:((p=b[0])==null?void 0:p.card_id)||0})},[E,n]),Pe=o.useCallback(()=>{if(!n)return;const l=E[E.length-1];$({...n,variants:[...E,{...he(),spec_name:j&&(l==null?void 0:l.spec_name)||"",spec_value:j&&(l==null?void 0:l.spec_value)||""}]})},[E,n,j]),ve=o.useCallback(async()=>{var h,N,f,B,se;if(!n||K.submitting)return;const l=n.trigger_type||"order_paid";if(!n.cookie_id)return alert("请选择账号");const d=(h=n.variants)!=null&&h.length?n.variants:[];if(l!=="review_missing_timeout"){if(!d.length||d.some(k=>!k.card_id))return alert(l==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");if(j&&d.some(k=>!k.spec_name.trim()||!k.spec_value.trim()))return alert("多规格商品必须填写每一行的规格名称和规格值")}if(l==="review_missing_timeout"&&!(((f=(N=n.actions)==null?void 0:N.find(Le=>Le.action_type==="send_text"))==null?void 0:f.message_template)||"").trim())return alert("请填写求评价文案");const b=l==="review_missing_timeout"?[]:d.map(k=>({...k,spec_name:j?k.spec_name.trim():"",spec_value:j?k.spec_value.trim():"",delivery_count:Math.max(1,Number(k.delivery_count)||1),enabled:k.enabled!==!1}));le(qe(K));let p=!1;try{await st({...n,trigger_type:l,name:(n.name||"").trim()||ye(l,(_==null?void 0:_.item_title)||n.item_id||""),config_json:l==="review_missing_timeout"?ce(n.config_json):n.config_json||"{}",actions:(B=n.actions)!=null&&B.length?n.actions:_e(l,((se=b[0])==null?void 0:se.card_id)||n.card_group_id||0),variants:b}),v(!1),await Promise.all([m(),I()]),alert("保存成功"),p=!0}catch(k){console.error("保存自动化规则失败:",k),alert("保存失败:"+k.message)}finally{le(k=>Ve(k,p))}},[K,n,j,m,I,_]),g=o.useCallback(async l=>{if(confirm("确定删除该自动化规则吗?"))try{await Et(l),await m(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[m]),O=o.useCallback(async l=>{try{await st({...l,enabled:!l.enabled}),await m()}catch(d){alert("操作失败:"+d.message)}},[m]),S=o.useCallback(async(l,d)=>{if(confirm(d==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":d==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await qt(l,d),await m()}catch(p){alert("处理失败:"+p.message)}},[m]),te=o.useCallback(async(l,d)=>{if(confirm(d==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Vt(l,d),await m()}catch(b){alert("处理失败:"+b.message)}},[m]),L=o.useCallback(()=>{if(!t)return alert("请先选择账号");z({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),q(!0)},[t]),ie=o.useCallback(async()=>{var b,p,h;if(!R||!t||Y.submitting)return;const l=R.type==="image"?!!((b=R.image_url)!=null&&b.trim()):!!((p=R.reply_content)!=null&&p.trim());if(!((h=R.keyword)!=null&&h.trim())||!l)return alert("请填写关键词和回复内容");V(qe(Y));let d=!1;try{await Kt({...R,match_type:"fuzzy",enabled:!0},t),q(!1),await T(),alert("保存成功"),d=!0}catch(N){alert("保存失败:"+N.message)}finally{V(N=>Ve(N,d))}},[R,T,Y,t]),ge=o.useCallback(async l=>{if(!(!t||!confirm("确定删除该回复规则吗?")))try{await Ut(l,t),await T(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[T,t]),oe=o.useCallback(async(l=t)=>{if(!l)return alert("请先选择账号");try{const d=await Wt(l);P({cookie_id:l,enabled:d.enabled,reply_content:d.reply_content,reply_once:d.reply_once,reply_image_url:d.reply_image_url||""})}catch{P({cookie_id:l,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}Q(!0)},[t]),me=o.useCallback(async()=>{if(H.submitting)return;if(!M.cookie_id)return alert("请先选择账号");if(M.enabled&&!M.reply_content.trim()&&!M.reply_image_url.trim())return alert("启用默认回复时,请填写回复内容或图片 URL");U(qe(H));let l=!1;try{await Zt(M.cookie_id,{enabled:M.enabled,reply_content:M.reply_content,reply_once:M.reply_once,reply_image_url:M.reply_image_url}),Q(!1),await J(),alert("保存成功"),l=!0}catch(d){alert("保存失败:"+d.message)}finally{U(d=>Ve(d,l))}},[M,H,J]),Ne=o.useCallback(async l=>{if(confirm("确定删除该账号默认回复吗?"))try{await Xt(l),await J(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[J]),be=o.useCallback(async l=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Qt(l),alert("清空成功")}catch(d){alert("清空失败:"+d.message)}},[]);return{showAutomationModal:D,setShowAutomationModal:v,showReplyModal:X,setShowReplyModal:q,showDefaultModal:re,setShowDefaultModal:Q,automationSubmitState:K,replySubmitState:Y,defaultReplySubmitState:H,editingAutomationRule:n,setEditingAutomationRule:$,editingReplyRule:R,setEditingReplyRule:z,defaultForm:M,setDefaultForm:P,selectedRuleItem:_,isMultiSpecRule:j,currentTrigger:F,currentMeta:ee,reviewConfig:ne,displayVariants:E,buildAutomationDraft:W,openAutomationRule:ue,openNewAutomationRule:$e,handleTriggerChange:je,handleAutomationItemChange:Me,updateVariant:pe,appendDeliveryContent:Pe,handleSaveAutomationRule:ve,handleDeleteAutomation:g,handleToggleAutomation:O,handleResolveRunIssue:S,handleResolveDeferredIssue:te,handleAddReplyRule:L,handleSaveReplyRule:ie,handleDeleteReply:ge,openDefaultReplyModal:oe,handleSaveDefaultReply:me,handleDeleteDefaultReply:Ne,handleClearDefaultReplyRecords:be}},os=({initialDeliveryTarget:t,onDeliveryTargetHandled:a})=>{var Xe,Qe;const[i,u]=o.useState("automation"),[r,y]=o.useState(""),[A,C]=o.useState(""),[m,I]=o.useState(""),[T,J]=o.useState(""),[w,G]=o.useState("all"),[D,v]=o.useState(1),[X,q]=o.useState(10),re=Yt({activeTab:i,selectedAccountId:r,automationTriggerFilter:T,automationStatusFilter:w,debouncedAutomationSearch:m,automationPage:D,automationPageSize:X,setSelectedAccountId:y,onAutomationPageChange:v}),{automationRules:Q,automationIssues:K,replyRules:le,defaultReplies:Y,accounts:V,cards:H,items:U,loading:n,setLoading:$,automationTotal:R,automationTotalPages:z,automationTriggerCounts:M,setAutomationRules:P,setCards:_,setItems:j,loadReferenceData:F,loadAutomationRules:ee,loadReplyRules:ne,loadDefaultReplies:E,refresh:W}=re,ue=as({selectedAccountId:r,setSelectedAccountId:y,setActiveTab:u,items:U,setAutomationRules:P,setCards:_,setItems:j,setLoading:$,loadAutomationRules:ee,loadReferenceData:F,loadReplyRules:ne,loadDefaultReplies:E,initialDeliveryTarget:t,onDeliveryTargetHandled:a}),{showAutomationModal:$e,setShowAutomationModal:je,showReplyModal:Me,setShowReplyModal:pe,showDefaultModal:Pe,setShowDefaultModal:ve,editingAutomationRule:g,setEditingAutomationRule:O,editingReplyRule:S,setEditingReplyRule:te,defaultForm:L,setDefaultForm:ie,selectedRuleItem:ge,isMultiSpecRule:oe,currentTrigger:me,currentMeta:Ne,reviewConfig:be,displayVariants:xe,openAutomationRule:l,openNewAutomationRule:d,handleTriggerChange:b,handleAutomationItemChange:p,updateVariant:h,appendDeliveryContent:N,handleSaveAutomationRule:f,handleDeleteAutomation:B,handleToggleAutomation:se,handleResolveRunIssue:k,handleResolveDeferredIssue:Le,handleAddReplyRule:xt,handleSaveReplyRule:ut,handleDeleteReply:pt,openDefaultReplyModal:We,handleSaveDefaultReply:gt,handleDeleteDefaultReply:bt,handleClearDefaultReplyRecords:ht}=ue;o.useEffect(()=>{const s=window.setTimeout(()=>{v(1),I(A.trim())},300);return(()=>window.clearTimeout(s))},[A]),o.useEffect(()=>{F().catch(s=>console.error("加载规则参考数据失败",s))},[F]),o.useEffect(()=>{W().catch(s=>console.error("刷新规则页面失败",s))},[W]);const Ie=o.useMemo(()=>Q.filter(s=>!r||s.cookie_id===r),[Q,r]),we=o.useMemo(()=>Pt(K,r),[K,r]),Ze=o.useMemo(()=>V.filter(s=>!r||s.id===r),[V,r]),yt=o.useMemo(()=>{if(z<=1)return[];const s=Math.max(1,Math.min(D-2,z-4)),c=Math.min(z,s+4);return Array.from({length:c-s+1},(x,de)=>s+de)},[D,z]),De=!!(A.trim()||T||w!=="all"),_t=()=>{C(""),I(""),J(""),G("all"),v(1)},ft=o.useMemo(()=>{const s=(g==null?void 0:g.cookie_id)||r;return U.filter(c=>c.cookie_id===s)},[g==null?void 0:g.cookie_id,U,r]),jt=i==="automation"?"新建自动化":i==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"min-w-0 space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap gap-3",children:[e.jsxs("select",{value:r,onChange:(s=>{y(s.target.value),v(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]}),e.jsxs("button",{onClick:W,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 whitespace-nowrap transition-colors",children:[e.jsx(Te,{className:`w-4 h-4 ${n?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:i==="automation"?(()=>d("order_paid")):i==="reply"?xt:(()=>void We()),disabled:!r,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50",children:[e.jsx(Ye,{className:"w-4 h-4"}),jt]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:He},{id:"reply",label:"关键词回复",icon:wt},{id:"default",label:"账号默认回复",icon:et}].map(s=>{const c=s.icon;return e.jsxs("button",{onClick:(()=>u(s.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${i===s.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(c,{className:"w-4 h-4"}),s.label]},s.id)})}),i==="automation"&&(we.runs.length>0||we.pending_tasks.length>0)&&e.jsx(It,{runs:we.runs,pendingTasks:we.pending_tasks,onResolveRun:((s,c)=>void k(s,c)),onResolveDeferredTask:((s,c)=>void Le(s,c))}),i==="automation"&&e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]",children:[e.jsxs("aside",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon;return e.jsx("button",{type:"button",onClick:(()=>d(s)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${nt(c.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(x,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:c.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:c.description})]})]})},s)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-black text-gray-900",children:"筛选结果构成"}),e.jsxs("span",{className:"text-xs font-bold text-gray-400",children:["共 ",R," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(x,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:c.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:M[s]||0})]},s)})})]})]}),e.jsxs("section",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(kt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"搜索自动化规则",placeholder:"搜索规则名、商品名或商品 ID...",value:A,onChange:(s=>{C(s.target.value),v(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]}),e.jsxs("div",{className:"relative xl:w-52",children:[e.jsx(Ct,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按自动化类型筛选",value:T,onChange:(s=>{J(s.target.value),v(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部自动化类型"}),Se.map(s=>e.jsx("option",{value:s,children:ae[s].shortLabel},s))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:w,onChange:(s=>{G(s.target.value),v(1)}),className:"ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36",children:[e.jsx("option",{value:"all",children:"全部状态"}),e.jsx("option",{value:"enabled",children:"已启用"}),e.jsx("option",{value:"disabled",children:"已禁用"})]}),De&&e.jsx("button",{type:"button",onClick:_t,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900",title:"清除筛选","aria-label":"清除筛选",children:e.jsx(ke,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs font-bold text-gray-400",children:[e.jsxs("span",{children:["找到 ",R," 条规则"]}),n&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Te,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),n&&Ie.length===0?e.jsxs("div",{className:"flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400",children:[e.jsx(Te,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Ie.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(He,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:De?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:De?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Ie.map(s=>{const c=ae[s.trigger_type],x=c.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${nt(c.accent,!0)}`,children:e.jsx(x,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:s.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${ts(s.enabled)}`,children:s.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:c.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:s.item_title||s.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:es(s)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>l(s)),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(ze,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>se(s)),className:`px-4 py-2 rounded-xl text-sm font-bold ${s.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:s.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>B(s.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ce,{className:"w-4 h-4"})})]})]})},s.id)}),R>0&&e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-gray-500",children:[e.jsxs("span",{children:["第 ",D," / ",Math.max(z,1)," 页"]}),e.jsx("span",{className:"h-4 w-px bg-gray-200"}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"sr-only",children:"每页显示数量"}),e.jsx("select",{value:X,onChange:(s=>{q(Number(s.target.value)),v(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(s=>e.jsxs("option",{value:s,children:[s," 条/页"]},s))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:D<=1||n,onClick:(()=>v(s=>Math.max(1,s-1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"上一页",title:"上一页",children:e.jsx(St,{className:"h-4 w-4"})}),yt.map(s=>e.jsx("button",{type:"button",disabled:n,onClick:(()=>v(s)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${s===D?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${s} 页`,"aria-current":s===D?"page":void 0,children:s},s)),e.jsx("button",{type:"button",disabled:D>=z||n,onClick:(()=>v(s=>Math.min(z,s+1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"下一页",title:"下一页",children:e.jsx(Rt,{className:"h-4 w-4"})})]})]})]})]}),i==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Je,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[le.map(s=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",s.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:s.type==="image"&&s.image_url?s.image_url:s.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>{te({...s}),pe(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>pt(s.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]},s.id)),le.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),i==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Je,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Ze.map(s=>{const c=Y[s.id],x=!!(c!=null&&c.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${x?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${x?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(et,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:Re(s)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${x?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:x?"已启用":"未启用"}),(c==null?void 0:c.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:x?c.reply_content||c.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>void We(s.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),x&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void ht(s.id)),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:(()=>void bt(s.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]})]},s.id)}),Ze.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),$e&&g&&Fe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:g.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:Ne.description})]}),e.jsx("button",{onClick:(()=>je(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon,de=me===s;return e.jsx("button",{type:"button",onClick:(()=>b(s)),className:`w-full rounded-2xl p-4 text-left border transition-all ${de?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(x,{className:`w-5 h-5 mt-0.5 ${de?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:c.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${de?"text-gray-500":"text-gray-400"}`,children:c.description})]})]})},s)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:Ne.flow.map((s,c)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:c+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:s})]},s))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-surface-subtle",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(At,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:g.name||"",onChange:(s=>O({...g,name:s.target.value})),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:g.cookie_id||"",onChange:(s=>O({...g,cookie_id:s.target.value,item_id:"",item_title:"",item_keyword:""})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:g.item_id||"",onChange:(s=>p(s.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ft.map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]})]}),ge&&me!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:ge.item_title||ge.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${oe?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:oe?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),me!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:me==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:oe?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:N,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Ye,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:xe.map((s,c)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${oe?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[oe&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:s.spec_name,onChange:(x=>h(c,{spec_name:x.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:s.spec_value,onChange:(x=>h(c,{spec_value:x.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:s.card_id||"",onChange:(x=>h(c,{card_id:Number(x.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),H.filter(x=>x.enabled&&x.type!=="api").map(x=>e.jsx("option",{value:x.id,children:x.name},x.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:s.delivery_count,onChange:(x=>h(c,{delivery_count:Math.max(1,Number(x.target.value)||1)})),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:s.delay_override===!0,onChange:(x=>h(c,{delay_override:x.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),s.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:s.delay_seconds||0,onChange:(x=>h(c,{delay_seconds:Math.max(0,Number(x.target.value)||0)})),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:s.delay_override?`本动作延时 ${s.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:xe.length===1,onClick:(()=>O({...g,variants:xe.filter((x,de)=>de!==c)})),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(Ce,{className:"w-4 h-4"})})]},s.id||c))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(it,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.after_shipped_hours||72),onChange:(s=>O({...g,config_json:ce(g.config_json,{after_shipped_hours:Math.max(1,Number(s.target.value)||72)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.repeat_interval_hours||24),onChange:(s=>O({...g,config_json:ce(g.config_json,{repeat_interval_hours:Math.max(1,Number(s.target.value)||24)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(be.max_attempts||1),onChange:(s=>O({...g,config_json:ce(g.config_json,{max_attempts:Math.max(1,Number(s.target.value)||1)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((Qe=(Xe=g.actions)==null?void 0:Xe.find(s=>s.action_type==="send_text"))==null?void 0:Qe.message_template)||"",onChange:(s=>{var c;return O({...g,actions:((c=g.actions)!=null&&c.length?g.actions:_e("review_missing_timeout")).map(x=>x.action_type==="send_text"?{...x,message_template:s.target.value}:x)})}),className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:g.priority||100,onChange:(s=>O({...g,priority:Number(s.target.value)||100})),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:g.enabled!==!1,onChange:(s=>O({...g,enabled:s.target.checked})),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:(()=>je(!1)),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Me&&S&&Fe.createPortal(e.jsx("div",{className:"modal-overlay",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:S.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>pe(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:S.item_id||"",onChange:(s=>te({...S,item_id:s.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),U.filter(s=>!r||s.cookie_id===r).map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:S.type||"text",onChange:(s=>{const c=s.target.value;te({...S,type:c,reply_content:c==="text"?S.reply_content:"",image_url:c==="image"?S.image_url:""})}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:S.keyword||"",onChange:(s=>te({...S,keyword:s.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),S.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:S.image_url||"",onChange:(s=>te({...S,image_url:s.target.value})),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:S.reply_content||"",onChange:(s=>te({...S,reply_content:s.target.value})),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>pe(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Pe&&Fe.createPortal(e.jsx("div",{className:"modal-overlay",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.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:(()=>ve(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:L.cookie_id,onChange:(s=>ie({...L,cookie_id:s.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:(()=>ie({...L,enabled:!L.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${L.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${L.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:L.reply_content,onChange:(s=>ie({...L,reply_content:s.target.value})),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:L.reply_image_url,onChange:(s=>ie({...L,reply_image_url:s.target.value})),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:L.reply_once,onChange:(s=>ie({...L,reply_once:s.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ve(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:gt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})};export{os as default}; diff --git a/internal/webui/static/assets/Rules-CMO3kj4s.js b/internal/webui/static/assets/Rules-CMO3kj4s.js new file mode 100644 index 0000000..4a8f4f1 --- /dev/null +++ b/internal/webui/static/assets/Rules-CMO3kj4s.js @@ -0,0 +1 @@ +import{j as e,a as o,b as De}from"./react-vendor-l-BBvuKH.js";import{k as Be,ae as lt,af as ft,m as jt,R as Ie,N as Xe,Z as Qe,u as vt,n as Ye,I as Nt,a1 as wt,X as ke,V as Fe,y as Ce,h as kt,g as Ct,a6 as St,ag as Rt,o as He,ah as At}from"./icons-vendor-Bgrth_9N.js";import{r as v,c as N}from"./index-CiBUw4Te.js";import{o as Ae,c as Ue}from"./contract-COFcZjyb.js";import"./vendor-cRYyTeIw.js";const ze=(t,s)=>t.allowed_resolutions.includes(s),Mt=(t,s)=>({runs:t.runs.filter(l=>!s||l.cookie_id===s),pending_tasks:t.pending_tasks.filter(l=>!s||l.cookie_id===s)}),Tt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",Pt=({runs:t,pendingTasks:s,onResolveRun:l,onResolveDeferredTask:x})=>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(Be,{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:Tt(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:[ze(r,"continue")&&e.jsx("button",{onClick:(()=>l(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),ze(r,"retry")&&e.jsx("button",{onClick:(()=>l(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),ze(r,"cancel")&&e.jsx("button",{onClick:(()=>l(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),s.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>x(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:(()=>x(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Et=async t=>v(s=>N.GET("/api/v1/accounts/details",{signal:s}),t),nt=async t=>v(s=>N.GET("/api/v1/cards",{signal:s}),t),it=async(t,s)=>v(l=>N.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:l}),s),ot=t=>t.map(s=>{var l,x;return{id:String(s.id),name:s.name||"",trigger_type:s.trigger_type||"order_paid",item_keyword:s.item_title||s.item_id||"",cookie_id:s.cookie_id||"",item_id:s.item_id||"",item_title:s.item_title||"",card_group_id:Number(((l=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((x=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:x.card_name)||"",priority:s.priority||100,enabled:s.enabled||!1,config_json:s.config_json||"{}",actions:(s.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(s.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let 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||"{}"}})}}),$t=async()=>{const t=await v(l=>N.GET("/api/v1/automation-rules",{signal:l})),s=Ue(t,["data","rules","items"]);return ot(s)},Lt=async({cookieId:t,triggerType:s,enabled:l,search:x,page:r=1,pageSize:y=10}={})=>{const T=await v(P=>N.GET("/api/v1/automation-rules",{params:{query:{page:r,page_size:y,cookie_id:t,trigger_type:s,enabled:l,search:x==null?void 0:x.trim()}},signal:P})),R=Ae(T,["data","result"])||{},m=ot(Ue(T,["data","rules","items"]));return{success:!0,data:m,total:Number(R.total??m.length),page:Number(R.page??r),page_size:Number(R.page_size??y),total_pages:Number(R.total_pages??(m.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(R.trigger_counts||{}).map(([P,z])=>[P,Number(z)]))}},Dt=(t,s)=>{if(t!=="order_paid")return s.map((r,y)=>({...r,sort_order:r.sort_order||y+1}));const l=s.filter(r=>r.action_type==="send_card").map((r,y)=>({...r,sort_order:y+1})),x=s.filter(r=>r.action_type!=="send_card"&&r.action_type!=="confirm_shipment");return[...l,...x.map((r,y)=>({...r,sort_order:l.length+y+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+x.length+1}]},et=async t=>{const s=t.trigger_type||"order_paid",x=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[s]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),r=(t.actions||[]).filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment"),y=t.variants&&t.variants.length>0?[...t.variants.map((m,P)=>({action_type:"send_card",card_id:m.card_id,delivery_count:m.delivery_count||1,enabled:m.enabled!==!1,sort_order:P+1,delay_seconds:m.delay_seconds||0,config_json:JSON.stringify({spec_name:m.spec_name||"",spec_value:m.spec_value||"",delay_override:m.delay_override===!0})})),...r]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],T=Dt(s,y),R={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||x||"自动化规则",trigger_type:s,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:T.map((m,P)=>({action_type:m.action_type,card_id:m.card_id||0,delivery_count:m.delivery_count||1,message_template:m.message_template||"",delay_seconds:m.delay_seconds||0,config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:m.sort_order||P+1}))};return t.id?v(m=>N.PUT("/api/v1/automation-rules/{rule_id}",{params:{path:{rule_id:String(t.id)}},body:R,signal:m})):v(m=>N.POST("/api/v1/automation-rules",{body:R,signal:m}))},It=async t=>v(s=>N.DELETE("/api/v1/automation-rules/{rule_id}",{params:{path:{rule_id:t}},signal:s})),Ft=async()=>{const t=await v(l=>N.GET("/api/v1/automation-issues",{signal:l})),s=Ae(t,["data","result"])||{};return{runs:Array.isArray(s==null?void 0:s.runs)?s.runs:[],pending_tasks:Array.isArray(s==null?void 0:s.pending_tasks)?s.pending_tasks:[]}},zt=async(t,s)=>v(l=>N.POST("/api/v1/automation-runs/{run_id}/resolve",{params:{path:{run_id:String(t)}},body:{resolution:s},signal:l})),Ot=async(t,s)=>v(l=>N.POST("/api/v1/automation-pending-tasks/{task_id}/resolve",{params:{path:{task_id:String(t)}},body:{resolution:s},signal:l})),Gt=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),qt=async t=>{const s=await v(l=>N.GET("/api/v1/reply-rules/{cid}/typed",{params:{path:{cid:t}},signal:l}));return Ue(s,["data","items","rules"]).map(Gt)},Vt=async t=>t?(await qt(t)).map(l=>({id:l.id,keyword:l.keyword||"",reply_content:l.reply||"",match_type:"fuzzy",enabled:!0,item_id:l.item_id||"",type:l.type==="image"?"image":"text",image_url:l.image_url||""})):[],Bt=async(t,s)=>{const l=t.type||"text",x={keyword:t.keyword||"",reply:l==="text"&&t.reply_content||"",item_id:t.item_id||"",type:l,image_url:l==="image"&&t.image_url||""};return t.id?v(r=>N.PUT("/api/v1/reply-rules/{cid}/typed/{id}",{params:{path:{cid:s,id:String(t.id)}},body:x,signal:r})):v(r=>N.POST("/api/v1/reply-rules/{cid}/items",{params:{path:{cid:s}},body:x,signal:r}))},Ut=async(t,s)=>v(l=>N.DELETE("/api/v1/reply-rules/{cid}/typed/{id}",{params:{path:{cid:s,id:t}},signal:l})),tt=async()=>{const t=await v(s=>N.GET("/api/v1/default-replies",{signal:s}));return Ae(t,["data","replies","items"])||{}},Jt=async t=>{const s=await v(x=>N.GET("/api/v1/default-replies/{cid}",{params:{path:{cid:t}},signal:x})),l=Ae(s,["data","result"])||{};return{cookie_id:t,enabled:l.enabled||!1,reply_content:l.reply_content||"",reply_once:l.reply_once||!1,reply_image_url:l.reply_image_url||""}},Kt=async(t,s)=>v(l=>N.PUT("/api/v1/default-replies/{cid}",{params:{path:{cid:t}},body:{enabled:s.enabled??!1,reply_content:s.reply_content||"",reply_once:s.reply_once??!1,reply_image_url:s.reply_image_url||""},signal:l})),Wt=async t=>v(s=>N.DELETE("/api/v1/default-replies/{cid}",{params:{path:{cid:t}},signal:s})),Zt=async t=>v(s=>N.POST("/api/v1/default-replies/{cid}/clear-records",{params:{path:{cid:t}},body:{},signal:s})),Oe=()=>({submitting:!1,result:"idle"}),Ge=t=>t.submitting?t:{submitting:!0,result:"idle"},qe=(t,s)=>({...t,submitting:!1,result:s?"success":"failure"}),at=t=>t+1,Ve=(t,s,l,x)=>t===s&&l===x,Xt=t=>{const[s,l]=o.useState([]),[x,r]=o.useState({runs:[],pending_tasks:[]}),[y,T]=o.useState([]),[R,m]=o.useState({}),[P,z]=o.useState([]),[J,C]=o.useState([]),[K,I]=o.useState([]),[w,Q]=o.useState(!1),V=o.useRef(0),le=o.useRef(0),[Y,W]=o.useState(0),[ne,H]=o.useState(0),[B,ee]=o.useState({}),Z=o.useCallback(async()=>{const L=Promise.all([Et(),nt(),it(),tt()]),[_,j,F,te]=await L;z(_),C(j),I(F),m(te),t.setSelectedAccountId(ie=>{var G;return ie||((G=_[0])==null?void 0:G.id)||""})},[t.setSelectedAccountId]),i=o.useCallback(async()=>{var te;const L=at(V.current);V.current=L;const _=Ft().catch(ie=>(console.warn("加载自动化异常列表失败,不阻断规则展示",ie),null)),j=await Lt({cookieId:t.selectedAccountId||void 0,triggerType:t.automationTriggerFilter,enabled:t.automationStatusFilter==="all"?void 0:t.automationStatusFilter==="enabled",search:t.debouncedAutomationSearch,page:t.automationPage,pageSize:t.automationPageSize});if(!Ve(L,V.current,t.selectedAccountId,t.selectedAccountId))return;l(j.data),W(j.total),H(j.total_pages),ee(j.trigger_counts||{}),j.page!==t.automationPage&&((te=t.onAutomationPageChange)==null||te.call(t,j.page));const F=await _;Ve(L,V.current,t.selectedAccountId,t.selectedAccountId)&&F&&r(F)},[t.automationPage,t.automationPageSize,t.automationStatusFilter,t.automationTriggerFilter,t.debouncedAutomationSearch,t.onAutomationPageChange,t.selectedAccountId]),E=o.useCallback(async()=>{const L=at(le.current);le.current=L;const _=t.selectedAccountId;if(T([]),!_)return;const j=await Vt(_);Ve(L,le.current,_,t.selectedAccountId)&&T(j)},[t.selectedAccountId]),M=o.useCallback(async()=>{m(await tt())},[]),O=o.useCallback(async()=>{Q(!0);try{t.activeTab==="automation"?await i():t.activeTab==="reply"?await E():await M()}finally{Q(!1)}},[i,M,E,t.activeTab]);return{automationRules:s,automationIssues:x,replyRules:y,defaultReplies:R,accounts:P,cards:J,items:K,automationTotal:Y,automationTotalPages:ne,automationTriggerCounts:B,loading:w,setLoading:Q,setAutomationRules:l,setCards:C,setItems:I,loadReferenceData:Z,loadAutomationRules:i,loadReplyRules:E,loadDefaultReplies:M,refresh:O}},re={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:jt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:ft},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:lt}},Se=["order_paid","buyer_reviewed","review_missing_timeout"],Qt="亲,商品使用满意的话,麻烦给个评价,谢谢~",ye=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),dt=t=>{if(!t)return{};try{const s=JSON.parse(t);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}},me=(t,s={})=>{const l=dt(t);return JSON.stringify({after_shipped_hours:Number(l.after_shipped_hours||72),repeat_interval_hours:Number(l.repeat_interval_hours||24),max_attempts:Number(l.max_attempts||1),...s})},_e=(t,s)=>{var x;const l=((x=re[t])==null?void 0:x.label)||"自动化规则";return s?`${l} - ${s}`:l},st=t=>{const s=(t||"").trim();return s?Object.values(re).some(l=>s===l.label||s.startsWith(`${l.label} -`)):!0},fe=(t,s=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:Qt,enabled:!0,sort_order:1}];const l={action_type:"send_card",card_id:s,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[l,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[l]},Yt=t=>{var l,x;if(t.trigger_type==="review_missing_timeout")return((x=(l=t.actions)==null?void 0:l.find(r=>r.action_type==="send_text"))==null?void 0:x.message_template)||"发送求评价文案";const s=(t.actions||[]).filter(r=>r.action_type==="send_card");return s.length?s.map(r=>r.card_name||`卡密 ${r.card_id}`).join(" / "):"未配置卡密库存"},rt=(t,s=!1)=>{const l={blue:s?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:s?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:s?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return l[t]||l.blue},Ht=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Re=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",ea=t=>t===!0||t===1||t==="1",ta=({selectedAccountId:t,setSelectedAccountId:s,setActiveTab:l,items:x,setAutomationRules:r,setCards:y,setItems:T,setLoading:R,loadAutomationRules:m,loadReferenceData:P,loadReplyRules:z,loadDefaultReplies:J,initialDeliveryTarget:C,onDeliveryTargetHandled:K})=>{var ue;const[I,w]=o.useState(!1),[Q,V]=o.useState(!1),[le,Y]=o.useState(!1),[W,ne]=o.useState(Oe),[H,B]=o.useState(Oe),[ee,Z]=o.useState(Oe),[i,E]=o.useState(null),[M,O]=o.useState(null),[$,L]=o.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),_=o.useMemo(()=>i!=null&&i.cookie_id&&i.item_id?x.find(n=>n.cookie_id===i.cookie_id&&n.item_id===i.item_id):void 0,[i==null?void 0:i.cookie_id,i==null?void 0:i.item_id,x]),j=ea(_==null?void 0:_.is_multi_spec),F=(i==null?void 0:i.trigger_type)||"order_paid",te=re[F],ie=dt(i==null?void 0:i.config_json),G=(ue=i==null?void 0:i.variants)!=null&&ue.length?i.variants:[ye()],X=o.useCallback((n="order_paid",d=t,b="")=>{const p=x.find(k=>k.cookie_id===d&&k.item_id===b),h=(p==null?void 0:p.item_title)||b;return{name:_e(n,h),trigger_type:n,cookie_id:d,item_id:b,item_title:(p==null?void 0:p.item_title)||"",item_keyword:h,card_group_id:0,priority:100,enabled:!0,config_json:n==="review_missing_timeout"?me():"{}",actions:fe(n),variants:n==="review_missing_timeout"?[]:[ye()]}},[x,t]),pe=o.useCallback(n=>{var b,p;const d=n.trigger_type||"order_paid";E({...n,trigger_type:d,config_json:d==="review_missing_timeout"?me(n.config_json):n.config_json||"{}",actions:(b=n.actions)!=null&&b.length?n.actions.map(h=>({...h})):fe(d,n.card_group_id),variants:(p=n.variants)!=null&&p.length?n.variants.map(h=>({...h})):d==="review_missing_timeout"?[]:[ye()]}),w(!0)},[]);o.useEffect(()=>{if(!C)return;let n=!1;return(async()=>{l("automation"),s(C.cookieId),R(!0);try{const[b,p,h]=await Promise.all([$t(),it(),nt().catch(f=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",f),[]))]);if(n)return;r(b),T(p),y(h);const k=b.find(f=>f.cookie_id===C.cookieId&&f.item_id===C.itemId&&f.trigger_type==="order_paid");if(k)pe(k);else{const f=p.find(U=>U.cookie_id===C.cookieId&&U.item_id===C.itemId);E({...X("order_paid",C.cookieId,C.itemId),item_title:(f==null?void 0:f.item_title)||"",item_keyword:(f==null?void 0:f.item_title)||C.itemId,name:_e("order_paid",(f==null?void 0:f.item_title)||C.itemId)}),w(!0)}}catch(b){console.error("打开商品自动化规则失败",b),alert("无法加载该商品的自动化规则")}finally{n||(R(!1),K==null||K())}})(),(()=>{n=!0})},[X,C,K,pe,l,r,y,T,R,s]);const Me=o.useCallback((n="order_paid")=>{if(!t){alert("请先选择账号");return}E(X(n)),w(!0)},[X,t]),je=o.useCallback(n=>{var p,h,k,f,U;if(!i)return;const d=((h=(p=i.variants)==null?void 0:p.find(se=>se.card_id))==null?void 0:h.card_id)||((f=(k=i.actions)==null?void 0:k.find(se=>se.action_type==="send_card"))==null?void 0:f.card_id)||i.card_group_id||0,b=(_==null?void 0:_.item_title)||i.item_title||i.item_id||"";E({...i,trigger_type:n,name:st(i.name)?_e(n,b):i.name,card_group_id:d,config_json:n==="review_missing_timeout"?me(i.config_json):"{}",actions:fe(n,d),variants:n==="review_missing_timeout"?[]:(U=i.variants)!=null&&U.length?i.variants:[{...ye(),card_id:d}]})},[i,_]),Te=o.useCallback(n=>{if(!i)return;const d=x.find(p=>p.cookie_id===(i.cookie_id||t)&&p.item_id===n),b=(d==null?void 0:d.item_title)||n;E({...i,item_id:n,item_title:(d==null?void 0:d.item_title)||"",item_keyword:b,name:st(i.name)?_e(F,b):i.name})},[F,i,x,t]),ge=o.useCallback((n,d)=>{var p;if(!i)return;const b=G.map((h,k)=>k===n?{...h,...d}:h);E({...i,variants:b,card_group_id:((p=b[0])==null?void 0:p.card_id)||0})},[G,i]),Pe=o.useCallback(()=>{if(!i)return;const n=G[G.length-1];E({...i,variants:[...G,{...ye(),spec_name:j&&(n==null?void 0:n.spec_name)||"",spec_value:j&&(n==null?void 0:n.spec_value)||""}]})},[G,i,j]),ve=o.useCallback(async()=>{var h,k,f,U,se;if(!i||W.submitting)return;const n=i.trigger_type||"order_paid";if(!i.cookie_id)return alert("请选择账号");const d=(h=i.variants)!=null&&h.length?i.variants:[];if(n!=="review_missing_timeout"){if(!d.length||d.some(S=>!S.card_id))return alert(n==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");if(j&&d.some(S=>!S.spec_name.trim()||!S.spec_value.trim()))return alert("多规格商品必须填写每一行的规格名称和规格值")}if(n==="review_missing_timeout"&&!(((f=(k=i.actions)==null?void 0:k.find(Ee=>Ee.action_type==="send_text"))==null?void 0:f.message_template)||"").trim())return alert("请填写求评价文案");const b=n==="review_missing_timeout"?[]:d.map(S=>({...S,spec_name:j?S.spec_name.trim():"",spec_value:j?S.spec_value.trim():"",delivery_count:Math.max(1,Number(S.delivery_count)||1),enabled:S.enabled!==!1}));ne(Ge(W));let p=!1;try{await et({...i,trigger_type:n,name:(i.name||"").trim()||_e(n,(_==null?void 0:_.item_title)||i.item_id||""),config_json:n==="review_missing_timeout"?me(i.config_json):i.config_json||"{}",actions:(U=i.actions)!=null&&U.length?i.actions:fe(n,((se=b[0])==null?void 0:se.card_id)||i.card_group_id||0),variants:b}),w(!1),await Promise.all([m(),P()]),alert("保存成功"),p=!0}catch(S){console.error("保存自动化规则失败:",S),alert("保存失败:"+S.message)}finally{ne(S=>qe(S,p))}},[W,i,j,m,P,_]),g=o.useCallback(async n=>{if(confirm("确定删除该自动化规则吗?"))try{await It(n),await m(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[m]),q=o.useCallback(async n=>{try{await et({...n,enabled:!n.enabled}),await m()}catch(d){alert("操作失败:"+d.message)}},[m]),A=o.useCallback(async(n,d)=>{if(confirm(d==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":d==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await zt(n,d),await m()}catch(p){alert("处理失败:"+p.message)}},[m]),ae=o.useCallback(async(n,d)=>{if(confirm(d==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Ot(n,d),await m()}catch(b){alert("处理失败:"+b.message)}},[m]),D=o.useCallback(()=>{if(!t)return alert("请先选择账号");O({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),V(!0)},[t]),oe=o.useCallback(async()=>{var b,p,h;if(!M||!t||H.submitting)return;const n=M.type==="image"?!!((b=M.image_url)!=null&&b.trim()):!!((p=M.reply_content)!=null&&p.trim());if(!((h=M.keyword)!=null&&h.trim())||!n)return alert("请填写关键词和回复内容");B(Ge(H));let d=!1;try{await Bt({...M,match_type:"fuzzy",enabled:!0},t),V(!1),await z(),alert("保存成功"),d=!0}catch(k){alert("保存失败:"+k.message)}finally{B(k=>qe(k,d))}},[M,z,H,t]),be=o.useCallback(async n=>{if(!(!t||!confirm("确定删除该回复规则吗?")))try{await Ut(n,t),await z(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[z,t]),de=o.useCallback(async(n=t)=>{if(!n)return alert("请先选择账号");try{const d=await Jt(n);L({cookie_id:n,enabled:d.enabled,reply_content:d.reply_content,reply_once:d.reply_once,reply_image_url:d.reply_image_url||""})}catch{L({cookie_id:n,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}Y(!0)},[t]),xe=o.useCallback(async()=>{if(ee.submitting)return;if(!$.cookie_id)return alert("请先选择账号");if($.enabled&&!$.reply_content.trim()&&!$.reply_image_url.trim())return alert("启用默认回复时,请填写回复内容或图片 URL");Z(Ge(ee));let n=!1;try{await Kt($.cookie_id,{enabled:$.enabled,reply_content:$.reply_content,reply_once:$.reply_once,reply_image_url:$.reply_image_url}),Y(!1),await J(),alert("保存成功"),n=!0}catch(d){alert("保存失败:"+d.message)}finally{Z(d=>qe(d,n))}},[$,ee,J]),Ne=o.useCallback(async n=>{if(confirm("确定删除该账号默认回复吗?"))try{await Wt(n),await J(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[J]),he=o.useCallback(async n=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Zt(n),alert("清空成功")}catch(d){alert("清空失败:"+d.message)}},[]);return{showAutomationModal:I,setShowAutomationModal:w,showReplyModal:Q,setShowReplyModal:V,showDefaultModal:le,setShowDefaultModal:Y,automationSubmitState:W,replySubmitState:H,defaultReplySubmitState:ee,editingAutomationRule:i,setEditingAutomationRule:E,editingReplyRule:M,setEditingReplyRule:O,defaultForm:$,setDefaultForm:L,selectedRuleItem:_,isMultiSpecRule:j,currentTrigger:F,currentMeta:te,reviewConfig:ie,displayVariants:G,buildAutomationDraft:X,openAutomationRule:pe,openNewAutomationRule:Me,handleTriggerChange:je,handleAutomationItemChange:Te,updateVariant:ge,appendDeliveryContent:Pe,handleSaveAutomationRule:ve,handleDeleteAutomation:g,handleToggleAutomation:q,handleResolveRunIssue:A,handleResolveDeferredIssue:ae,handleAddReplyRule:D,handleSaveReplyRule:oe,handleDeleteReply:be,openDefaultReplyModal:de,handleSaveDefaultReply:xe,handleDeleteDefaultReply:Ne,handleClearDefaultReplyRecords:he}},ia=({initialDeliveryTarget:t,onDeliveryTargetHandled:s})=>{var We,Ze;const[l,x]=o.useState("automation"),[r,y]=o.useState(""),[T,R]=o.useState(""),[m,P]=o.useState(""),[z,J]=o.useState(""),[C,K]=o.useState("all"),[I,w]=o.useState(1),[Q,V]=o.useState(10),le=Xt({activeTab:l,selectedAccountId:r,automationTriggerFilter:z,automationStatusFilter:C,debouncedAutomationSearch:m,automationPage:I,automationPageSize:Q,setSelectedAccountId:y,onAutomationPageChange:w}),{automationRules:Y,automationIssues:W,replyRules:ne,defaultReplies:H,accounts:B,cards:ee,items:Z,loading:i,setLoading:E,automationTotal:M,automationTotalPages:O,automationTriggerCounts:$,setAutomationRules:L,setCards:_,setItems:j,loadReferenceData:F,loadAutomationRules:te,loadReplyRules:ie,loadDefaultReplies:G,refresh:X}=le,pe=ta({selectedAccountId:r,setSelectedAccountId:y,setActiveTab:x,items:Z,setAutomationRules:L,setCards:_,setItems:j,setLoading:E,loadAutomationRules:te,loadReferenceData:F,loadReplyRules:ie,loadDefaultReplies:G,initialDeliveryTarget:t,onDeliveryTargetHandled:s}),{showAutomationModal:Me,setShowAutomationModal:je,showReplyModal:Te,setShowReplyModal:ge,showDefaultModal:Pe,setShowDefaultModal:ve,editingAutomationRule:g,setEditingAutomationRule:q,editingReplyRule:A,setEditingReplyRule:ae,defaultForm:D,setDefaultForm:oe,selectedRuleItem:be,isMultiSpecRule:de,currentTrigger:xe,currentMeta:Ne,reviewConfig:he,displayVariants:ue,openAutomationRule:n,openNewAutomationRule:d,handleTriggerChange:b,handleAutomationItemChange:p,updateVariant:h,appendDeliveryContent:k,handleSaveAutomationRule:f,handleDeleteAutomation:U,handleToggleAutomation:se,handleResolveRunIssue:S,handleResolveDeferredIssue:Ee,handleAddReplyRule:ct,handleSaveReplyRule:mt,handleDeleteReply:xt,openDefaultReplyModal:Je,handleSaveDefaultReply:ut,handleDeleteDefaultReply:pt,handleClearDefaultReplyRecords:gt}=pe;o.useEffect(()=>{const a=window.setTimeout(()=>{w(1),P(T.trim())},300);return(()=>window.clearTimeout(a))},[T]),o.useEffect(()=>{F().catch(a=>console.error("加载规则参考数据失败",a))},[F]),o.useEffect(()=>{X().catch(a=>console.error("刷新规则页面失败",a))},[X]);const $e=o.useMemo(()=>Y.filter(a=>!r||a.cookie_id===r),[Y,r]),we=o.useMemo(()=>Mt(W,r),[W,r]),Ke=o.useMemo(()=>B.filter(a=>!r||a.id===r),[B,r]),bt=o.useMemo(()=>{if(O<=1)return[];const a=Math.max(1,Math.min(I-2,O-4)),c=Math.min(O,a+4);return Array.from({length:c-a+1},(u,ce)=>a+ce)},[I,O]),Le=!!(T.trim()||z||C!=="all"),ht=()=>{R(""),P(""),J(""),K("all"),w(1)},yt=o.useMemo(()=>{const a=(g==null?void 0:g.cookie_id)||r;return Z.filter(c=>c.cookie_id===a)},[g==null?void 0:g.cookie_id,Z,r]),_t=l==="automation"?"新建自动化":l==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"min-w-0 space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap gap-3",children:[e.jsxs("select",{value:r,onChange:(a=>{y(a.target.value),w(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),B.map(a=>e.jsx("option",{value:a.id,children:Re(a)},a.id))]}),e.jsxs("button",{onClick:X,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 whitespace-nowrap transition-colors",children:[e.jsx(Ie,{className:`w-4 h-4 ${i?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:l==="automation"?(()=>d("order_paid")):l==="reply"?ct:(()=>void Je()),disabled:!r,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50",children:[e.jsx(Xe,{className:"w-4 h-4"}),_t]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Qe},{id:"reply",label:"关键词回复",icon:vt},{id:"default",label:"账号默认回复",icon:Ye}].map(a=>{const c=a.icon;return e.jsxs("button",{onClick:(()=>x(a.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${l===a.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(c,{className:"w-4 h-4"}),a.label]},a.id)})}),l==="automation"&&(we.runs.length>0||we.pending_tasks.length>0)&&e.jsx(Pt,{runs:we.runs,pendingTasks:we.pending_tasks,onResolveRun:((a,c)=>void S(a,c)),onResolveDeferredTask:((a,c)=>void Ee(a,c))}),l==="automation"&&e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]",children:[e.jsxs("aside",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:Se.map(a=>{const c=re[a],u=c.icon;return e.jsx("button",{type:"button",onClick:(()=>d(a)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${rt(c.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(u,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:c.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:c.description})]})]})},a)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-black text-gray-900",children:"筛选结果构成"}),e.jsxs("span",{className:"text-xs font-bold text-gray-400",children:["共 ",M," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Se.map(a=>{const c=re[a],u=c.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(u,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:c.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:$[a]||0})]},a)})})]})]}),e.jsxs("section",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(Nt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"搜索自动化规则",placeholder:"搜索规则名、商品名或商品 ID...",value:T,onChange:(a=>{R(a.target.value),w(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]}),e.jsxs("div",{className:"relative xl:w-52",children:[e.jsx(wt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按自动化类型筛选",value:z,onChange:(a=>{J(a.target.value),w(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部自动化类型"}),Se.map(a=>e.jsx("option",{value:a,children:re[a].shortLabel},a))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:C,onChange:(a=>{K(a.target.value),w(1)}),className:"ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36",children:[e.jsx("option",{value:"all",children:"全部状态"}),e.jsx("option",{value:"enabled",children:"已启用"}),e.jsx("option",{value:"disabled",children:"已禁用"})]}),Le&&e.jsx("button",{type:"button",onClick:ht,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900",title:"清除筛选","aria-label":"清除筛选",children:e.jsx(ke,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs font-bold text-gray-400",children:[e.jsxs("span",{children:["找到 ",M," 条规则"]}),i&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Ie,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),i&&$e.length===0?e.jsxs("div",{className:"flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400",children:[e.jsx(Ie,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):$e.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Qe,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:Le?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:Le?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):$e.map(a=>{const c=re[a.trigger_type],u=c.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${rt(c.accent,!0)}`,children:e.jsx(u,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:a.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Ht(a.enabled)}`,children:a.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:c.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:a.item_title||a.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Yt(a)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>n(a)),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(Fe,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>se(a)),className:`px-4 py-2 rounded-xl text-sm font-bold ${a.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:a.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>U(a.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ce,{className:"w-4 h-4"})})]})]})},a.id)}),M>0&&e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-gray-500",children:[e.jsxs("span",{children:["第 ",I," / ",Math.max(O,1)," 页"]}),e.jsx("span",{className:"h-4 w-px bg-gray-200"}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"sr-only",children:"每页显示数量"}),e.jsx("select",{value:Q,onChange:(a=>{V(Number(a.target.value)),w(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(a=>e.jsxs("option",{value:a,children:[a," 条/页"]},a))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:I<=1||i,onClick:(()=>w(a=>Math.max(1,a-1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"上一页",title:"上一页",children:e.jsx(kt,{className:"h-4 w-4"})}),bt.map(a=>e.jsx("button",{type:"button",disabled:i,onClick:(()=>w(a)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${a===I?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${a} 页`,"aria-current":a===I?"page":void 0,children:a},a)),e.jsx("button",{type:"button",disabled:I>=O||i,onClick:(()=>w(a=>Math.min(O,a+1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"下一页",title:"下一页",children:e.jsx(Ct,{className:"h-4 w-4"})})]})]})]})]}),l==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Be,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[ne.map(a=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",a.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:a.type==="image"&&a.image_url?a.image_url:a.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>{ae({...a}),ge(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(Fe,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>xt(a.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]},a.id)),ne.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),l==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Be,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Ke.map(a=>{const c=H[a.id],u=!!(c!=null&&c.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${u?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${u?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(Ye,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:Re(a)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${u?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:u?"已启用":"未启用"}),(c==null?void 0:c.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:u?c.reply_content||c.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>void Je(a.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(Fe,{className:"w-4 h-4"})}),u&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void gt(a.id)),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:(()=>void pt(a.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]})]},a.id)}),Ke.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),Me&&g&&De.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:g.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:Ne.description})]}),e.jsx("button",{onClick:(()=>je(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:Se.map(a=>{const c=re[a],u=c.icon,ce=xe===a;return e.jsx("button",{type:"button",onClick:(()=>b(a)),className:`w-full rounded-2xl p-4 text-left border transition-all ${ce?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(u,{className:`w-5 h-5 mt-0.5 ${ce?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:c.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${ce?"text-gray-500":"text-gray-400"}`,children:c.description})]})]})},a)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:Ne.flow.map((a,c)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:c+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:a})]},a))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-surface-subtle",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(St,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:g.name||"",onChange:(a=>q({...g,name:a.target.value})),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:g.cookie_id||"",onChange:(a=>q({...g,cookie_id:a.target.value,item_id:"",item_title:"",item_keyword:""})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),B.map(a=>e.jsx("option",{value:a.id,children:Re(a)},a.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:g.item_id||"",onChange:(a=>p(a.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),yt.map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]})]}),be&&xe!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:be.item_title||be.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${de?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:de?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),xe!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rt,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:xe==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:de?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:k,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Xe,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:ue.map((a,c)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${de?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[de&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:a.spec_name,onChange:(u=>h(c,{spec_name:u.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:a.spec_value,onChange:(u=>h(c,{spec_value:u.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:a.card_id||"",onChange:(u=>h(c,{card_id:Number(u.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),ee.filter(u=>u.enabled&&u.type!=="api").map(u=>e.jsx("option",{value:u.id,children:u.name},u.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:a.delivery_count,onChange:(u=>h(c,{delivery_count:Math.max(1,Number(u.target.value)||1)})),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:a.delay_override===!0,onChange:(u=>h(c,{delay_override:u.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),a.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:a.delay_seconds||0,onChange:(u=>h(c,{delay_seconds:Math.max(0,Number(u.target.value)||0)})),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:a.delay_override?`本动作延时 ${a.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:ue.length===1,onClick:(()=>q({...g,variants:ue.filter((u,ce)=>ce!==c)})),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(Ce,{className:"w-4 h-4"})})]},a.id||c))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(lt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(he.after_shipped_hours||72),onChange:(a=>q({...g,config_json:me(g.config_json,{after_shipped_hours:Math.max(1,Number(a.target.value)||72)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(he.repeat_interval_hours||24),onChange:(a=>q({...g,config_json:me(g.config_json,{repeat_interval_hours:Math.max(1,Number(a.target.value)||24)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(he.max_attempts||1),onChange:(a=>q({...g,config_json:me(g.config_json,{max_attempts:Math.max(1,Number(a.target.value)||1)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((Ze=(We=g.actions)==null?void 0:We.find(a=>a.action_type==="send_text"))==null?void 0:Ze.message_template)||"",onChange:(a=>{var c;return q({...g,actions:((c=g.actions)!=null&&c.length?g.actions:fe("review_missing_timeout")).map(u=>u.action_type==="send_text"?{...u,message_template:a.target.value}:u)})}),className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:g.priority||100,onChange:(a=>q({...g,priority:Number(a.target.value)||100})),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:g.enabled!==!1,onChange:(a=>q({...g,enabled:a.target.checked})),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:(()=>je(!1)),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Te&&A&&De.createPortal(e.jsx("div",{className:"modal-overlay",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:A.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>ge(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:A.item_id||"",onChange:(a=>ae({...A,item_id:a.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),Z.filter(a=>!r||a.cookie_id===r).map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:A.type||"text",onChange:(a=>{const c=a.target.value;ae({...A,type:c,reply_content:c==="text"?A.reply_content:"",image_url:c==="image"?A.image_url:""})}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:A.keyword||"",onChange:(a=>ae({...A,keyword:a.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),A.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:A.image_url||"",onChange:(a=>ae({...A,image_url:a.target.value})),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:A.reply_content||"",onChange:(a=>ae({...A,reply_content:a.target.value})),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ge(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:mt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(At,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Pe&&De.createPortal(e.jsx("div",{className:"modal-overlay",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.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:(()=>ve(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:D.cookie_id,onChange:(a=>oe({...D,cookie_id:a.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),B.map(a=>e.jsx("option",{value:a.id,children:Re(a)},a.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:(()=>oe({...D,enabled:!D.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${D.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${D.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:D.reply_content,onChange:(a=>oe({...D,reply_content:a.target.value})),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:D.reply_image_url,onChange:(a=>oe({...D,reply_image_url:a.target.value})),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:D.reply_once,onChange:(a=>oe({...D,reply_once:a.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ve(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})};export{ia as default}; diff --git a/internal/webui/static/assets/Settings-WRDun9wT.js b/internal/webui/static/assets/Settings-CQ_-2bDk.js similarity index 99% rename from internal/webui/static/assets/Settings-WRDun9wT.js rename to internal/webui/static/assets/Settings-CQ_-2bDk.js index 477f761..d47b695 100644 --- a/internal/webui/static/assets/Settings-WRDun9wT.js +++ b/internal/webui/static/assets/Settings-CQ_-2bDk.js @@ -1 +1 @@ -import{a as r,j as e}from"./react-vendor-l-BBvuKH.js";import{r as M,a as q}from"./index-WrujSo30.js";import{f as xe,R as ae,aa as ue,r as pe,z as T,F as D,ab as me,t as he,S as re,ac as le,ad as ge,o as ye}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",fe=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],be=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"]),we=s=>{if("values"in s||"secrets"in s)return s;const a={},n={};for(const[d,x]of Object.entries(s))if(x!=null){if(oe.has(d)){n[d]=x===""?{action:"clear"}:{action:"replace",value:String(x)};continue}(typeof x=="string"||typeof x=="number"||typeof x=="boolean")&&(a[d]=x)}return Object.keys(n).length>0?{values:a,secrets:n}:a},je=s=>{const a={...s};for(const n of oe){const d=`${n}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const n=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(n)?n:10}return a},ve=async(s,a)=>M(n=>q.PUT("/api/v1/session/credentials",{body:s,signal:n}),a),_e=async s=>{const a=await M(n=>q.GET("/api/v1/settings/system",{signal:n}),s);return je(a)},Ne=async(s,a)=>M(n=>q.PUT("/api/v1/settings/system",{body:we(s),signal:n}),a),Se=async(s,a="",n)=>{const d=await M(x=>q.POST("/api/v1/settings/ai-models",{body:{base_url:s,api_key:a},signal:x}),n);return Array.isArray(d.models)?d.models:[]},ke=async s=>M(a=>q.GET("/api/v1/session",{signal:a}),s),Ce=s=>Object.fromEntries(Object.entries(s).filter(([a,n])=>!be.has(a)&&n!==void 0&&n!==null)),Ee=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,n)=>s===a&&!n.aborted,K=s=>s instanceof Error&&s.message==="请求已取消",U=(s,a)=>s instanceof Error?s.message:a,Ae=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),$=(s,a)=>({type:s,text:a}),Ie=()=>{const[s,a]=r.useState(null),[n,d]=r.useState(!1),[x,m]=r.useState(""),[S,A]=r.useState(!1),[R,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[P,u]=r.useState(""),[z,v]=r.useState(!1),[G,L]=r.useState(!1),[F,p]=r.useState(!1),[b,V]=r.useState(!1),[Y,J]=r.useState(!1),[W,_]=r.useState(!1),[O,y]=r.useState(null),[t,ee]=r.useState(()=>Ae()),[ce,B]=r.useState("idle"),se=r.useRef(null),te=r.useRef(null),h=r.useRef(0),H=r.useRef(null);te.current=s;const E=r.useCallback(()=>{var c;(c=H.current)==null||c.abort();const o=new AbortController;return H.current=o,h.current+=1,{controller:o,sequence:h.current}},[]),Q=r.useCallback(async(o,c=!1,l)=>{const i=o||te.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),u("");try{const N=await Se(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(Z=>Z&&{...Z,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||K(N))return;w([]),v(!1),u(U(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),X=r.useCallback(()=>{const{controller:o,sequence:c}=E();d(!0),B("loading"),m(""),Promise.all([_e({signal:o.signal}),ke({signal:o.signal})]).then(([l,i])=>{f(h.current,c,o.signal)&&(a(l),i.username&&ee(g=>({...g,new_username:i.username||""})),Q(l,!1,o.signal),B("success"))}).catch(l=>{!f(h.current,c,o.signal)||K(l)||(a(null),m(U(l,"加载配置失败")),B("error"))}).finally(()=>{f(h.current,c,o.signal)&&d(!1)})},[E,Q]);r.useEffect(()=>(X(),(()=>{var o;return(o=H.current)==null?void 0:o.abort()})),[X]),r.useEffect(()=>{const o=c=>{var l;(l=se.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",o),(()=>document.removeEventListener("mousedown",o))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:o,sequence:c}=E();A(!0),k("");try{if(await Ne(Ce(s),{signal:o.signal}),!f(h.current,c,o.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(h.current,c,o.signal)||K(l))return;k(U(l,"保存配置失败"))}finally{f(h.current,c,o.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async o=>{o.preventDefault(),y(null);const c=Ee(t);if(c){y($("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await ve({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(h.current,i,l.signal))return;if(!g.success){y($("error",g.message||"登录凭据更新失败"));return}y($("success",g.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(g){if(!f(h.current,i,l.signal)||K(g))return;y($("error",U(g,"登录凭据更新失败")))}finally{f(h.current,i,l.signal)&&_(!1)}},[E,t]);return{settings:s,loading:n,loadError:x,saving:S,saveError:R,aiModels:C,modelsLoading:j,modelError:P,modelDropdownOpen:z,showApiKey:G,showCaptchaSecret:F,showCurrentPassword:b,showNewPassword:Y,credentialsSaving:W,credentialsMessage:O,credentials:t,requestStatus:ce,modelPickerRef:se,loadSettings:X,loadAIModels:((o,c)=>void Q(o,c)),handleSave:ie,handleCredentialsSave:de,setSettings:a,setModelDropdownOpen:v,setShowApiKey:L,setShowCaptchaSecret:p,setShowCurrentPassword:V,setShowNewPassword:J,setCredentials:ee,setCredentialsMessage:y}},Le=()=>{const{settings:s,loading:a,loadError:n,saving:d,saveError:x,aiModels:m,modelsLoading:S,modelError:A,modelDropdownOpen:R,showApiKey:k,showCaptchaSecret:C,showCurrentPassword:w,showNewPassword:j,credentialsSaving:I,credentialsMessage:P,credentials:u,modelPickerRef:z,loadSettings:v,loadAIModels:G,handleSave:L,handleCredentialsSave:F,setSettings:p,setModelDropdownOpen:b,setShowApiKey:V,setShowCaptchaSecret:Y,setShowCurrentPassword:J,setShowNewPassword:W,setCredentials:_}=Ie();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[n||(a?"加载配置中...":"暂无配置"),!a&&n&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:v,children:"重新加载"})})]});const O=s.ai_model||"",y=m;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(xe,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:v,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(ae,{className:"w-4 h-4"}),"刷新"]})]}),x&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:x}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>{}),children:"重试保存"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(ue,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:(t=>p({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:fe.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:(t=>p({...s,log_format:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:(t=>p({...s,renewal_log_retention_days:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-brand text-white",children:e.jsx(pe,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||ne,onChange:(t=>p({...s,ai_api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:k?"text":"password",value:s.ai_api_key||"",onChange:(t=>p({...s,ai_api_key:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:s.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>V(!k)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:k?e.jsx(T,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:z,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:O,onFocus:(()=>m.length>0&&b(!0)),onChange:(t=>{p({...s,ai_model:t.target.value}),m.length>0&&b(!0)}),onKeyDown:(t=>{t.key==="Escape"&&b(!1),t.key==="ArrowDown"&&m.length>0&&b(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>m.length>0&&b(t=>!t)),disabled:m.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(me,{className:`w-4 h-4 transition-transform ${R?"rotate-180":""}`})}),R&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:y.length>0?y.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{p({...s,ai_model:t}),b(!1)}),className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:t}),t===O&&e.jsx(he,{className:"w-4 h-4 shrink-0 text-brand"})]},t)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>G(void 0,!0)),disabled:S,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(ae,{className:`w-4 h-4 ${S?"animate-spin":""}`}),"读取模型"]})]}),A?e.jsx("p",{className:"text-xs text-red-500",children:A}):e.jsx("p",{className:"text-xs text-gray-500",children:m.length>0?`已从当前 API 地址读取到 ${m.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(re,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:(t=>p({...s,"captcha.remote_service_url":t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:C?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>p({...s,"captcha.remote_secret_key":t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:s["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>Y(!C)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:C?"隐藏秘钥":"显示秘钥",children:C?e.jsx(T,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(t=>p({...s,"captcha.remote_pass_cookies":t.target.checked})),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(le,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:F,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:u.new_username,onChange:(t=>_({...u,new_username:t.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:w?"text":"password",value:u.current_password,onChange:(t=>_({...u,current_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:(()=>J(!w)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:w?"隐藏密码":"显示密码",children:w?e.jsx(T,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:j?"text":"password",value:u.new_password,onChange:(t=>_({...u,new_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:(()=>W(!j)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:j?"隐藏密码":"显示密码",children:j?e.jsx(T,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:j?"text":"password",value:u.confirm_password,onChange:(t=>_({...u,confirm_password:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),P&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${P.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(re,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:P.text})]}),e.jsxs("button",{type:"submit",disabled:I||!u.new_username||!u.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(le,{className:"w-4 h-4"}),I?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:L,disabled:d,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(ye,{className:"w-6 h-6"}),d?"保存中...":"保存所有配置"]})})]})};export{Le as default}; +import{a as r,j as e}from"./react-vendor-l-BBvuKH.js";import{r as M,c as q}from"./index-CiBUw4Te.js";import{f as xe,R as ae,aa as ue,r as pe,z as T,F as D,ab as me,t as he,S as re,ac as le,ad as ge,o as ye}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",fe=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],be=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"]),we=s=>{if("values"in s||"secrets"in s)return s;const a={},n={};for(const[d,x]of Object.entries(s))if(x!=null){if(oe.has(d)){n[d]=x===""?{action:"clear"}:{action:"replace",value:String(x)};continue}(typeof x=="string"||typeof x=="number"||typeof x=="boolean")&&(a[d]=x)}return Object.keys(n).length>0?{values:a,secrets:n}:a},je=s=>{const a={...s};for(const n of oe){const d=`${n}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const n=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(n)?n:10}return a},ve=async(s,a)=>M(n=>q.PUT("/api/v1/session/credentials",{body:s,signal:n}),a),_e=async s=>{const a=await M(n=>q.GET("/api/v1/settings/system",{signal:n}),s);return je(a)},Ne=async(s,a)=>M(n=>q.PUT("/api/v1/settings/system",{body:we(s),signal:n}),a),Se=async(s,a="",n)=>{const d=await M(x=>q.POST("/api/v1/settings/ai-models",{body:{base_url:s,api_key:a},signal:x}),n);return Array.isArray(d.models)?d.models:[]},ke=async s=>M(a=>q.GET("/api/v1/session",{signal:a}),s),Ce=s=>Object.fromEntries(Object.entries(s).filter(([a,n])=>!be.has(a)&&n!==void 0&&n!==null)),Ee=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,n)=>s===a&&!n.aborted,K=s=>s instanceof Error&&s.message==="请求已取消",U=(s,a)=>s instanceof Error?s.message:a,Ae=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),$=(s,a)=>({type:s,text:a}),Ie=()=>{const[s,a]=r.useState(null),[n,d]=r.useState(!1),[x,m]=r.useState(""),[S,A]=r.useState(!1),[R,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[P,u]=r.useState(""),[z,v]=r.useState(!1),[G,L]=r.useState(!1),[F,p]=r.useState(!1),[b,V]=r.useState(!1),[Y,J]=r.useState(!1),[W,_]=r.useState(!1),[O,y]=r.useState(null),[t,ee]=r.useState(()=>Ae()),[ce,B]=r.useState("idle"),se=r.useRef(null),te=r.useRef(null),h=r.useRef(0),H=r.useRef(null);te.current=s;const E=r.useCallback(()=>{var c;(c=H.current)==null||c.abort();const o=new AbortController;return H.current=o,h.current+=1,{controller:o,sequence:h.current}},[]),Q=r.useCallback(async(o,c=!1,l)=>{const i=o||te.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),u("");try{const N=await Se(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(Z=>Z&&{...Z,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||K(N))return;w([]),v(!1),u(U(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),X=r.useCallback(()=>{const{controller:o,sequence:c}=E();d(!0),B("loading"),m(""),Promise.all([_e({signal:o.signal}),ke({signal:o.signal})]).then(([l,i])=>{f(h.current,c,o.signal)&&(a(l),i.username&&ee(g=>({...g,new_username:i.username||""})),Q(l,!1,o.signal),B("success"))}).catch(l=>{!f(h.current,c,o.signal)||K(l)||(a(null),m(U(l,"加载配置失败")),B("error"))}).finally(()=>{f(h.current,c,o.signal)&&d(!1)})},[E,Q]);r.useEffect(()=>(X(),(()=>{var o;return(o=H.current)==null?void 0:o.abort()})),[X]),r.useEffect(()=>{const o=c=>{var l;(l=se.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",o),(()=>document.removeEventListener("mousedown",o))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:o,sequence:c}=E();A(!0),k("");try{if(await Ne(Ce(s),{signal:o.signal}),!f(h.current,c,o.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(h.current,c,o.signal)||K(l))return;k(U(l,"保存配置失败"))}finally{f(h.current,c,o.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async o=>{o.preventDefault(),y(null);const c=Ee(t);if(c){y($("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await ve({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(h.current,i,l.signal))return;if(!g.success){y($("error",g.message||"登录凭据更新失败"));return}y($("success",g.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(g){if(!f(h.current,i,l.signal)||K(g))return;y($("error",U(g,"登录凭据更新失败")))}finally{f(h.current,i,l.signal)&&_(!1)}},[E,t]);return{settings:s,loading:n,loadError:x,saving:S,saveError:R,aiModels:C,modelsLoading:j,modelError:P,modelDropdownOpen:z,showApiKey:G,showCaptchaSecret:F,showCurrentPassword:b,showNewPassword:Y,credentialsSaving:W,credentialsMessage:O,credentials:t,requestStatus:ce,modelPickerRef:se,loadSettings:X,loadAIModels:((o,c)=>void Q(o,c)),handleSave:ie,handleCredentialsSave:de,setSettings:a,setModelDropdownOpen:v,setShowApiKey:L,setShowCaptchaSecret:p,setShowCurrentPassword:V,setShowNewPassword:J,setCredentials:ee,setCredentialsMessage:y}},Le=()=>{const{settings:s,loading:a,loadError:n,saving:d,saveError:x,aiModels:m,modelsLoading:S,modelError:A,modelDropdownOpen:R,showApiKey:k,showCaptchaSecret:C,showCurrentPassword:w,showNewPassword:j,credentialsSaving:I,credentialsMessage:P,credentials:u,modelPickerRef:z,loadSettings:v,loadAIModels:G,handleSave:L,handleCredentialsSave:F,setSettings:p,setModelDropdownOpen:b,setShowApiKey:V,setShowCaptchaSecret:Y,setShowCurrentPassword:J,setShowNewPassword:W,setCredentials:_}=Ie();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[n||(a?"加载配置中...":"暂无配置"),!a&&n&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:v,children:"重新加载"})})]});const O=s.ai_model||"",y=m;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(xe,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:v,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(ae,{className:"w-4 h-4"}),"刷新"]})]}),x&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:x}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>{}),children:"重试保存"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(ue,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:(t=>p({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:fe.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:(t=>p({...s,log_format:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:(t=>p({...s,renewal_log_retention_days:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-brand text-white",children:e.jsx(pe,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||ne,onChange:(t=>p({...s,ai_api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:k?"text":"password",value:s.ai_api_key||"",onChange:(t=>p({...s,ai_api_key:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:s.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>V(!k)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:k?e.jsx(T,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:z,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:O,onFocus:(()=>m.length>0&&b(!0)),onChange:(t=>{p({...s,ai_model:t.target.value}),m.length>0&&b(!0)}),onKeyDown:(t=>{t.key==="Escape"&&b(!1),t.key==="ArrowDown"&&m.length>0&&b(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>m.length>0&&b(t=>!t)),disabled:m.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(me,{className:`w-4 h-4 transition-transform ${R?"rotate-180":""}`})}),R&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:y.length>0?y.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{p({...s,ai_model:t}),b(!1)}),className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:t}),t===O&&e.jsx(he,{className:"w-4 h-4 shrink-0 text-brand"})]},t)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>G(void 0,!0)),disabled:S,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(ae,{className:`w-4 h-4 ${S?"animate-spin":""}`}),"读取模型"]})]}),A?e.jsx("p",{className:"text-xs text-red-500",children:A}):e.jsx("p",{className:"text-xs text-gray-500",children:m.length>0?`已从当前 API 地址读取到 ${m.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(re,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:(t=>p({...s,"captcha.remote_service_url":t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:C?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>p({...s,"captcha.remote_secret_key":t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:s["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>Y(!C)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:C?"隐藏秘钥":"显示秘钥",children:C?e.jsx(T,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(t=>p({...s,"captcha.remote_pass_cookies":t.target.checked})),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(le,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:F,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(ge,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:u.new_username,onChange:(t=>_({...u,new_username:t.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:w?"text":"password",value:u.current_password,onChange:(t=>_({...u,current_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:(()=>J(!w)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:w?"隐藏密码":"显示密码",children:w?e.jsx(T,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:j?"text":"password",value:u.new_password,onChange:(t=>_({...u,new_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:(()=>W(!j)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:j?"隐藏密码":"显示密码",children:j?e.jsx(T,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:j?"text":"password",value:u.confirm_password,onChange:(t=>_({...u,confirm_password:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),P&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${P.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(re,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:P.text})]}),e.jsxs("button",{type:"submit",disabled:I||!u.new_username||!u.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(le,{className:"w-4 h-4"}),I?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:L,disabled:d,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(ye,{className:"w-6 h-6"}),d?"保存中...":"保存所有配置"]})})]})};export{Le as default}; diff --git a/internal/webui/static/assets/contract-COFcZjyb.js b/internal/webui/static/assets/contract-COFcZjyb.js new file mode 100644 index 0000000..35184fc --- /dev/null +++ b/internal/webui/static/assets/contract-COFcZjyb.js @@ -0,0 +1 @@ +const a=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),i=(t,s=["data","items","results"])=>{let r=t,e=0;for(;e<2;e+=1){if(Array.isArray(r))return r;if(!a(r))return[];for(const n of s){const c=r[n];if(Array.isArray(c))return c;if(c===null)return[]}const o=r.data;if(a(o)){r=o;continue}return[]}return[]},d=(t,s=["data","result"])=>{let r=t,e=0;for(;e<2;e+=1){if(!a(r))return;for(const o of s){const n=r[o];if(a(n))return n}return r}};export{i as c,d as o}; diff --git a/internal/webui/static/assets/index-CiBUw4Te.js b/internal/webui/static/assets/index-CiBUw4Te.js new file mode 100644 index 0000000..e1fec6d --- /dev/null +++ b/internal/webui/static/assets/index-CiBUw4Te.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-CJrI6NVV.js","assets/react-vendor-l-BBvuKH.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-Bgrth_9N.js","assets/charts-vendor-DlHaeEQJ.js","assets/vendor-cRYyTeIw.js","assets/vendor-DUblxfbA.css","assets/contract-COFcZjyb.js","assets/AccountList-DX3reM6l.js","assets/OrderList-B4B8_a2q.js","assets/CardList-DDZ2JnUG.js","assets/ItemList-C0hxXhgx.js","assets/Settings-CQ_-2bDk.js","assets/Rules-CMO3kj4s.js","assets/Notifications-BCUsqoS1.js","assets/Chat-QumIYKUd.js"])))=>i.map(i=>d[i]); +import{c as I,j as t,a as l,d as K}from"./react-vendor-l-BBvuKH.js";import{o as W}from"./vendor-cRYyTeIw.js";import{L as z,a as P,S as J,U as Q,A as X,b as ee,c as te,M as se,C as ne,B as re,d as ae,Z as oe,e as ie,f as ce,G as R,g as le,h as de,i as ue}from"./icons-vendor-Bgrth_9N.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"]'))a(r);new MutationObserver(r=>{for(const c of r)if(c.type==="childList")for(const o of c.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const c={};return r.integrity&&(c.integrity=r.integrity),r.referrerPolicy&&(c.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?c.credentials="include":r.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function a(r){if(r.ep)return;r.ep=!0;const c=s(r);fetch(r.href,c)}})();class he extends I.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}let _=!1;class O extends Error{constructor(n,s){super(pe(s,n)),this.name="ApiError",this.status=n,this.code=N(s)?s.code:`http_${n}`,this.requestId=N(s)?s.request_id:void 0,this.request_id=this.requestId,this.details=N(s)?s.details:void 0,this.payload=s}}const me=()=>{_||typeof window>"u"||(_=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{_=!1}))},fe=(e,n)=>{const s=new AbortController,a=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?a():e==null||e.addEventListener("abort",a,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",a)}}},N=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},pe=(e,n)=>typeof e=="string"?e:N(e)?e.message:`请求失败: ${n}`,xe=3e4,ge=async(e,n)=>{const s=new URL(typeof e=="string"?e:e instanceof URL?e.toString():e.url),a=e instanceof Request?e:new Request(e,n),r=a.headers.get("content-type")||"",c=a.method==="GET"||a.method==="HEAD"?void 0:r.includes("multipart/form-data")?await a.clone().formData():await a.clone().text(),o=s.origin==="http://localhost"?`${s.pathname}${s.search}`:e;return await fetch(o,{method:a.method,headers:a.headers,body:c,signal:a.signal,credentials:"include"})},be=typeof location>"u"?"http://localhost":location.origin,v=W({baseUrl:be,fetch:ge});function nt(e){return e}async function w(e,n={}){var a;const s=fe(n.signal,n.timeoutMs??xe);try{const r=await e(s.signal);if(r.response.status===401&&!n.skipAuthLogout&&me(),r.error!==void 0)throw new O(r.response.status,r.error);if(r.data===void 0)throw new O(r.response.status,void 0);return r.data}catch(r){throw s.signal.aborted?new Error((a=n.signal)!=null&&a.aborted?"请求已取消":"请求超时,请稍后重试"):r}finally{s.cleanup()}}const ve=async e=>{const n=await w(s=>v.POST("/api/v1/session/login",{body:e,signal:s}),{skipAuthLogout:!0});return{...n,token:n.token??void 0}},we=async e=>{const n=await w(s=>v.POST("/api/v1/session/initialize",{body:{password:e},signal:s}),{skipAuthLogout:!0});return{...n,token:n.token??void 0}},ye=async e=>w(n=>v.GET("/api/v1/session",{signal:n}),e),Le=async()=>({success:!0,message:(await w(n=>v.POST("/api/v1/session/logout",{body:{},signal:n}))).message}),U=l.createContext(void 0),je=({children:e})=>{const[n,s]=l.useState(!1),[a,r]=l.useState(!1),[c,o]=l.useState(!0),[i,u]=l.useState(!1),d=()=>{s(!1),r(!1)};l.useEffect(()=>{const x=new AbortController;let p=!0;ye({signal:x.signal}).then(b=>{if(p){if((b==null?void 0:b.initialized)===!1){u(!0),d();return}u(!1),b!=null&&b.authenticated?(s(!0),r(b.is_admin===!0)):d()}}).catch(b=>{!p||b instanceof DOMException&&b.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&o(!1)});const h=()=>d();return window.addEventListener("auth:logout",h),(()=>{p=!1,x.abort(),window.removeEventListener("auth:logout",h)})},[]);const m=async x=>{const p=await ve(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},g=async x=>{const p=await we(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},f=async()=>{try{await Le()}finally{d()}};return t.jsx(U.Provider,{value:{checkingAuth:c,isLoggedIn:n,isAdmin:a,needsInit:i,signIn:m,initialize:g,signOut:f},children:e})},q=()=>{const e=l.useContext(U);if(!e)throw new Error("useSession 必须在 SessionProvider 内使用");return e},B="ydisks.sidebar.v1",Ce=()=>{try{return window.localStorage.getItem(B)==="collapsed"}catch{return!1}},Ee=e=>{try{window.localStorage.setItem(B,e?"collapsed":"expanded")}catch{}},Ne=({className:e="w-full h-full text-white"})=>t.jsx("svg",{className:e,viewBox:"0 0 256 256","aria-hidden":"true",children:t.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:t.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),F=({sizeClass:e="w-12 h-12",logoClassName:n="w-full h-full text-white"})=>t.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[t.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),t.jsxs("div",{className:`relative ${e} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[t.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[t.jsx("defs",{children:t.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[t.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),t.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),t.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),t.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:t.jsx(Ne,{className:n})})]})]}),Se=()=>{const{checkingAuth:e,needsInit:n,signIn:s,initialize:a}=q(),[r,c]=l.useState(""),[o,i]=l.useState(""),[u,d]=l.useState(""),[m,g]=l.useState(""),[f,x]=l.useState(!1),[p,h]=l.useState(""),b=async y=>{y.preventDefault(),x(!0),h("");try{const L=await s({username:r,password:o});L.success||h(L.message||"登录失败")}catch(L){h(L instanceof Error&&L.message||"登录失败")}finally{x(!1)}},C=async y=>{if(y.preventDefault(),h(""),u.length<8){h("密码至少需要 8 个字符");return}if(u!==m){h("两次输入的密码不一致");return}x(!0);try{const L=await a(u);if(!L.success){h(L.message||"初始化失败,请重试");return}d(""),g("")}catch(L){h(L instanceof Error&&L.message||"初始化失败,请重试")}finally{x(!1)}};if(e)return t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-surface","aria-label":"正在校验会话",children:t.jsx(z,{className:"h-8 w-8 animate-spin text-brand"})});const Z=n?"首次设置管理员密码":"欢迎回来",Y=n?"设置完成后会自动进入系统,管理员账号为 admin。":"Ydisks闲鱼助手 · 自动发货与管家系统";return t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-4 font-sans",children:t.jsxs("section",{className:"w-full max-w-lg rounded-xl border border-white bg-white/80 p-8 shadow-panel backdrop-blur-3xl md:p-12",children:[t.jsxs("header",{className:"mb-8 text-center",children:[t.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:t.jsx(F,{sizeClass:"h-24 w-24"})}),t.jsx("h1",{className:"text-3xl font-extrabold text-gray-900",children:Z}),t.jsx("p",{className:"mt-2 font-medium text-gray-600",children:Y})]}),n?t.jsxs("form",{className:"space-y-5",onSubmit:C,children:[t.jsxs("label",{className:"relative block",children:[t.jsx("span",{className:"sr-only",children:"设置管理员密码"}),t.jsx(P,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),t.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>d(y.target.value)),placeholder:"设置管理员密码(至少 8 个字符)",type:"password",value:u})]}),t.jsxs("label",{className:"relative block",children:[t.jsx("span",{className:"sr-only",children:"确认管理员密码"}),t.jsx(J,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),t.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>g(y.target.value)),placeholder:"再次输入密码",type:"password",value:m})]}),t.jsx(M,{submitting:f,text:"设置密码并进入系统"})]}):t.jsxs("form",{className:"space-y-5",onSubmit:b,children:[t.jsxs("label",{className:"relative block",children:[t.jsx("span",{className:"sr-only",children:"管理员账号"}),t.jsx(Q,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),t.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>c(y.target.value)),placeholder:"管理员账号",type:"text",value:r})]}),t.jsxs("label",{className:"relative block",children:[t.jsx("span",{className:"sr-only",children:"管理员密码"}),t.jsx(P,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),t.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>i(y.target.value)),placeholder:"密码",type:"password",value:o})]}),t.jsx(M,{submitting:f,text:"立即登录"})]}),p?t.jsx("p",{className:"mt-5 rounded-xl bg-red-50 p-3 text-center text-sm font-medium text-red-600",children:p}):null]})})},M=({submitting:e,text:n})=>t.jsx("button",{className:"ios-btn-primary flex h-14 w-full items-center justify-center gap-2 rounded-xl text-lg disabled:opacity-70",disabled:e,type:"submit",children:e?t.jsx(z,{className:"h-5 w-5 animate-spin"}):t.jsxs(t.Fragment,{children:[t.jsx("span",{children:n}),t.jsx(X,{className:"h-5 w-5"})]})}),_e="modulepreload",Te=function(e){return"/static/"+e},D={},j=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let o=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),u=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));r=o(s.map(d=>{if(d=Te(d),d in D)return;D[d]=!0;const m=d.endsWith(".css"),g=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${g}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":_e,m||(f.as="script"),f.crossOrigin="",f.href=d,u&&f.setAttribute("nonce",u),document.head.appendChild(f),m)return new Promise((x,p)=>{f.addEventListener("load",x),f.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${d}`)))})}))}function c(o){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=o,window.dispatchEvent(i),!i.defaultPrevented)throw o}return r.then(o=>{for(const i of o||[])i.status==="rejected"&&c(i.reason);return n().catch(c)})},Ae=({activeTab:e,isAdmin:n=!1,collapsed:s,onToggleCollapsed:a,onNavigate:r,onLogout:c,buildInfo:o,hasUnreadChatMessage:i=!1})=>{const u=[{id:"dashboard",icon:ee,label:"仪表盘"},{id:"accounts",icon:te,label:"账号管理"},{id:"chat",icon:se,label:"在线聊天"},{id:"cards",icon:ne,label:"卡密库存"},{id:"items",icon:re,label:"商品列表"},{id:"orders",icon:ae,label:"订单管理"},{id:"rules",icon:oe,label:"自动化规则"},{id:"notifications",icon:ie,label:"通知设置"},...n?[{id:"settings",icon:ce,label:"系统与AI"}]:[]],d=/^\d+\.\d+\.\d+$/.test(o.version)?`v${o.version}`:o.version;return t.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${s?"w-16":"w-64"}`,children:[t.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${s?"justify-center px-2":"gap-3 px-5"}`,children:[t.jsx(F,{sizeClass:"h-10 w-10"}),!s&&t.jsxs("div",{className:"min-w-0 leading-tight",children:[t.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),t.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),t.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${s?"px-2":"px-3"}`,"aria-label":"主导航",children:u.map(m=>{const g=m.icon,f=e===m.id;return t.jsx(I.Fragment,{children:t.jsxs("button",{type:"button",title:s?m.label:void 0,"aria-label":m.label,"aria-current":f?"page":void 0,onClick:(()=>r(m.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${s?"justify-center":"gap-3 px-3.5"} ${f?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[t.jsxs("span",{className:"relative flex h-[19px] w-[19px] shrink-0",children:[t.jsx(g,{className:`h-[19px] w-[19px] ${f?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),m.id==="chat"&&i&&t.jsx("span",{className:"absolute -right-1 -top-1 h-3 w-3 rounded-full border-2 border-white bg-red-500",role:"status","aria-label":"在线聊天有未读消息"})]}),!s&&t.jsx("span",{className:"truncate text-sm font-bold",children:m.label}),f&&!s&&t.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},m.id)})}),t.jsxs("div",{children:[t.jsx("div",{title:s?`版本 ${o.version} · ${o.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${s?"flex justify-center px-1":"px-6"}`,children:s?t.jsx(R,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${o.version}`}):t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[t.jsx(R,{className:"h-3.5 w-3.5"}),"运行版本"]}),t.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[t.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:d}),t.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:o.commit})]})]})}),t.jsxs("div",{className:`space-y-2 p-2 ${s?"":"p-3"}`,children:[t.jsxs("button",{type:"button",onClick:a,title:s?"展开侧边栏":"收起侧边栏","aria-label":s?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${s?"justify-center":"gap-3 px-3"}`,children:[s?t.jsx(le,{className:"h-5 w-5"}):t.jsx(de,{className:"h-5 w-5"}),!s&&t.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),t.jsxs("button",{type:"button",onClick:c,title:s?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${s?"justify-center":"gap-3 px-3"}`,children:[t.jsx(ue,{className:"h-5 w-5"}),!s&&t.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},ke=async e=>(await w(s=>v.GET("/api/v1/accounts/details",{signal:s}),e)).map(s=>({id:s.id,enabled:s.enabled,auto_confirm:s.auto_confirm,remark:s.remark,pause_duration:s.pause_duration,paused_until:s.paused_until,paused:s.paused,username:s.username,show_browser:s.show_browser,nickname:s.nickname,avatar_url:s.avatar_url,profile_error:s.profile_error})),rt=async e=>w(n=>v.GET("/api/v1/accounts/runtime-status",{signal:n}),e),Ie=async(e,n,s,a=!1)=>await w(c=>v.GET("/api/v1/chat/sessions",{params:{query:{account_id:e,cursor:n,refresh:a?1:void 0}},signal:c}),{timeoutMs:a?6e4:s==null?void 0:s.timeoutMs,signal:s==null?void 0:s.signal}),at=async(e,n,s,a,r)=>await w(o=>v.GET("/api/v1/chat/messages",{params:{query:{account_id:e,chat_id:n,cursor:s,before_id:a}},signal:o}),r),ot=async(e,n)=>w(s=>v.POST("/api/v1/chat/messages",{body:e,signal:s}),n),it=async(e,n)=>{const s=new FormData;return Object.entries(e).forEach(([a,r])=>s.append(a,r)),w(a=>v.POST("/api/v1/chat/images",{body:s,signal:a}),{timeoutMs:12e4,...n})},ct=async(e,n,s,a)=>w(r=>v.POST("/api/v1/chat/read",{body:{account_id:e,chat_id:n,message_ids:s.map(c=>({messageId:c.messageId,sessionId:c.sessionId,cid:c.cid,conversationType:c.conversationType}))},signal:r}),a),S=new Set;let V="connecting";const k=new Set,lt=e=>(e({type:"connection",state:V}),S.add(e),(()=>S.delete(e))),E=e=>{V=e;for(const n of S)n({type:"connection",state:e})},Pe=e=>{for(const n of S)n({type:"message",message:e})},Re=e=>(k.add(e),(()=>k.delete(e))),dt=e=>{for(const n of k)n(e)},Oe=1e3,Me=e=>`【新消息】${e}`,De=()=>{const[e,n]=l.useState(0),[s,a]=l.useState(!1),r=l.useRef(document.title),c=l.useRef(0);return l.useEffect(()=>{const i=()=>n(0),u=()=>{document.visibilityState==="visible"&&i()};return window.addEventListener("focus",i),document.addEventListener("visibilitychange",u),(()=>{window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",u)})},[]),l.useEffect(()=>{if(e<=0){document.title=r.current;return}let i=!0;const u=()=>{document.title=i?Me(r.current):r.current};u();const d=window.setInterval(()=>{i=!i,u()},Oe);return(()=>{window.clearInterval(d),document.title=r.current})},[e]),l.useEffect(()=>{const i=new AbortController,u=c.current;return(async()=>{try{const g=(await ke({signal:i.signal})).filter(p=>p.enabled),f=await Promise.all(g.map(p=>Ie(p.id,void 0,{signal:i.signal})));if(i.signal.aborted||c.current!==u)return;const x=f.some(p=>p.sessions.some(h=>h.unread_count>0));a(x)}catch{}})(),(()=>i.abort())},[]),l.useEffect(()=>Re(a),[]),{notifyIncomingMessage:l.useCallback(i=>{i.direction!=="incoming"||i.message_type==="system"||(c.current+=1,n(u=>u+1),a(!0))},[]),hasUnreadChatMessage:s}},$e=()=>{const e=De(),{notifyIncomingMessage:n,hasUnreadChatMessage:s}=e;return l.useEffect(()=>{let a=!1,r=0,c=0,o=null;const i=()=>{if(a)return;E("connecting");const u=window.location.protocol==="https:"?"wss:":"ws:";o=new WebSocket(`${u}//${window.location.host}/api/v1/chat/ws`),o.onopen=()=>{c=0,E("online")},o.onmessage=d=>{try{const g=JSON.parse(d.data).message;g&&(n(g),Pe(g))}catch{}},o.onclose=()=>{if(a)return;E("offline");const d=Math.min(15e3,1e3*2**Math.min(c++,4));r=window.setTimeout(i,d)},o.onerror=()=>o==null?void 0:o.close()};return i(),(()=>{a=!0,window.clearTimeout(r),o==null||o.close(),E("offline")})},[n]),{hasUnreadChatMessage:s}},ze=async e=>w(n=>v.GET("/health",{signal:n}),e),T=l.lazy(()=>j(()=>import("./Dashboard-CJrI6NVV.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]))),Ue=l.lazy(()=>j(()=>import("./AccountList-DX3reM6l.js"),__vite__mapDeps([8,1,7,3,5,6]))),qe=l.lazy(()=>j(()=>import("./OrderList-B4B8_a2q.js"),__vite__mapDeps([9,1,2,3,7,5,6]))),Be=l.lazy(()=>j(()=>import("./CardList-DDZ2JnUG.js"),__vite__mapDeps([10,1,7,3,5,6]))),Fe=l.lazy(()=>j(()=>import("./ItemList-C0hxXhgx.js"),__vite__mapDeps([11,1,7,3,5,6]))),Ve=l.lazy(()=>j(()=>import("./Settings-CQ_-2bDk.js"),__vite__mapDeps([12,1,3,5,6]))),Ge=l.lazy(()=>j(()=>import("./Rules-CMO3kj4s.js"),__vite__mapDeps([13,1,3,7,5,6]))),He=l.lazy(()=>j(()=>import("./Notifications-BCUsqoS1.js"),__vite__mapDeps([14,1,3,5,6]))),Ze=l.lazy(()=>j(()=>import("./Chat-QumIYKUd.js"),__vite__mapDeps([15,1,5,6,3]))),Ye=()=>t.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:t.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),Ke=({activeTab:e,isAdmin:n,deliveryRuleTarget:s,onConfigureDelivery:a,onDeliveryTargetHandled:r})=>{const c=i=>{a({cookieId:i.cookie_id,itemId:i.item_id,requestId:Date.now()})},o=()=>{switch(e){case"dashboard":return t.jsx(T,{});case"accounts":return t.jsx(Ue,{});case"chat":return t.jsx(Ze,{});case"orders":return t.jsx(qe,{});case"cards":return t.jsx(Be,{});case"items":return t.jsx(Fe,{onConfigureDelivery:c});case"rules":return t.jsx(Ge,{initialDeliveryTarget:s,onDeliveryTargetHandled:r});case"notifications":return t.jsx(He,{isAdmin:n});case"settings":return n?t.jsx(Ve,{}):t.jsx(T,{});default:return t.jsx(T,{})}};return t.jsx(l.Suspense,{fallback:t.jsx(Ye,{}),children:o()})},We=({activeTab:e,isAdmin:n,collapsed:s,deliveryRuleTarget:a,onToggleCollapsed:r,onNavigate:c,onLogout:o,onConfigureDelivery:i,onDeliveryTargetHandled:u})=>{const[d,m]=l.useState({version:"dev",commit:"unknown"}),{hasUnreadChatMessage:g}=$e();return l.useEffect(()=>{const f=new AbortController;return ze({signal:f.signal}).then(x=>m({version:String(x.version||"dev"),commit:String(x.commit||"unknown")})).catch(x=>{x instanceof DOMException&&x.name}),(()=>f.abort())},[]),t.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[t.jsx(Ae,{activeTab:e,isAdmin:n,collapsed:s,onToggleCollapsed:r,onNavigate:c,onLogout:o,buildInfo:d,hasUnreadChatMessage:g}),t.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${s?"ml-16":"ml-64"} ${e==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[t.jsx("div",{className:"fixed top-0 right-0 -z-10 h-[800px] w-[800px] pointer-events-none rounded-full bg-gradient-to-bl from-blue-50 to-transparent opacity-60 blur-[120px]"}),t.jsx("div",{className:`${e==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:t.jsx(Ke,{activeTab:e,isAdmin:n,deliveryRuleTarget:a,onConfigureDelivery:i,onDeliveryTargetHandled:u})})]})]})},G={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/chat":"chat","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},A=Object.fromEntries(Object.entries(G).map(([e,n])=>[n,e])),$=()=>G[window.location.pathname]??"dashboard",Je=()=>{const{isLoggedIn:e,isAdmin:n,signOut:s}=q(),[a,r]=l.useState($),[c,o]=l.useState(),[i,u]=l.useState(Ce);l.useEffect(()=>{const h=()=>r($());return window.addEventListener("popstate",h),(()=>window.removeEventListener("popstate",h))},[]),l.useEffect(()=>{e&&!n&&a==="settings"&&(window.history.replaceState({},"",A.dashboard),r("dashboard"))},[a,n,e]);const d=h=>{const b=h==="settings"&&!n?"dashboard":h,C=A[b];C!==window.location.pathname&&window.history.pushState({},"",C),r(b)},m=h=>{const b=Object.prototype.hasOwnProperty.call(A,h)?h:"dashboard";d(b)},g=async()=>{try{await s()}catch(h){console.error("退出登录失败",h)}},f=()=>{u(h=>{const b=!h;return Ee(b),b})},x=h=>{o(h),d("rules")},p=()=>o(void 0);return e?t.jsx(We,{activeTab:a,isAdmin:n,collapsed:i,deliveryRuleTarget:c,onToggleCollapsed:f,onNavigate:m,onLogout:g,onConfigureDelivery:x,onDeliveryTargetHandled:p}):t.jsx(Se,{})},Qe=()=>t.jsx(he,{children:t.jsx(je,{children:t.jsx(Je,{})})}),H=document.getElementById("root");if(!H)throw new Error("Could not find root element to mount to");const Xe=K.createRoot(H);Xe.render(t.jsx(I.StrictMode,{children:t.jsx(Qe,{})}));export{O as A,nt as a,at as b,v as c,ot as d,it as e,ke as f,Ie as g,rt as h,ct as m,dt as p,w as r,lt as s}; diff --git a/internal/webui/static/assets/index-WrujSo30.js b/internal/webui/static/assets/index-WrujSo30.js deleted file mode 100644 index 004f6a2..0000000 --- a/internal/webui/static/assets/index-WrujSo30.js +++ /dev/null @@ -1,2 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-Ba2fUvQH.js","assets/react-vendor-l-BBvuKH.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-Bgrth_9N.js","assets/charts-vendor-DlHaeEQJ.js","assets/vendor-cRYyTeIw.js","assets/vendor-DUblxfbA.css","assets/AccountList-DgwrfNi_.js","assets/OrderList-CXbMt2fz.js","assets/CardList-CfmBeFUG.js","assets/ItemList-CH6EVxKe.js","assets/Settings-WRDun9wT.js","assets/Rules-4H5_byLi.js","assets/Notifications-DHwrazHy.js","assets/Chat-MUERwcqZ.js"])))=>i.map(i=>d[i]); -import{c as M,j as s,a as l,d as ne}from"./react-vendor-l-BBvuKH.js";import{o as re}from"./vendor-cRYyTeIw.js";import{L as V,a as U,S as ae,U as oe,A as ie,b as ce,c as le,M as de,C as ue,B as he,d as me,Z as fe,e as pe,f as ge,G as q,g as xe,h as ye,i as be}from"./icons-vendor-Bgrth_9N.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&o(a)}).observe(document,{childList:!0,subtree:!0});function t(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=t(r);fetch(r.href,i)}})();class we extends M.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:t}=this.props;return n?s.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:s.jsxs("section",{className:"max-w-md text-center",children:[s.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),s.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):t}}const ve=3e4,je=10*6e4;let k=!1;class N extends Error{constructor(n,t){super(Ee(t,n)),this.name="ApiError",this.status=n,this.code=E(t)?t.code:`http_${n}`,this.requestId=E(t)?t.request_id:void 0,this.request_id=this.requestId,this.details=E(t)?t.details:void 0,this.payload=t}}const $=()=>{k||typeof window>"u"||(k=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{k=!1}))},Le=e=>{if(!e)return"";const n=new URLSearchParams;for(const[o,r]of Object.entries(e))r!=null&&n.set(o,String(r));const t=n.toString();return t?`?${t}`:""},A=async(e,n,t={})=>{var d;const o=Le(t.params),r=`${n}${o}`,i=D(t.signal,t.timeoutMs??ve);let a;try{a=await fetch(r,{method:e,credentials:"include",signal:i.signal,headers:{...t.body===void 0?{}:{"Content-Type":"application/json"}},body:t.body===void 0?void 0:JSON.stringify(t.body)})}catch(h){throw i.signal.aborted?new Error((d=t.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):h}finally{i.cleanup()}const u=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!t.skipAuthLogout&&$();const h=await H(a,u);throw new N(a.status,h)}return u?await a.json():await a.text()},j=async(e,n,t)=>A("GET",e,{params:n,...t}),G=async(e,n,t)=>A("POST",e,{body:n,...t}),mt=async(e,n,t)=>A("PUT",e,{body:n,...t}),ft=async(e,n,t)=>A("DELETE",e,{params:n,...t}),Ce=async(e,n,t={})=>{var u;const o=D(t.signal,t.timeoutMs??je);let r;try{r=await fetch(e,{method:"POST",credentials:"include",signal:o.signal,body:n})}catch(d){throw o.signal.aborted?new Error((u=t.signal)!=null&&u.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{o.cleanup()}const a=(r.headers.get("content-type")||"").includes("application/json"),c=await H(r,a);if(!r.ok)throw r.status===401&&$(),new N(r.status,c);return c},D=(e,n)=>{const t=new AbortController,o=()=>t.abort(e==null?void 0:e.reason);e!=null&&e.aborted?o():e==null||e.addEventListener("abort",o,{once:!0});const r=globalThis.setTimeout(()=>t.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:t.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",o)}}},H=async(e,n)=>n?e.json().catch(()=>{}):e.text().catch(()=>{}),E=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},Ee=(e,n)=>typeof e=="string"?e:E(e)?e.message:`请求失败: ${n}`,Ne=3e4,Se=async(e,n)=>{const t=new URL(typeof e=="string"?e:e instanceof URL?e.toString():e.url),o=e instanceof Request?e:new Request(e,n),r=o.method==="GET"||o.method==="HEAD"?void 0:await o.clone().text(),i=t.origin==="http://localhost"?`${t.pathname}${t.search}`:e;return await fetch(i,{method:o.method,headers:o.headers,body:r,signal:o.signal,credentials:"include"})},_e=typeof location>"u"?"http://localhost":location.origin,P=re({baseUrl:_e,fetch:Se});async function T(e,n={}){var o;const t=D(n.signal,n.timeoutMs??Ne);try{const r=await e(t.signal);if(r.response.status===401&&!n.skipAuthLogout&&$(),r.error!==void 0)throw new N(r.response.status,r.error);if(r.data===void 0)throw new N(r.response.status,void 0);return r.data}catch(r){throw t.signal.aborted?new Error((o=n.signal)!=null&&o.aborted?"请求已取消":"请求超时,请稍后重试"):r}finally{t.cleanup()}}const Ae=async e=>{const n=await T(t=>P.POST("/api/v1/session/login",{body:e,signal:t}),{skipAuthLogout:!0});return{...n,token:n.token??void 0}},Pe=async e=>{const n=await T(t=>P.POST("/api/v1/session/initialize",{body:{password:e},signal:t}),{skipAuthLogout:!0});return{...n,token:n.token??void 0}},Te=async e=>T(n=>P.GET("/api/v1/session",{signal:n}),e),ke=async()=>({success:!0,message:(await T(n=>P.POST("/api/v1/session/logout",{body:{},signal:n}))).message}),J=l.createContext(void 0),Re=({children:e})=>{const[n,t]=l.useState(!1),[o,r]=l.useState(!1),[i,a]=l.useState(!0),[c,u]=l.useState(!1),d=()=>{t(!1),r(!1)};l.useEffect(()=>{const g=new AbortController;let p=!0;Te({signal:g.signal}).then(y=>{if(p){if((y==null?void 0:y.initialized)===!1){u(!0),d();return}u(!1),y!=null&&y.authenticated?(t(!0),r(y.is_admin===!0)):d()}}).catch(y=>{!p||y instanceof DOMException&&y.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&a(!1)});const m=()=>d();return window.addEventListener("auth:logout",m),(()=>{p=!1,g.abort(),window.removeEventListener("auth:logout",m)})},[]);const h=async g=>{const p=await Ae(g);return p.success&&(u(!1),t(!0),r(p.is_admin===!0)),p},x=async g=>{const p=await Pe(g);return p.success&&(u(!1),t(!0),r(p.is_admin===!0)),p},f=async()=>{try{await ke()}finally{d()}};return s.jsx(J.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:o,needsInit:c,signIn:h,initialize:x,signOut:f},children:e})},Z=()=>{const e=l.useContext(J);if(!e)throw new Error("useSession 必须在 SessionProvider 内使用");return e},Y="ydisks.sidebar.v1",Ie=()=>{try{return window.localStorage.getItem(Y)==="collapsed"}catch{return!1}},Oe=e=>{try{window.localStorage.setItem(Y,e?"collapsed":"expanded")}catch{}},Me=({className:e="w-full h-full text-white"})=>s.jsx("svg",{className:e,viewBox:"0 0 256 256","aria-hidden":"true",children:s.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:s.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),K=({sizeClass:e="w-12 h-12",logoClassName:n="w-full h-full text-white"})=>s.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[s.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),s.jsxs("div",{className:`relative ${e} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[s.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[s.jsx("defs",{children:s.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[s.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),s.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),s.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),s.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:s.jsx(Me,{className:n})})]})]}),$e=()=>{const{checkingAuth:e,needsInit:n,signIn:t,initialize:o}=Z(),[r,i]=l.useState(""),[a,c]=l.useState(""),[u,d]=l.useState(""),[h,x]=l.useState(""),[f,g]=l.useState(!1),[p,m]=l.useState(""),y=async b=>{b.preventDefault(),g(!0),m("");try{const w=await t({username:r,password:a});w.success||m(w.message||"登录失败")}catch(w){m(w instanceof Error&&w.message||"登录失败")}finally{g(!1)}},L=async b=>{if(b.preventDefault(),m(""),u.length<8){m("密码至少需要 8 个字符");return}if(u!==h){m("两次输入的密码不一致");return}g(!0);try{const w=await o(u);if(!w.success){m(w.message||"初始化失败,请重试");return}d(""),x("")}catch(w){m(w instanceof Error&&w.message||"初始化失败,请重试")}finally{g(!1)}};if(e)return s.jsx("main",{className:"flex min-h-screen items-center justify-center bg-surface","aria-label":"正在校验会话",children:s.jsx(V,{className:"h-8 w-8 animate-spin text-brand"})});const te=n?"首次设置管理员密码":"欢迎回来",se=n?"设置完成后会自动进入系统,管理员账号为 admin。":"Ydisks闲鱼助手 · 自动发货与管家系统";return s.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-4 font-sans",children:s.jsxs("section",{className:"w-full max-w-lg rounded-xl border border-white bg-white/80 p-8 shadow-panel backdrop-blur-3xl md:p-12",children:[s.jsxs("header",{className:"mb-8 text-center",children:[s.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:s.jsx(K,{sizeClass:"h-24 w-24"})}),s.jsx("h1",{className:"text-3xl font-extrabold text-gray-900",children:te}),s.jsx("p",{className:"mt-2 font-medium text-gray-600",children:se})]}),n?s.jsxs("form",{className:"space-y-5",onSubmit:L,children:[s.jsxs("label",{className:"relative block",children:[s.jsx("span",{className:"sr-only",children:"设置管理员密码"}),s.jsx(U,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),s.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(b=>d(b.target.value)),placeholder:"设置管理员密码(至少 8 个字符)",type:"password",value:u})]}),s.jsxs("label",{className:"relative block",children:[s.jsx("span",{className:"sr-only",children:"确认管理员密码"}),s.jsx(ae,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),s.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(b=>x(b.target.value)),placeholder:"再次输入密码",type:"password",value:h})]}),s.jsx(z,{submitting:f,text:"设置密码并进入系统"})]}):s.jsxs("form",{className:"space-y-5",onSubmit:y,children:[s.jsxs("label",{className:"relative block",children:[s.jsx("span",{className:"sr-only",children:"管理员账号"}),s.jsx(oe,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),s.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(b=>i(b.target.value)),placeholder:"管理员账号",type:"text",value:r})]}),s.jsxs("label",{className:"relative block",children:[s.jsx("span",{className:"sr-only",children:"管理员密码"}),s.jsx(U,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),s.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(b=>c(b.target.value)),placeholder:"密码",type:"password",value:a})]}),s.jsx(z,{submitting:f,text:"立即登录"})]}),p?s.jsx("p",{className:"mt-5 rounded-xl bg-red-50 p-3 text-center text-sm font-medium text-red-600",children:p}):null]})})},z=({submitting:e,text:n})=>s.jsx("button",{className:"ios-btn-primary flex h-14 w-full items-center justify-center gap-2 rounded-xl text-lg disabled:opacity-70",disabled:e,type:"submit",children:e?s.jsx(V,{className:"h-5 w-5 animate-spin"}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:n}),s.jsx(ie,{className:"h-5 w-5"})]})}),De="modulepreload",Ue=function(e){return"/static/"+e},F={},v=function(n,t,o){let r=Promise.resolve();if(t&&t.length>0){let a=function(d){return Promise.all(d.map(h=>Promise.resolve(h).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));r=a(t.map(d=>{if(d=Ue(d),d in F)return;F[d]=!0;const h=d.endsWith(".css"),x=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${x}`))return;const f=document.createElement("link");if(f.rel=h?"stylesheet":De,h||(f.as="script"),f.crossOrigin="",f.href=d,u&&f.setAttribute("nonce",u),document.head.appendChild(f),h)return new Promise((g,p)=>{f.addEventListener("load",g),f.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return r.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return n().catch(i)})},qe=({activeTab:e,isAdmin:n=!1,collapsed:t,onToggleCollapsed:o,onNavigate:r,onLogout:i,buildInfo:a,hasUnreadChatMessage:c=!1})=>{const u=[{id:"dashboard",icon:ce,label:"仪表盘"},{id:"accounts",icon:le,label:"账号管理"},{id:"chat",icon:de,label:"在线聊天"},{id:"cards",icon:ue,label:"卡密库存"},{id:"items",icon:he,label:"商品列表"},{id:"orders",icon:me,label:"订单管理"},{id:"rules",icon:fe,label:"自动化规则"},{id:"notifications",icon:pe,label:"通知设置"},...n?[{id:"settings",icon:ge,label:"系统与AI"}]:[]],d=/^\d+\.\d+\.\d+$/.test(a.version)?`v${a.version}`:a.version;return s.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${t?"w-16":"w-64"}`,children:[s.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${t?"justify-center px-2":"gap-3 px-5"}`,children:[s.jsx(K,{sizeClass:"h-10 w-10"}),!t&&s.jsxs("div",{className:"min-w-0 leading-tight",children:[s.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),s.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),s.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${t?"px-2":"px-3"}`,"aria-label":"主导航",children:u.map(h=>{const x=h.icon,f=e===h.id;return s.jsx(M.Fragment,{children:s.jsxs("button",{type:"button",title:t?h.label:void 0,"aria-label":h.label,"aria-current":f?"page":void 0,onClick:(()=>r(h.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${t?"justify-center":"gap-3 px-3.5"} ${f?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[s.jsxs("span",{className:"relative flex h-[19px] w-[19px] shrink-0",children:[s.jsx(x,{className:`h-[19px] w-[19px] ${f?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),h.id==="chat"&&c&&s.jsx("span",{className:"absolute -right-1 -top-1 h-3 w-3 rounded-full border-2 border-white bg-red-500",role:"status","aria-label":"在线聊天有未读消息"})]}),!t&&s.jsx("span",{className:"truncate text-sm font-bold",children:h.label}),f&&!t&&s.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},h.id)})}),s.jsxs("div",{children:[s.jsx("div",{title:t?`版本 ${a.version} · ${a.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${t?"flex justify-center px-1":"px-6"}`,children:t?s.jsx(q,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${a.version}`}):s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[s.jsx(q,{className:"h-3.5 w-3.5"}),"运行版本"]}),s.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[s.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:d}),s.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:a.commit})]})]})}),s.jsxs("div",{className:`space-y-2 p-2 ${t?"":"p-3"}`,children:[s.jsxs("button",{type:"button",onClick:o,title:t?"展开侧边栏":"收起侧边栏","aria-label":t?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${t?"justify-center":"gap-3 px-3"}`,children:[t?s.jsx(xe,{className:"h-5 w-5"}):s.jsx(ye,{className:"h-5 w-5"}),!t&&s.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),s.jsxs("button",{type:"button",onClick:i,title:t?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${t?"justify-center":"gap-3 px-3"}`,children:[s.jsx(be,{className:"h-5 w-5"}),!t&&s.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},S=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pt=(e,n=["data","items","results"])=>{let t=e,o=0;for(;o<2;o+=1){if(Array.isArray(t))return t;if(!S(t))return[];for(const i of n){const a=t[i];if(Array.isArray(a))return a;if(a===null)return[]}const r=t.data;if(S(r)){t=r;continue}return[]}return[]},W=(e,n=["data","result"])=>{let t=e,o=0;for(;o<2;o+=1){if(!S(t))return;for(const r of n){const i=t[r];if(S(i))return i}return t}},ze=async e=>j("/api/v1/accounts/details",void 0,e),gt=async e=>j("/api/v1/accounts/runtime-status",void 0,e),Fe=async(e,n,t,o=!1)=>{const r=await j("/api/v1/chat/sessions",{account_id:e,cursor:n,refresh:o?1:void 0},o?{timeoutMs:6e4,...t}:t),i=W(r,["data","result"])||{};return{sessions:i.sessions||[],has_more:i.has_more===!0,next_cursor:i.next_cursor}},xt=async(e,n,t,o,r)=>{const i=await j("/api/v1/chat/messages",{account_id:e,chat_id:n,cursor:t,before_id:o},r),a=W(i,["data","result"])||{};return{messages:a.messages||[],has_more:a.has_more===!0,next_cursor:a.next_cursor,session:a.session}},yt=async(e,n)=>G("/api/v1/chat/messages",e,n),bt=async(e,n)=>{const t=new FormData;return Object.entries(e).forEach(([o,r])=>t.append(o,r)),Ce("/api/v1/chat/images",t,{timeoutMs:12e4,...n})},wt=async(e,n,t,o)=>G("/api/v1/chat/read",{account_id:e,chat_id:n,message_ids:t},o),_=new Set;let Q="connecting";const O=new Set,vt=e=>(e({type:"connection",state:Q}),_.add(e),(()=>_.delete(e))),C=e=>{Q=e;for(const n of _)n({type:"connection",state:e})},Be=e=>{for(const n of _)n({type:"message",message:e})},Ve=e=>(O.add(e),(()=>O.delete(e))),jt=e=>{for(const n of O)n(e)},Ge=1e3,He=e=>`【新消息】${e}`,Je=()=>{const[e,n]=l.useState(0),[t,o]=l.useState(!1),r=l.useRef(document.title),i=l.useRef(0);return l.useEffect(()=>{const c=()=>n(0),u=()=>{document.visibilityState==="visible"&&c()};return window.addEventListener("focus",c),document.addEventListener("visibilitychange",u),(()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",u)})},[]),l.useEffect(()=>{if(e<=0){document.title=r.current;return}let c=!0;const u=()=>{document.title=c?He(r.current):r.current};u();const d=window.setInterval(()=>{c=!c,u()},Ge);return(()=>{window.clearInterval(d),document.title=r.current})},[e]),l.useEffect(()=>{const c=new AbortController,u=i.current;return(async()=>{try{const x=(await ze({signal:c.signal})).filter(p=>p.enabled),f=await Promise.all(x.map(p=>Fe(p.id,void 0,{signal:c.signal})));if(c.signal.aborted||i.current!==u)return;const g=f.some(p=>p.sessions.some(m=>m.unread_count>0));o(g)}catch{}})(),(()=>c.abort())},[]),l.useEffect(()=>Ve(o),[]),{notifyIncomingMessage:l.useCallback(c=>{c.direction!=="incoming"||c.message_type==="system"||(i.current+=1,n(u=>u+1),o(!0))},[]),hasUnreadChatMessage:t}},Ze=()=>{const e=Je(),{notifyIncomingMessage:n,hasUnreadChatMessage:t}=e;return l.useEffect(()=>{let o=!1,r=0,i=0,a=null;const c=()=>{if(o)return;C("connecting");const u=window.location.protocol==="https:"?"wss:":"ws:";a=new WebSocket(`${u}//${window.location.host}/api/v1/chat/ws`),a.onopen=()=>{i=0,C("online")},a.onmessage=d=>{try{const x=JSON.parse(d.data).message;x&&(n(x),Be(x))}catch{}},a.onclose=()=>{if(o)return;C("offline");const d=Math.min(15e3,1e3*2**Math.min(i++,4));r=window.setTimeout(c,d)},a.onerror=()=>a==null?void 0:a.close()};return c(),(()=>{o=!0,window.clearTimeout(r),a==null||a.close(),C("offline")})},[n]),{hasUnreadChatMessage:t}},Ye=async e=>j("/health",void 0,e),R=l.lazy(()=>v(()=>import("./Dashboard-Ba2fUvQH.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),Ke=l.lazy(()=>v(()=>import("./AccountList-DgwrfNi_.js"),__vite__mapDeps([7,1,3,5,6]))),We=l.lazy(()=>v(()=>import("./OrderList-CXbMt2fz.js"),__vite__mapDeps([8,1,2,3,5,6]))),Qe=l.lazy(()=>v(()=>import("./CardList-CfmBeFUG.js"),__vite__mapDeps([9,1,3,5,6]))),Xe=l.lazy(()=>v(()=>import("./ItemList-CH6EVxKe.js"),__vite__mapDeps([10,1,3,5,6]))),et=l.lazy(()=>v(()=>import("./Settings-WRDun9wT.js"),__vite__mapDeps([11,1,3,5,6]))),tt=l.lazy(()=>v(()=>import("./Rules-4H5_byLi.js"),__vite__mapDeps([12,1,3,5,6]))),st=l.lazy(()=>v(()=>import("./Notifications-DHwrazHy.js"),__vite__mapDeps([13,1,3,5,6]))),nt=l.lazy(()=>v(()=>import("./Chat-MUERwcqZ.js"),__vite__mapDeps([14,1,5,6,3]))),rt=()=>s.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),at=({activeTab:e,isAdmin:n,deliveryRuleTarget:t,onConfigureDelivery:o,onDeliveryTargetHandled:r})=>{const i=c=>{o({cookieId:c.cookie_id,itemId:c.item_id,requestId:Date.now()})},a=()=>{switch(e){case"dashboard":return s.jsx(R,{});case"accounts":return s.jsx(Ke,{});case"chat":return s.jsx(nt,{});case"orders":return s.jsx(We,{});case"cards":return s.jsx(Qe,{});case"items":return s.jsx(Xe,{onConfigureDelivery:i});case"rules":return s.jsx(tt,{initialDeliveryTarget:t,onDeliveryTargetHandled:r});case"notifications":return s.jsx(st,{isAdmin:n});case"settings":return n?s.jsx(et,{}):s.jsx(R,{});default:return s.jsx(R,{})}};return s.jsx(l.Suspense,{fallback:s.jsx(rt,{}),children:a()})},ot=({activeTab:e,isAdmin:n,collapsed:t,deliveryRuleTarget:o,onToggleCollapsed:r,onNavigate:i,onLogout:a,onConfigureDelivery:c,onDeliveryTargetHandled:u})=>{const[d,h]=l.useState({version:"dev",commit:"unknown"}),{hasUnreadChatMessage:x}=Ze();return l.useEffect(()=>{const f=new AbortController;return Ye({signal:f.signal}).then(g=>h({version:String(g.version||"dev"),commit:String(g.commit||"unknown")})).catch(g=>{g instanceof DOMException&&g.name}),(()=>f.abort())},[]),s.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[s.jsx(qe,{activeTab:e,isAdmin:n,collapsed:t,onToggleCollapsed:r,onNavigate:i,onLogout:a,buildInfo:d,hasUnreadChatMessage:x}),s.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${t?"ml-16":"ml-64"} ${e==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[s.jsx("div",{className:"fixed top-0 right-0 -z-10 h-[800px] w-[800px] pointer-events-none rounded-full bg-gradient-to-bl from-blue-50 to-transparent opacity-60 blur-[120px]"}),s.jsx("div",{className:`${e==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:s.jsx(at,{activeTab:e,isAdmin:n,deliveryRuleTarget:o,onConfigureDelivery:c,onDeliveryTargetHandled:u})})]})]})},X={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/chat":"chat","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},I=Object.fromEntries(Object.entries(X).map(([e,n])=>[n,e])),B=()=>X[window.location.pathname]??"dashboard",it=()=>{const{isLoggedIn:e,isAdmin:n,signOut:t}=Z(),[o,r]=l.useState(B),[i,a]=l.useState(),[c,u]=l.useState(Ie);l.useEffect(()=>{const m=()=>r(B());return window.addEventListener("popstate",m),(()=>window.removeEventListener("popstate",m))},[]),l.useEffect(()=>{e&&!n&&o==="settings"&&(window.history.replaceState({},"",I.dashboard),r("dashboard"))},[o,n,e]);const d=m=>{const y=m==="settings"&&!n?"dashboard":m,L=I[y];L!==window.location.pathname&&window.history.pushState({},"",L),r(y)},h=m=>{const y=Object.prototype.hasOwnProperty.call(I,m)?m:"dashboard";d(y)},x=async()=>{try{await t()}catch(m){console.error("退出登录失败",m)}},f=()=>{u(m=>{const y=!m;return Oe(y),y})},g=m=>{a(m),d("rules")},p=()=>a(void 0);return e?s.jsx(ot,{activeTab:o,isAdmin:n,collapsed:c,deliveryRuleTarget:i,onToggleCollapsed:f,onNavigate:h,onLogout:x,onConfigureDelivery:g,onDeliveryTargetHandled:p}):s.jsx($e,{})},ct=()=>s.jsx(we,{children:s.jsx(Re,{children:s.jsx(it,{})})}),ee=document.getElementById("root");if(!ee)throw new Error("Could not find root element to mount to");const lt=ne.createRoot(ee);lt.render(s.jsx(M.StrictMode,{children:s.jsx(ct,{})}));export{N as A,P as a,G as b,pt as c,Ce as d,ft as e,Fe as f,j as g,jt as h,xt as i,yt as j,bt as k,ze as l,wt as m,gt as n,W as o,mt as p,T as r,vt as s}; diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index 999185e..d5c86f8 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,7 +6,7 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - + diff --git a/tools/apicheck/main.go b/tools/apicheck/main.go index fd1b877..68f59f4 100644 --- a/tools/apicheck/main.go +++ b/tools/apicheck/main.go @@ -6,22 +6,12 @@ import ( "fmt" "os" "path/filepath" - "regexp" - "sort" "strings" "github.com/getkin/kin-openapi/openapi3" ) -// routeKey 是路由方法与路径的稳定组合键。 -type routeKey struct { - // method 是小写 HTTP 方法。 - method string - // path 是 chi 路由路径。 - path string -} - -// main 加载并验证 OpenAPI 文档,同时检查真实版本化路由的双向覆盖。 +// main 加载并验证 OpenAPI 文档的静态结构;真实 chi 路由双向覆盖由 Server 契约测试执行。 func main() { // root 是待检查仓库根目录,默认使用当前工作目录。 root := "." @@ -43,7 +33,7 @@ func main() { fmt.Println("api-check: 通过") } -// check 执行规范语法、operation 元数据和路由双向覆盖检查。 +// check 执行规范语法和 operation 元数据检查。 func check(root string) ([]string, error) { // specPath 是仓库中唯一 OpenAPI 契约文件路径。 specPath := filepath.Join(root, "api", "openapi.yaml") @@ -63,12 +53,18 @@ func check(root string) ([]string, error) { item := document.Paths.Find(path) for method, operation := range item.Operations() { // method、operation 是当前 HTTP 方法和定义。 method = strings.ToLower(method) + // exceptionKind 是当前 operation 显式声明的成功响应特殊校验类型;空值表示必须具备普通成功响应。 + exceptionKind := contractSuccessExceptionKind(operation) if operation.OperationID == "" { violations = append(violations, fmt.Sprintf("%s %s 缺少 operationId", strings.ToUpper(method), path)) } - if operation.Responses == nil || !hasSuccessResponse(operation.Responses) { + if operation.Responses == nil || exceptionKind == "" && !hasSuccessResponse(operation.Responses) { violations = append(violations, fmt.Sprintf("%s %s 缺少成功响应", strings.ToUpper(method), path)) } + // exceptionViolations 是特殊成功校验元数据不满足其受限语义时产生的全部错误。 + for _, exceptionViolation := range validateContractSuccessException(operation) { + violations = append(violations, fmt.Sprintf("%s %s %s", strings.ToUpper(method), path, exceptionViolation)) + } if operation.Responses == nil || operation.Responses.Value("400") == nil || operation.Responses.Value("401") == nil { violations = append(violations, fmt.Sprintf("%s %s 缺少统一错误响应", strings.ToUpper(method), path)) } @@ -77,34 +73,97 @@ func check(root string) ([]string, error) { } } } - // routes、err 分别是真实版本化路由集合和收集失败原因。 - routes, err := sourceRoutes(filepath.Join(root, "internal", "server")) - if err != nil { - return nil, err - } - // specRoutes 保存规范登记的路由方法和路径组合键。 - specRoutes := make(map[routeKey]struct{}) - for _, path := range document.Paths.Keys() { // path 是当前规范路径模板。 - for method := range document.Paths.Find(path).Operations() { // method 是当前规范 HTTP 方法。 - specRoutes[routeKey{method: strings.ToLower(method), path: path}] = struct{}{} - } - } - for route := range routes { // route 是真实 Router 中发现的 operation。 - // exists 表示真实 operation 是否已经登记到 OpenAPI。 - if _, exists := specRoutes[route]; !exists { - violations = append(violations, fmt.Sprintf("真实路由 %s %s 未登记到 api/openapi.yaml", strings.ToUpper(route.method), route.path)) - } - } - for route := range specRoutes { // route 是规范中声明的 operation。 - // exists 表示规范 operation 是否存在真实版本化路由。 - if _, exists := routes[route]; !exists { - violations = append(violations, fmt.Sprintf("OpenAPI 登记 %s %s 不存在真实版本化路由", strings.ToUpper(route.method), route.path)) - } - } - sort.Strings(violations) return violations, nil } +// contractSuccessExceptionKind 返回 operation 显式登记的成功响应特殊校验类型;无法解析的值交给校验函数报错。 +func contractSuccessExceptionKind(operation *openapi3.Operation) string { + if operation == nil || operation.Extensions == nil { + return "" + } + // rawException、exists 分别是 YAML 扩展原值及其是否已登记。 + rawException, exists := operation.Extensions["x-contract-success-exception"] + if !exists { + return "" + } + // exception、ok 分别是扩展对象及其结构是否符合 OpenAPI 扩展的 YAML 解码结果。 + exception, ok := rawException.(map[string]any) + if !ok { + return "" + } + // kind、ok 分别是特殊校验类别及其字符串类型断言结果。 + kind, ok := exception["kind"].(string) + if !ok { + return "" + } + return kind +} + +// validateContractSuccessException 只允许 WebSocket、二进制和永久关闭接口跳过普通 2xx 成功响应,并验证各自的强制契约。 +func validateContractSuccessException(operation *openapi3.Operation) []string { + if operation == nil || operation.Extensions == nil { + return nil + } + // rawException、exists 分别是特殊校验扩展原值及是否显式登记。 + rawException, exists := operation.Extensions["x-contract-success-exception"] + if !exists { + return nil + } + // exception、ok 分别是解码后的扩展对象及其结构是否有效。 + exception, ok := rawException.(map[string]any) + if !ok { + return []string{"x-contract-success-exception 必须是包含 kind 的对象"} + } + // kind、ok 分别是特殊校验类别及其是否为字符串。 + kind, ok := exception["kind"].(string) + if !ok { + return []string{"x-contract-success-exception.kind 必须是字符串"} + } + switch kind { + case "websocket": + if operation.Responses == nil || operation.Responses.Value("101") == nil { + return []string{"WebSocket 特殊校验必须声明 101 协议升级响应"} + } + // exists 表示 WebSocket operation 是否同时登记了可校验的服务端事件 schema。 + if _, exists := operation.Extensions["x-websocket-message-schema"]; !exists { + return []string{"WebSocket 特殊校验必须声明 x-websocket-message-schema"} + } + case "binary": + if !hasBinarySuccessResponse(operation.Responses) { + return []string{"二进制特殊校验必须声明含 binary format 的 2xx 响应"} + } + case "permanently_disabled": + if hasSuccessResponse(operation.Responses) || operation.Responses == nil || operation.Responses.Value("501") == nil { + return []string{"永久关闭特殊校验只能声明 501 错误响应,不得保留 2xx 或 101 成功响应"} + } + default: + return []string{fmt.Sprintf("不支持的 x-contract-success-exception.kind %q", kind)} + } + return nil +} + +// hasBinarySuccessResponse 判断 operation 是否声明内容格式为 binary 的普通 HTTP 成功响应。 +func hasBinarySuccessResponse(responses *openapi3.Responses) bool { + if responses == nil { + return false + } + // status 是当前待检查的 2xx 成功状态码。 + for _, status := range []string{"200", "201", "202", "204"} { + // responseRef 是当前状态码对应的 OpenAPI 响应定义。 + responseRef := responses.Value(status) + if responseRef == nil || responseRef.Value == nil { + continue + } + // mediaType、media 分别是当前响应声明的媒体类型及其 schema 定义。 + for mediaType, media := range responseRef.Value.Content { + if media != nil && media.Schema != nil && media.Schema.Value != nil && media.Schema.Value.Format == "binary" && !strings.HasPrefix(mediaType, "application/json") { + return true + } + } + } + return false +} + // hasSuccessResponse 判断 operation 是否声明了至少一个合法成功或协议升级状态。 func hasSuccessResponse(responses *openapi3.Responses) bool { if responses == nil { @@ -118,38 +177,3 @@ func hasSuccessResponse(responses *openapi3.Responses) bool { } return false } - -// sourceRoutes 从版本化 route 文件和动态订单刷新挂载点收集真实路由。 -func sourceRoutes(serverDir string) (map[routeKey]struct{}, error) { - // methodPattern 匹配版本化文件中的静态 chi 方法调用。 - methodPattern := regexp.MustCompile(`r\.(Get|Post|Put|Patch|Delete)\("([^"\n]+)"`) - // routes 保存扫描到的真实版本化路由。 - routes := make(map[routeKey]struct{}) - // entries、err 分别是路由目录项和读取失败原因。 - entries, err := os.ReadDir(serverDir) - if err != nil { - return nil, fmt.Errorf("读取 Server 路由目录失败: %w", err) - } - for _, entry := range entries { // entry 是当前版本化路由源文件目录项。 - if entry.IsDir() || !strings.HasPrefix(entry.Name(), "versioned_") || !strings.HasSuffix(entry.Name(), ".go") { - continue - } - // source、readErr 分别是路由源码和读取失败原因。 - source, readErr := os.ReadFile(filepath.Join(serverDir, entry.Name())) - if readErr != nil { - return nil, fmt.Errorf("读取路由文件 %s 失败: %w", entry.Name(), readErr) - } - for _, match := range methodPattern.FindAllSubmatch(source, -1) { // match 是当前静态路由匹配结果。 - // path 是匹配结果中的 chi 路由路径。 - path := string(match[2]) - if path == "/health" || strings.HasPrefix(path, "/api/v1/") { - routes[routeKey{method: strings.ToLower(string(match[1])), path: path}] = struct{}{} - } - } - } - // mountOrderRefreshJobRoutes 使用 prefix 拼接路径,静态正则无法看到其三个 operation。 - routes[routeKey{method: "post", path: "/api/v1/orders/refresh"}] = struct{}{} - routes[routeKey{method: "get", path: "/api/v1/orders/refresh/{job_id}"}] = struct{}{} - routes[routeKey{method: "delete", path: "/api/v1/orders/refresh/{job_id}"}] = struct{}{} - return routes, nil -} diff --git a/tools/apicheck/main_test.go b/tools/apicheck/main_test.go index 2ca23a0..18783e2 100644 --- a/tools/apicheck/main_test.go +++ b/tools/apicheck/main_test.go @@ -1,40 +1,78 @@ package main import ( - "os" - "path/filepath" "testing" + + "github.com/getkin/kin-openapi/openapi3" ) -// TestSourceRoutesIncludesDynamicOrderRefresh 验证动态 prefix 挂载的订单刷新 operation 不会从路由登记中遗漏。 -func TestSourceRoutesIncludesDynamicOrderRefresh(t *testing.T) { - // serverDir 是本测试构造的版本化路由源码目录。 - serverDir := t.TempDir() - // source 是包含一个静态路由的最小 chi 路由源码夹具。 - source := []byte(`package server -func mount(r any) { - r.Get("/api/v1/session", nil) -} -`) - // writeErr 是写入路由源码夹具失败的原因。 - if writeErr := os.WriteFile(filepath.Join(serverDir, "versioned_session_routes.go"), source, 0o600); writeErr != nil { - t.Fatal(writeErr) +// TestContractSuccessExceptionValidation 验证特殊成功校验只接受 WebSocket、二进制和永久关闭三类受限契约。 +func TestContractSuccessExceptionValidation(t *testing.T) { + // websocketResponses 是包含 101 协议升级响应的 WebSocket 最小响应集合。 + websocketResponses := openapi3.NewResponses(openapi3.WithStatus(101, &openapi3.ResponseRef{Value: openapi3.NewResponse().WithDescription("upgrade")})) + // websocketOperation 是登记消息 schema 的合法 WebSocket operation。 + websocketOperation := &openapi3.Operation{Responses: websocketResponses, Extensions: map[string]any{ + "x-contract-success-exception": map[string]any{"kind": "websocket"}, + "x-websocket-message-schema": map[string]any{"$ref": "#/components/schemas/Event"}, + }} + // got 是从合法 WebSocket operation 解析出的特殊校验类别。 + if got := contractSuccessExceptionKind(websocketOperation); got != "websocket" { + t.Fatalf("特殊类型=%q", got) } - // routes、readErr 分别是收集到的路由集合和读取失败原因。 - routes, readErr := sourceRoutes(serverDir) - if readErr != nil { - t.Fatal(readErr) + // violations 保存合法 WebSocket operation 产生的结构违规,预期为空。 + if violations := validateContractSuccessException(websocketOperation); len(violations) != 0 { + t.Fatalf("合法 WebSocket 特殊校验失败: %v", violations) } - // expected 是动态订单刷新 POST operation 的稳定键。 - expected := routeKey{method: "post", path: "/api/v1/orders/refresh"} - // exists 表示动态订单刷新 operation 是否已被发现。 - if _, exists := routes[expected]; !exists { - t.Fatalf("动态订单刷新路由未登记: %+v", routes) + // missingUpgradeOperation 是缺少 101 响应的 WebSocket 错误夹具。 + missingUpgradeOperation := &openapi3.Operation{Responses: openapi3.NewResponses(), Extensions: websocketOperation.Extensions} + // violations 保存缺少升级响应时必须出现的结构违规。 + if violations := validateContractSuccessException(missingUpgradeOperation); len(violations) == 0 { + t.Fatal("缺少 101 的 WebSocket 未被拒绝") } - // staticRoute 是夹具中的静态 session operation。 - staticRoute := routeKey{method: "get", path: "/api/v1/session"} - // exists 表示静态 session operation 是否已被发现。 - if _, exists := routes[staticRoute]; !exists { - t.Fatalf("静态路由未登记: %+v", routes) + // missingSchemaOperation 是缺少消息 schema 扩展的 WebSocket 错误夹具。 + missingSchemaOperation := &openapi3.Operation{Responses: websocketResponses, Extensions: map[string]any{"x-contract-success-exception": map[string]any{"kind": "websocket"}}} + // violations 保存缺少事件 schema 时必须出现的结构违规。 + if violations := validateContractSuccessException(missingSchemaOperation); len(violations) == 0 { + t.Fatal("缺少消息 schema 的 WebSocket 未被拒绝") + } + // binaryResponses 是包含 binary schema 的 CSV 成功响应集合。 + binaryResponses := openapi3.NewResponses(openapi3.WithStatus(200, &openapi3.ResponseRef{Value: openapi3.NewResponse().WithContent(openapi3.Content{ + "text/csv": &openapi3.MediaType{Schema: &openapi3.SchemaRef{Value: &openapi3.Schema{Format: "binary"}}}, + })})) + // binaryOperation 是合法二进制下载 operation。 + binaryOperation := &openapi3.Operation{Responses: binaryResponses, Extensions: map[string]any{"x-contract-success-exception": map[string]any{"kind": "binary"}}} + if !hasBinarySuccessResponse(binaryResponses) || len(validateContractSuccessException(binaryOperation)) != 0 { + t.Fatal("合法二进制特殊校验失败") + } + // invalidBinaryOperation 是缺少 binary format 的二进制错误夹具。 + invalidBinaryOperation := &openapi3.Operation{Responses: openapi3.NewResponses(openapi3.WithStatus(200, &openapi3.ResponseRef{Value: openapi3.NewResponse()})), Extensions: binaryOperation.Extensions} + // violations 保存二进制下载缺少 binary schema 时必须出现的结构违规。 + if violations := validateContractSuccessException(invalidBinaryOperation); len(violations) == 0 { + t.Fatal("缺少 binary schema 的特殊校验未被拒绝") + } + // disabledOperation 是不声明任何 2xx、只声明 501 的永久关闭 operation。 + disabledOperation := &openapi3.Operation{Responses: openapi3.NewResponses(openapi3.WithStatus(501, &openapi3.ResponseRef{Value: openapi3.NewResponse()})), Extensions: map[string]any{"x-contract-success-exception": map[string]any{"kind": "permanently_disabled"}}} + if len(validateContractSuccessException(disabledOperation)) != 0 { + t.Fatal("合法永久关闭特殊校验失败") + } + // invalidDisabledOperation 是错误保留 200 成功响应的永久关闭 operation。 + invalidDisabledOperation := &openapi3.Operation{Responses: openapi3.NewResponses( + openapi3.WithStatus(200, &openapi3.ResponseRef{Value: openapi3.NewResponse()}), + openapi3.WithStatus(501, &openapi3.ResponseRef{Value: openapi3.NewResponse()}), + ), Extensions: disabledOperation.Extensions} + // violations 保存永久关闭 operation 仍声明成功码时必须出现的结构违规。 + if violations := validateContractSuccessException(invalidDisabledOperation); len(violations) == 0 { + t.Fatal("保留 200 的永久关闭 operation 未被拒绝") + } + // invalidKindOperation 是未登记类别的特殊校验 operation。 + invalidKindOperation := &openapi3.Operation{Extensions: map[string]any{"x-contract-success-exception": map[string]any{"kind": "other"}}} + // violations 保存未知特殊校验类别必须产生的结构违规。 + if violations := validateContractSuccessException(invalidKindOperation); len(violations) == 0 { + t.Fatal("未知特殊校验类别未被拒绝") + } + // malformedOperation 是扩展值不是对象的错误 operation。 + malformedOperation := &openapi3.Operation{Extensions: map[string]any{"x-contract-success-exception": "websocket"}} + if contractSuccessExceptionKind(malformedOperation) != "" || len(validateContractSuccessException(malformedOperation)) == 0 { + t.Fatal("格式错误的特殊校验扩展未被拒绝") } } diff --git a/tools/architecturecheck/main_test.go b/tools/architecturecheck/main_test.go index b1d66b9..e82dd6a 100644 --- a/tools/architecturecheck/main_test.go +++ b/tools/architecturecheck/main_test.go @@ -8,7 +8,6 @@ import ( "testing" ) - // TestHTTPResponseContractBoundary 验证 HTTP 契约扫描会拒绝动态 map 和直接 map 响应。 func TestHTTPResponseContractBoundary(t *testing.T) { // fset 是模拟 Server 源码的文件位置集合。 diff --git a/tools/architecturecheck/phase_policy.go b/tools/architecturecheck/phase_policy.go index fd194d8..06f3441 100644 --- a/tools/architecturecheck/phase_policy.go +++ b/tools/architecturecheck/phase_policy.go @@ -100,6 +100,68 @@ func checkActivatedRepositoryGates(root string, activeStage int) []violation { } if architectureStageEnabled(activeStage, architectureStageClosure) { violations = append(violations, checkQualityArchitecture(root)...) + violations = append(violations, checkOpenAPIContractClosure(root)...) + } + return violations +} + +// checkOpenAPIContractClosure 永久禁止手写 transport 汇总、生成类型越过契约层和旧 HTTP 请求旁路回流。 +func checkOpenAPIContractClosure(root string) []violation { + // violations 保存 OpenAPI 契约闭环的物理文件和依赖方向违规。 + var violations []violation + // frontendRoot 是前端源码根目录,用于定位只读生成类型和 feature adapter。 + frontendRoot := filepath.Join(root, "frontend") + // legacyTransportPath 是阶段六必须永久删除的手写 DTO 汇总文件。 + legacyTransportPath := filepath.Join(frontendRoot, "shared", "api-contract", "transport.ts") + // statErr 表示旧手写 DTO 汇总文件是否仍然存在。 + if _, statErr := os.Stat(legacyTransportPath); statErr == nil { + violations = append(violations, violation{file: "frontend/shared/api-contract/transport.ts", line: 1, message: "阶段六禁止重新引入手写 transport DTO 汇总;必须使用生成类型或所属 feature UI 模型"}) + } + // importPattern 提取静态 import 和 export-from 的模块路径,避免通过 re-export 隐藏旁路。 + importPattern := regexp.MustCompile(`(?m)(?:from\s+)["']([^"']+)["']`) + // walkErr 是扫描前端生产源码时的文件系统错误。 + walkErr := filepath.WalkDir(frontendRoot, func(path string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.IsDir() { + if entry.Name() == "node_modules" || entry.Name() == "coverage" || entry.Name() == "dist" { + return filepath.SkipDir + } + return nil + } + if !isFrontendProductionPath(path) { + return nil + } + // relativePath 是当前源码相对于 frontend 的稳定路径。 + relativePath, relativeErr := filepath.Rel(frontendRoot, path) + if relativeErr != nil { + return relativeErr + } + relativePath = filepath.ToSlash(relativePath) + // source、readErr 分别保存源码文本及读取失败原因。 + source, readErr := os.ReadFile(path) + if readErr != nil { + return readErr + } + // sourceText 是当前文件的字符串视图,供稳定依赖检查使用。 + sourceText := string(source) + // match 是当前静态导入或再导出的完整正则匹配结果。 + for _, match := range importPattern.FindAllStringSubmatch(sourceText, -1) { + // specifier 是当前静态导入或再导出的模块路径。 + specifier := match[1] + if strings.HasSuffix(specifier, "/transport") || strings.HasSuffix(specifier, "/transport.ts") { + violations = append(violations, violation{file: "frontend/" + relativePath, line: sourceLineAt(source, strings.Index(sourceText, match[0])), message: "阶段六禁止引用手写 transport DTO;请改用生成契约或 feature UI 模型"}) + } + // shared/api-contract 是生成类型的唯一宿主;feature 只能经自己的 api adapter 使用类型。 + if strings.Contains(specifier, "generated/schema") && !strings.HasPrefix(relativePath, "shared/api-contract/") { + violations = append(violations, violation{file: "frontend/" + relativePath, line: sourceLineAt(source, strings.Index(sourceText, match[0])), message: "生成 OpenAPI 类型不得越过 shared 契约层直接进入 feature、组件或 Hook"}) + } + } + return nil + }) + if walkErr != nil { + violations = append(violations, violation{file: "frontend", line: 1, message: fmt.Sprintf("扫描 OpenAPI 契约闭环失败: %v", walkErr)}) } return violations } @@ -243,6 +305,8 @@ func checkReactArchitecture(root string) []violation { } // modulePattern 提取静态 import、re-export 和动态 import 的模块路径。 modulePattern := regexp.MustCompile(`(?m)(?:from\s+|import\s*\()\s*["']([^"']+)["']`) + // legacyHTTPImportPattern 仅匹配旧 HTTP client 的具名导入,用于永久禁止 feature 恢复未类型化请求旁路。 + legacyHTTPImportPattern := regexp.MustCompile(`(?s)import\s*\{([^}]*)\}\s*from\s*["'][^"']*shared/http/client["']`) // walkErr 是遍历前端生产源码时的文件系统错误。 walkErr := filepath.WalkDir(frontendRoot, func(path string, entry fs.DirEntry, walkErr error) error { if walkErr != nil { @@ -270,6 +334,19 @@ func checkReactArchitecture(root string) []violation { } // sourceText 是用于模块和网络边界匹配的源码文本。 sourceText := string(source) + // legacyMatch 是当前 feature 对旧 HTTP client 的具名导入;只允许错误类型和请求控制类型继续复用。 + for _, legacyMatch := range legacyHTTPImportPattern.FindAllStringSubmatch(sourceText, -1) { + // importedNames 保存去除 type 与别名后的本地导入名称。 + importedNames := strings.Split(legacyMatch[1], ",") + // importedName 是当前待核验的旧 client 导入名称。 + for _, importedName := range importedNames { + // normalizedName 是去除 TypeScript type 前缀与别名后的源导出名称。 + normalizedName := strings.TrimSpace(strings.Split(strings.TrimPrefix(strings.TrimSpace(importedName), "type "), " as ")[0]) + if normalizedName == "get" || normalizedName == "post" || normalizedName == "put" || normalizedName == "del" || normalizedName == "postForm" { + violations = append(violations, violation{file: "frontend/" + relativePath, line: sourceLineAt(source, strings.Index(sourceText, legacyMatch[0])), message: "feature 禁止导入旧 HTTP get/post/put/del/postForm;必须使用生成契约客户端"}) + } + } + } if relativePath != "shared/http/client.ts" && relativePath != "shared/api-contract/client.ts" && (strings.Contains(sourceText, "fetch(") || regexp.MustCompile(`\baxios\b`).MatchString(sourceText)) { violations = append(violations, violation{file: "frontend/" + relativePath, line: 1, message: "前端生产代码不得绕过共享 HTTP 契约客户端直接请求网络"}) } diff --git a/tools/architecturecheck/phase_policy_test.go b/tools/architecturecheck/phase_policy_test.go index e4e4e67..d8f1c4b 100644 --- a/tools/architecturecheck/phase_policy_test.go +++ b/tools/architecturecheck/phase_policy_test.go @@ -213,3 +213,34 @@ func TestQualityArchitectureGate(t *testing.T) { t.Fatalf("violations=%+v", violations) } } + +// TestOpenAPIContractClosureGate 验证阶段六拒绝手写 DTO 汇总和 feature 直接读取生成 schema。 +func TestOpenAPIContractClosureGate(t *testing.T) { + // root 是承载阶段六违规样例的独立临时仓库。 + root := t.TempDir() + // transportPath 是模拟被错误恢复的旧手写 DTO 汇总文件。 + transportPath := filepath.Join(root, "frontend", "shared", "api-contract", "transport.ts") + // mkdirErr 表示创建旧 DTO 样例目录失败的原因。 + if mkdirErr := os.MkdirAll(filepath.Dir(transportPath), 0o755); mkdirErr != nil { + t.Fatal(mkdirErr) + } + // writeErr 表示写入旧 DTO 样例失败的原因。 + if writeErr := os.WriteFile(transportPath, []byte("export interface Legacy {}\n"), 0o600); writeErr != nil { + t.Fatal(writeErr) + } + // featurePath 是绕过 adapter 直接导入生成 schema 的 feature UI 样例。 + featurePath := filepath.Join(root, "frontend", "app", "features", "items", "page.tsx") + // mkdirErr 表示创建 feature 样例目录失败的原因。 + if mkdirErr := os.MkdirAll(filepath.Dir(featurePath), 0o755); mkdirErr != nil { + t.Fatal(mkdirErr) + } + // writeErr 表示写入 feature 旁路样例失败的原因。 + if writeErr := os.WriteFile(featurePath, []byte("import type { components } from '../../../shared/api-contract/generated/schema';\ntype Row = components['schemas']['ItemListResponse'];\n"), 0o600); writeErr != nil { + t.Fatal(writeErr) + } + // violations 是闭环门禁必须同时报告的两类绕过。 + violations := checkOpenAPIContractClosure(root) + if len(violations) != 2 { + t.Fatalf("violations=%+v", violations) + } +}