Skip to content

Let's use AI to Earn!

fix(web): pay task one1 (#452)

布莱恩·奥夫托·杰森张f6989f9960c8
diff --git a/project/web/src/api/payment.ts b/project/web/src/api/payment.ts
index 82abf37c..d0ce2b41 100644
--- a/project/web/src/api/payment.ts
+++ b/project/web/src/api/payment.ts
@@ -73,3 +73,195 @@ export function cancelSubscriptionApi(params: any) {
data: params,
})
}
+
+/**
+ * 获取收入记录列表
+ */
+export function getIncomeListApi(params: {
+ currency?: 'CNY' | 'UNK' | 'USD'
+ page?: number
+ pageSize?: number
+ status?: 'pending' | 'withdrawn'
+ type?: 'reward_back' | 'task' | 'task_back' | 'task_withdraw'
+ [property: string]: any
+}) {
+ return request<PaginatedResponse<any>>({
+ url: 'payment/income',
+ method: 'GET',
+ params,
+ })
+}
+
+/**
+ * 获取收入记录详情
+ */
+export function getIncomeDetailApi(id: string) {
+ return request<any>({
+ url: `payment/income/${id}`,
+ method: 'GET',
+ })
+}
+
+/**
+ * 创建提现申请
+ */
+export function createWithdrawApi(params: {
+ amount: number
+ currency: 'CNY' | 'UNK' | 'USD'
+ incomeRecordIds?: string[]
+ metadata?: { [key: string]: any }
+ relId?: string
+ type: 'reward' | 'task'
+ walletAccountId: string
+ [property: string]: any
+}) {
+ return request<any>({
+ url: 'payment/withdraw',
+ method: 'POST',
+ data: params,
+ })
+}
+
+/**
+ * 获取提现记录列表
+ */
+export function getWithdrawListApi(params: {
+ currency?: 'CNY' | 'UNK' | 'USD'
+ page?: number
+ pageSize?: number
+ status?: 'approved' | 'failed' | 'paid' | 'pending' | 'rejected'
+ type?: 'reward' | 'task'
+ [property: string]: any
+}) {
+ return request<PaginatedResponse<any>>({
+ url: 'payment/withdraw',
+ method: 'GET',
+ params,
+ })
+}
+
+/**
+ * 提现全部待提现收入
+ */
+export function withdrawAllPendingApi(params: {
+ currency: 'CNY' | 'UNK' | 'USD'
+ type?: 'reward' | 'task'
+ walletAccountId: string
+ [property: string]: any
+}) {
+ return request<any>({
+ url: 'payment/withdraw/all-pending',
+ method: 'POST',
+ data: params,
+ })
+}
+
+/**
+ * 获取提现记录详情
+ */
+export function getWithdrawDetailApi(id: string) {
+ return request<any>({
+ url: `payment/withdraw/${id}`,
+ method: 'GET',
+ })
+}
+
+/**
+ * 取消提现申请
+ */
+export function cancelWithdrawApi(id: string) {
+ return request<any>({
+ url: `payment/withdraw/${id}/cancel`,
+ method: 'POST',
+ })
+}
+
+/**
+ * 创建钱包账户
+ */
+export function createWalletAccountApi(params: {
+ account?: string
+ email?: string
+ idCard?: string
+ isDefault?: boolean
+ phone?: string
+ stripeConnectedAccountId?: string
+ type: 'alipay' | 'stripe_connect' | 'wechat_pay'
+ userName?: string
+ [property: string]: any
+}) {
+ return request<any>({
+ url: 'payment/user-wallet-account',
+ method: 'POST',
+ data: params,
+ })
+}
+
+/**
+ * 获取钱包账户列表
+ */
+export function getWalletAccountListApi(params: {
+ page?: number
+ pageSize?: number
+ type?: 'alipay' | 'stripe_connect' | 'wechat_pay'
+ [property: string]: any
+}) {
+ return request<{
+ page: number
+ pageSize: number
+ totalPages: number
+ total: number
+ list: any[]
+ }>({
+ url: 'payment/user-wallet-account',
+ method: 'GET',
+ params,
+ })
+}
+
+/**
+ * 获取钱包账户详情
+ */
+export function getWalletAccountDetailApi(id: string) {
+ return request<any>({
+ url: `payment/user-wallet-account/${id}`,
+ method: 'GET',
+ })
+}
+
+/**
+ * 更新钱包账户
+ */
+export function updateWalletAccountApi(id: string, params: {
+ email?: string
+ idCard?: string
+ phone?: string
+ userName?: string
+ [property: string]: any
+}) {
+ return request<any>({
+ url: `payment/user-wallet-account/${id}`,
+ method: 'PATCH',
+ data: params,
+ })
+}
+
+/**
+ * 删除钱包账户
+ */
+export function deleteWalletAccountApi(id: string) {
+ return request<any>({
+ url: `payment/user-wallet-account/${id}`,
+ method: 'DELETE',
+ })
+}
+
+/**
+ * 设置为默认钱包账户
+ */
+export function setDefaultWalletAccountApi(id: string) {
+ return request<any>({
+ url: `payment/user-wallet-account/${id}/set-default`,
+ method: 'POST',
+ })
+}
\ No newline at end of file
diff --git a/project/web/src/api/types/income.ts b/project/web/src/api/types/income.ts
index 139d200c..ce7c6655 100644
--- a/project/web/src/api/types/income.ts
+++ b/project/web/src/api/types/income.ts
@@ -2,6 +2,36 @@ export enum IncomeType {
TASK = 'task', // 任务
TASK_BACK = 'task_back', // 任务回退
REWARD_BACK = 'reward_back', // 奖励回退
+ TASK_WITHDRAW = 'task_withdraw', // 任务提现
+}
+
+// 新 API 枚举类型
+export enum Currency {
+ Cny = 'CNY',
+ Unk = 'UNK',
+ Usd = 'USD',
+}
+
+export enum IncomeStatus {
+ Pending = 'pending',
+ Withdrawn = 'withdrawn',
+}
+
+export enum IncomeTypeEnum {
+ RewardBack = 'reward_back',
+ Task = 'task',
+ TaskBack = 'task_back',
+ TaskWithdraw = 'task_withdraw',
+}
+
+// 收入记录请求参数
+export interface IncomeListRequest {
+ currency?: Currency
+ page?: number
+ pageSize?: number
+ status?: IncomeStatus
+ type?: IncomeTypeEnum
+ [property: string]: any
}
// 订单类型 (根据实际API返回结构)
@@ -11,11 +41,12 @@ export interface IncomeRecord {
userId: string
amount: number
relId?: string
- type: IncomeType
+ type: IncomeType | IncomeTypeEnum
desc?: string
metadata?: Record<string, unknown>
- // 提现状态:1=可提现,0=已申请
- status?: number
+ // 提现状态:1=可提现,0=已申请 或 pending/withdrawn
+ status?: number | IncomeStatus
createdAt: Date
updatedAt: Date
+ currency?: Currency
}
diff --git a/project/web/src/api/types/userWalletAccount.ts b/project/web/src/api/types/userWalletAccount.ts
index 7b886150..ed818cd3 100644
--- a/project/web/src/api/types/userWalletAccount.ts
+++ b/project/web/src/api/types/userWalletAccount.ts
@@ -1,35 +1,76 @@
-/*
- * @Author: nevin
- * @Date: 2025-03-01 19:27:35
- * @LastEditTime: 2025-03-01 19:39:02
- * @LastEditors: nevin
- * @Description: 用户钱包账户
- */
+// 旧类型(保留兼容)
+export type WalletType = 'ZFB' | 'WX_PAY'
+
+export interface UserWalletAccountCreateDto {
+ userId: string
+ mail: string // email
+ userName?: string
+ account: string
+ cardNum?: string
+ phone?: string
+ type: WalletType
+}
+
+export interface UserWalletAccount extends UserWalletAccountCreateDto {
+ _id: string
+ createdAt?: string
+ updatedAt?: string
+}
+
+// 新API类型
export enum WalletAccountType {
- ZFB = 'ZFB',
- WX_PAY = 'WX_PAY',
+ Alipay = 'alipay',
+ StripeConnect = 'stripe_connect',
+ WechatPay = 'wechat_pay',
}
-export interface UserWallet {
- userId: string
- balance: number
- income: number
+export interface WalletAccountRequest {
+ account?: string
+ email?: string
+ idCard?: string
+ isDefault?: boolean
+ phone?: string
+ stripeConnectedAccountId?: string
+ type: WalletAccountType
+ userName?: string
+ [property: string]: any
+}
+
+export interface WalletAccountUpdateRequest {
+ email?: string
+ idCard?: string
+ phone?: string
+ userName?: string
+ [property: string]: any
}
-export interface UserWalletAccount {
+export interface WalletAccount {
id: string
- account: string // 账户号
userId: string
- userName: string // 真实姓名
- cardNum: string // 身份证号
- phone: string // 绑定的手机号
type: WalletAccountType
+ account: string
+ userName?: string
+ phone?: string
+ email?: string
+ idCard?: string
+ stripeConnectedAccountId?: string
+ isDefault: boolean
+ isVerified: boolean
+ createdAt: string
+ updatedAt: string
}
-export interface CreateUserWalletAccountParams {
- account: string // 账户号
- userName: string // 真实姓名
- cardNum: string // 身份证号
- phone: string // 绑定的手机号
- type: WalletAccountType
+export interface WalletAccountListRequest {
+ page?: number
+ pageSize?: number
+ type?: WalletAccountType
+ [property: string]: any
+}
+
+export interface WalletAccountListResponse {
+ page: number
+ pageSize: number
+ totalPages: number
+ total: number
+ list: WalletAccount[]
}
diff --git a/project/web/src/api/types/withdraw.ts b/project/web/src/api/types/withdraw.ts
index 3747fc87..6a6c8b72 100644
--- a/project/web/src/api/types/withdraw.ts
+++ b/project/web/src/api/types/withdraw.ts
@@ -1,8 +1,10 @@
+// 旧枚举(保留兼容)
export enum WithdrawRecordType {
TASK = 'task', // 任务
REWARD = 'reward', // 奖励
}
+// 旧状态枚举(保留兼容)
export enum WithdrawRecordStatus {
WAIT = 0,
SUCCESS = 1,
@@ -10,6 +12,27 @@ export enum WithdrawRecordStatus {
TASK_WITHDRAW = 2, // 任务提现
}
+// 新API枚举
+export enum Currency {
+ Cny = 'CNY',
+ Unk = 'UNK',
+ Usd = 'USD',
+}
+
+export enum WithdrawType {
+ Reward = 'reward',
+ Task = 'task',
+}
+
+export enum WithdrawStatus {
+ Approved = 'approved',
+ Failed = 'failed',
+ Paid = 'paid',
+ Pending = 'pending',
+ Rejected = 'rejected',
+}
+
+// 旧接口(保留兼容)
export interface WithdrawRecord {
_id: string
id: string
@@ -25,3 +48,60 @@ export interface WithdrawRecord {
createdAt: Date
updatedAt: Date
}
+
+// 新API接口
+export interface WalletAccountSnapshot {
+ [key: string]: string
+}
+
+export interface WithdrawRecordNew {
+ id: string
+ userId: string
+ amount: number
+ currency: Currency
+ type: WithdrawType
+ status: WithdrawStatus
+ walletAccountId: string
+ walletAccountSnapshot?: WalletAccountSnapshot
+ incomeRecordIds?: string[]
+ relId?: string
+ flowId?: string
+ stripeTransferId?: string
+ adminId?: string
+ adminNote?: string
+ screenshotUrls?: string[]
+ paidAt?: Date
+ metadata?: { [key: string]: any }
+ createdAt: Date
+ updatedAt: Date
+}
+
+// 创建提现申请请求
+export interface CreateWithdrawRequest {
+ amount: number
+ currency: Currency
+ incomeRecordIds?: string[]
+ metadata?: { [key: string]: any }
+ relId?: string
+ type: WithdrawType
+ walletAccountId: string
+ [property: string]: any
+}
+
+// 获取提现记录列表请求
+export interface GetWithdrawListRequest {
+ currency?: Currency
+ page?: number
+ pageSize?: number
+ status?: WithdrawStatus
+ type?: WithdrawType
+ [property: string]: any
+}
+
+// 提现全部待提现收入请求
+export interface WithdrawAllPendingRequest {
+ currency: Currency
+ type?: WithdrawType
+ walletAccountId: string
+ [property: string]: any
+}
diff --git a/project/web/src/app/[lng]/cgmaterial/cgmaterialPageCore.tsx b/project/web/src/app/[lng]/cgmaterial/cgmaterialPageCore.tsx
index fea18f0d..0d65029e 100644
--- a/project/web/src/app/[lng]/cgmaterial/cgmaterialPageCore.tsx
+++ b/project/web/src/app/[lng]/cgmaterial/cgmaterialPageCore.tsx
@@ -10,17 +10,13 @@ import Image from 'next/image'
import { useParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import { getAccountListApi } from '@/api/account'
-import { getChatModels } from '@/api/ai'
import { apiGetEngagementPosts } from '@/api/engagement'
import {
apiCreateMaterial,
apiCreateMaterialGroup,
- apiCreateMaterialTask,
apiDeleteMaterialGroup,
apiGetMaterialGroupList,
apiGetMaterialList,
- apiPreviewMaterialTask,
- apiStartMaterialTask,
apiUpdateMaterial,
apiUpdateMaterialGroupInfo,
} from '@/api/material'
@@ -76,27 +72,10 @@ export default function CgMaterialPageCore() {
// 单个素材位置
const [singleLocation, setSingleLocation] = useState<[number, number]>([0, 0])
- // 创建/批量表单
+ // 创建表单
const [form] = Form.useForm()
- const [batchForm] = Form.useForm()
const [createGroupForm] = Form.useForm()
const [creating, setCreating] = useState(false)
- const [batchModal, setBatchModal] = useState(false)
- const [batchTaskLoading, setBatchTaskLoading] = useState(false)
- const [chatModels, setChatModels] = useState<any[]>([])
- const [chatModelsLoading, setChatModelsLoading] = useState(false)
-
- // 批量生成草稿相关
- const [batchMediaGroups, setBatchMediaGroups] = useState<string[]>([])
- const [batchCoverGroup, setBatchCoverGroup] = useState<string>('')
- const [batchLocation, setBatchLocation] = useState<[number, number]>([0, 0])
- // 预览相关
- const [currentTaskId, setCurrentTaskId] = useState<string | null>(null)
- const [lastTaskParams, setLastTaskParams] = useState<any>(null)
- const [previewModal, setPreviewModal] = useState(false)
- const [previewLoading, setPreviewLoading] = useState(false)
- const [previewList, setPreviewList] = useState<any[]>([])
- const [previewData, setPreviewData] = useState<any>(null)
const [detailModal, setDetailModal] = useState(false)
const [detailData, setDetailData] = useState<any>(null)
@@ -487,128 +466,6 @@ export default function CgMaterialPageCore() {
}
}
- // 打开批量生成草稿弹窗时,拉取媒体组和定位
- async function openBatchModal() {
- setBatchModal(true)
- // 拉取媒体组
- const res = await getMediaGroupList(1, 50)
- setMediaGroups(((res?.data as any)?.list as any[]) || [])
- // 拉取聊天大模型
- try {
- setChatModelsLoading(true)
- const chatRes = await getChatModels()
- setChatModels(((chatRes?.data as any[]) || []))
- }
- catch (e) {
- // 忽略加载失败,不阻塞弹窗
- setChatModels([])
- }
- finally {
- setChatModelsLoading(false)
- }
- // 获取地理位置
- if (navigator.geolocation) {
- navigator.geolocation.getCurrentPosition(
- (pos) => {
- setBatchLocation([pos.coords.longitude, pos.coords.latitude])
- batchForm.setFieldsValue({ location: [pos.coords.longitude, pos.coords.latitude] })
- },
- () => {
- setBatchLocation([0, 0])
- batchForm.setFieldsValue({ location: [0, 0] })
- },
- )
- }
- else {
- setBatchLocation([0, 0])
- batchForm.setFieldsValue({ location: [0, 0] })
- }
- }
-
- // 生成任务参数
- function getBatchTaskParams() {
- const values = batchForm.getFieldsValue()
- return {
- groupId: selectedGroup?._id,
- num: values.num,
- aiModelTag: values.model,
- prompt: values.prompt,
- title: values.title,
- desc: values.desc,
- location: batchLocation,
- publishTime: new Date().toISOString(),
- mediaGroups: batchMediaGroups,
- coverGroup: batchCoverGroup,
- option: {},
- }
- }
-
- // 预览批量生成草稿
- async function handlePreviewMaterial() {
- const values = await batchForm.validateFields()
- const params: any = getBatchTaskParams()
- // 判断参数是否变化
- if (!lastTaskParams || JSON.stringify(params) !== JSON.stringify(lastTaskParams)) {
- setCurrentTaskId(null)
- setLastTaskParams(params)
- }
- setPreviewLoading(true)
- let taskId = currentTaskId
- try {
- if (!taskId) {
- const res = await apiCreateMaterialTask(params)
- taskId = res?.data?._id || null
- setCurrentTaskId(taskId ?? null)
- }
- if (taskId) {
- const res = await apiPreviewMaterialTask(taskId)
- // @ts-ignore
- setPreviewData(res?.data?.data || null)
- setPreviewModal(true)
- }
- else {
- toast.error(t('batchGenerate.previewFailed'))
- }
- }
- catch (e) {
- toast.error(t('batchGenerate.previewFailed'))
- }
- finally {
- setPreviewLoading(false)
- }
- }
-
- // 批量生成草稿
- async function handleBatchMaterial() {
- const values = await batchForm.validateFields()
- const params: any = getBatchTaskParams()
- setBatchTaskLoading(true)
- try {
- let taskId = currentTaskId
- // 如果参数变化或没有taskId,重新创建
- if (!lastTaskParams || JSON.stringify(params) !== JSON.stringify(lastTaskParams)) {
- const res = await apiCreateMaterialTask(params)
- taskId = res?.data?._id || null
- setCurrentTaskId(taskId ?? null)
- setLastTaskParams(params)
- }
- if (taskId) {
- await apiStartMaterialTask(taskId)
- toast.success(t('batchGenerate.taskStarted'))
- setBatchModal(false)
- batchForm.resetFields()
- fetchMaterialList(selectedGroup._id)
- setCurrentTaskId(null)
- setLastTaskParams(null)
- }
- }
- catch (e) {
- toast.error(t('batchGenerate.generateFailed'))
- }
- finally {
- setBatchTaskLoading(false)
- }
- }
// 处理编辑组
async function handleEditGroup() {
@@ -1192,7 +1049,7 @@ export default function CgMaterialPageCore() {
content: t('sidebar.deleteConfirmDesc', { name: item.name || item.title }),
okText: t('sidebar.delete'),
okType: 'destructive',
- cancelText: t('batchGenerate.cancel'),
+ cancelText: t('actions.cancel' as any),
onOk: async () => {
try {
await apiDeleteMaterialGroup(item._id)
@@ -1234,14 +1091,6 @@ export default function CgMaterialPageCore() {
>
{t('content.createMaterial')}
</Button>
- <Button
- className={styles.actionButton}
- onClick={openBatchModal}
- disabled={!selectedGroup}
- icon={<FileTextOutlined />}
- >
- {t('content.batchGenerate')}
- </Button>
</div>
</div>
@@ -1424,7 +1273,7 @@ export default function CgMaterialPageCore() {
setSelectedPublishItems([])
}}
>
- {t('batchGenerate.cancel')}
+ {t('actions.cancel' as any)}
</Button>
),
(
@@ -2237,109 +2086,6 @@ export default function CgMaterialPageCore() {
</Form.Item>
</Form>
</Modal>
- {/* 批量生成草稿弹窗 */}
- <Modal
- open={batchModal}
- title={t('batchGenerate.title')}
- onOk={handleBatchMaterial}
- onCancel={() => setBatchModal(false)}
- confirmLoading={batchTaskLoading}
- footer={[
- <Button key="preview" onClick={handlePreviewMaterial} loading={previewLoading} type="default">{t('batchGenerate.preview')}</Button>,
- <Button key="submit" type="primary" onClick={handleBatchMaterial} loading={batchTaskLoading}>{t('batchGenerate.startTask')}</Button>,
- <Button key="cancel" onClick={() => setBatchModal(false)}>{t('batchGenerate.cancel')}</Button>,
- ]}
- >
- <Form form={batchForm} layout="vertical">
- <Form.Item label={t('batchGenerate.model')} name="model" rules={[{ required: true, message: t('batchGenerate.modelPlaceholder') }]}>
- <Select
- style={{ width: 200 }}
- loading={chatModelsLoading}
- options={chatModels.map((m: any) => ({ label: m?.description || m?.name, value: m?.name }))}
- placeholder={t('batchGenerate.modelPlaceholder')}
- />
- </Form.Item>
- <Form.Item label={t('batchGenerate.prompt')} name="prompt">
- <Input placeholder={t('batchGenerate.promptPlaceholder')} />
- </Form.Item>
- <Form.Item label={t('fields.title' as any)} name="title">
- <Input placeholder={t('batchGenerate.titlePlaceholder')} />
- </Form.Item>
- <Form.Item label={t('fields.description' as any)} name="desc">
- <TextArea rows={3} placeholder={t('batchGenerate.descPlaceholder')} />
- </Form.Item>
- <Form.Item label={t('batchGenerate.coverGroup')} name="coverGroup" rules={[{ required: true, message: t('batchGenerate.coverGroupPlaceholder') }]}>
- <Select
- options={mediaGroups.map((g: any) => ({ label: g.title, value: g._id }))}
- style={{ width: 200 }}
- onChange={v => setBatchCoverGroup(v)}
- />
- </Form.Item>
- <Form.Item label={t('batchGenerate.mediaGroups')} name="mediaGroups" rules={[{ required: true, message: t('batchGenerate.mediaGroupsPlaceholder') }]}>
- <Select
- mode="multiple"
- options={mediaGroups.map((g: any) => ({ label: g.title, value: g._id }))}
- style={{ width: 300 }}
- onChange={v => setBatchMediaGroups(v)}
- />
- </Form.Item>
- <Form.Item label={t('batchGenerate.num')} name="num" initialValue={4} rules={[{ required: true }]}>
- <InputNumber min={1} max={20} />
- </Form.Item>
- {/* <Form.Item label="地理位置" name="location">
- <Input value={batchLocation.join(',')} disabled />
- </Form.Item> */}
- </Form>
- </Modal>
- {/* 预览弹窗 */}
- <Modal
- open={previewModal}
- title={t('previewModal.title' as any)}
- onCancel={() => setPreviewModal(false)}
- footer={null}
- width={700}
- >
- <Spin spinning={previewLoading}>
- {!previewData
- ? (
- <div style={{ textAlign: 'center', color: '#888' }}>{t('batchGenerate.noPreview')}</div>
- )
- : (
- <Card title={previewData.title} bordered>
- <div style={{ marginBottom: 8 }}>
- <b>{t('detail.descLabel' as any)}</b>
- {previewData.desc}
- </div>
- <div style={{ marginBottom: 8 }}>
- <b>{t('detail.typeLabel' as any)}</b>
- {getMaterialTypeLabel(previewData.type)}
- </div>
- <div style={{ marginBottom: 8 }}>
- <b>{t('detail.coverLabel' as any)}</b>
- <div style={{ marginTop: 4 }}>
- {previewData.coverUrl && (
- <Image
- src={getOssUrl(previewData.coverUrl)}
- alt="cover"
- width={320}
- height={120}
- style={{ width: '100%', maxWidth: 320, height: 120, objectFit: 'cover', borderRadius: 8, display: 'block' }}
- />
- )}
- </div>
- </div>
- <div style={{ marginBottom: 8 }}>
- <b>{t('fields.location' as any)}</b>
- {Array.isArray(previewData.location) ? previewData.location.join(', ') : ''}
- </div>
- <div>
- <b>{t('detail.materialsLabel' as any)}</b>
- {renderMediaContent(previewData.mediaList)}
- </div>
- </Card>
- )}
- </Spin>
- </Modal>
{/* 详情弹窗 */}
<Modal
open={detailModal}
diff --git a/project/web/src/app/[lng]/income/income.module.scss b/project/web/src/app/[lng]/income/income.module.scss
new file mode 100644
index 00000000..6e11eba0
--- /dev/null
+++ b/project/web/src/app/[lng]/income/income.module.scss
@@ -0,0 +1,255 @@
+.container {
+ padding: 24px;
+ min-height: 100vh;
+ background: var(--background);
+}
+
+/* 页面头部样式 - 简约设计 */
+.header {
+ margin-bottom: 32px;
+}
+
+.headerContent {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ background: var(--card);
+ border-radius: 12px;
+ padding: 24px;
+}
+
+.headerLeft {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+}
+
+.headerIcon {
+ width: 48px;
+ height: 48px;
+ background: var(--muted);
+ border-radius: 10px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 24px;
+ color: var(--primary);
+}
+
+.headerText {
+ flex: 1;
+}
+
+.headerTitle {
+ font-size: 24px;
+ font-weight: 600;
+ margin: 0 0 4px 0;
+ color: var(--foreground);
+}
+
+.headerSubtitle {
+ font-size: 14px;
+ margin: 0;
+ color: var(--muted-foreground);
+ font-weight: 400;
+}
+
+.headerRight {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+}
+
+.walletBlock {
+ background: var(--muted);
+ border-radius: 10px;
+ padding: 16px 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ min-width: 200px;
+}
+
+.walletBlockTop {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.walletButton {
+ width: 100%;
+ justify-content: center;
+}
+
+.balanceIcon {
+ width: 40px;
+ height: 40px;
+ background: var(--primary);
+ border-radius: 8px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 18px;
+ color: var(--primary-foreground);
+}
+
+.balanceInfo {
+ flex: 1;
+}
+
+.balanceLabel {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ margin-bottom: 4px;
+ font-weight: 500;
+}
+
+.balanceAmount {
+ font-size: 20px;
+ font-weight: 600;
+ color: var(--foreground);
+}
+
+/* 主要内容样式 */
+.content {
+ background: var(--card);
+ border-radius: 12px;
+ padding: 24px;
+}
+
+.content :global([role="tablist"]) {
+ margin-bottom: 0;
+}
+
+/* 提现弹窗样式 */
+.withdrawModalContent {
+ padding: 20px 0;
+}
+
+.withdrawInfo {
+ background: var(--muted);
+ border-radius: 10px;
+ padding: 20px;
+ margin-bottom: 20px;
+}
+
+.withdrawItem {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 12px;
+ padding: 8px 0;
+}
+
+.withdrawItem:last-child {
+ margin-bottom: 0;
+ border-bottom: none;
+}
+
+.withdrawLabel {
+ font-weight: 500;
+ color: var(--foreground);
+ font-size: 14px;
+}
+
+.withdrawValue {
+ color: var(--muted-foreground);
+ font-size: 14px;
+ word-break: break-all;
+ max-width: 200px;
+ text-align: right;
+}
+
+.withdrawAmount {
+ color: var(--primary);
+ font-weight: 600;
+ font-size: 16px;
+}
+
+.withdrawWarning {
+ background: var(--warning);
+ border-radius: 8px;
+ padding: 16px;
+ color: var(--warning-foreground);
+ margin-top: 16px;
+}
+
+.withdrawWarning p {
+ margin: 0 0 8px 0;
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+.withdrawWarning p:last-child {
+ margin-bottom: 0;
+}
+
+/* 移动端适配 */
+@media (max-width: 768px) {
+ .container {
+ padding: 16px;
+ }
+
+ .headerContent {
+ flex-direction: column;
+ gap: 20px;
+ padding: 20px;
+ align-items: stretch;
+ }
+
+ .headerLeft {
+ flex-direction: column;
+ gap: 12px;
+ text-align: center;
+ }
+
+ .headerIcon {
+ width: 40px;
+ height: 40px;
+ font-size: 20px;
+ }
+
+ .headerTitle {
+ font-size: 20px;
+ }
+
+ .headerSubtitle {
+ font-size: 13px;
+ }
+
+ .headerRight {
+ flex-direction: column;
+ width: 100%;
+ gap: 12px;
+ }
+
+ .walletBlock {
+ min-width: auto;
+ width: 100%;
+ }
+
+ .walletBlockTop {
+ flex-direction: column;
+ text-align: center;
+ gap: 8px;
+ }
+
+ .balanceAmount {
+ font-size: 18px;
+ }
+
+ .content {
+ padding: 16px;
+ }
+
+ .withdrawItem {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 4px;
+ }
+
+ .withdrawValue {
+ max-width: none;
+ text-align: left;
+ }
+}
diff --git a/project/web/src/app/[lng]/income/page.tsx b/project/web/src/app/[lng]/income/page.tsx
new file mode 100644
index 00000000..b75ae42c
--- /dev/null
+++ b/project/web/src/app/[lng]/income/page.tsx
@@ -0,0 +1,711 @@
+/**
+ * IncomePage - 收入页面
+ * 显示收入记录和提现记录
+ */
+
+'use client'
+
+import type { IncomeRecord } from '@/api/types/income'
+import type { WithdrawRecord } from '@/api/types/withdraw'
+import { CheckCircleOutlined, ClockCircleOutlined, CloseCircleOutlined, DollarOutlined, HistoryOutlined, WalletOutlined } from '@ant-design/icons'
+import { useParams, useRouter } from 'next/navigation'
+import { useEffect, useState } from 'react'
+import { WithdrawRecordStatus, WithdrawStatus } from '@/api/types/withdraw'
+import { getIncomeListApi, getIncomeDetailApi, createWithdrawApi, getWithdrawListApi } from '@/api/payment'
+import { useTransClient } from '@/app/i18n/client'
+import WalletAccountSelect from '@/components/WalletAccountSelect'
+import WalletModal from '@/components/WalletModal'
+import { useUserStore } from '@/store/user'
+import { toast } from '@/lib/toast'
+import { Button } from '@/components/ui/button'
+import { Card } from '@/components/ui/card'
+import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
+import { Badge } from '@/components/ui/badge'
+import { Spin } from '@/components/ui/spin'
+import { Empty } from '@/components/ui/empty'
+import { Pagination } from '@/components/ui/pagination'
+import { Modal } from '@/components/ui/modal'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
+import styles from './income.module.scss'
+
+export default function IncomePage() {
+ const router = useRouter()
+ const params = useParams()
+ const { userInfo, token, lang } = useUserStore()
+ const { t } = useTransClient('income')
+ const lng = params.lng as string
+
+ // 收入记录相关状态
+ const [incomeRecords, setIncomeRecords] = useState<IncomeRecord[]>([])
+ const [incomeLoading, setIncomeLoading] = useState(false)
+ const [incomePagination, setIncomePagination] = useState({
+ current: 1,
+ pageSize: 10,
+ total: 0,
+ })
+ const [incomeFilters, setIncomeFilters] = useState({
+ type: undefined as 'reward_back' | 'task' | 'task_back' | 'task_withdraw' | undefined,
+ status: undefined as 'pending' | 'withdrawn' | undefined,
+ })
+
+ // 提现记录相关状态
+ const [withdrawRecords, setWithdrawRecords] = useState<WithdrawRecord[]>([])
+ const [withdrawLoading, setWithdrawLoading] = useState(false)
+ const [withdrawPagination, setWithdrawPagination] = useState({
+ current: 1,
+ pageSize: 10,
+ total: 0,
+ })
+
+ // 提现申请状态
+ const [withdrawModalVisible, setWithdrawModalVisible] = useState(false)
+ const [selectedIncomeRecord, setSelectedIncomeRecord] = useState<IncomeRecord | null>(null)
+ const [withdrawSubmitting, setWithdrawSubmitting] = useState(false)
+ const [selectedWalletAccountId, setSelectedWalletAccountId] = useState<string>('')
+
+ // 钱包弹窗状态
+ const [walletModalOpen, setWalletModalOpen] = useState(false)
+
+ // 收入详情状态
+ const [incomeDetailModalVisible, setIncomeDetailModalVisible] = useState(false)
+ const [incomeDetail, setIncomeDetail] = useState<any>(null)
+ const [incomeDetailLoading, setIncomeDetailLoading] = useState(false)
+
+ // 获取收入记录
+ const fetchIncomeRecords = async (page: number = 1, pageSize: number = 10) => {
+ setIncomeLoading(true)
+ try {
+ const response = await getIncomeListApi({
+ page,
+ pageSize,
+ ...(incomeFilters.type && { type: incomeFilters.type }),
+ ...(incomeFilters.status && { status: incomeFilters.status }),
+ })
+ if (response?.data) {
+ setIncomeRecords(response.data.list || [])
+ setIncomePagination({
+ current: page,
+ pageSize,
+ total: response.data.count || 0,
+ })
+ }
+ else {
+ toast.error(t('messages.getIncomeRecordsFailed'))
+ }
+ }
+ catch (error) {
+ toast.error(t('messages.getIncomeRecordsFailed'))
+ }
+ finally {
+ setIncomeLoading(false)
+ }
+ }
+
+ // 获取收入详情
+ const fetchIncomeDetail = async (id: string) => {
+ setIncomeDetailLoading(true)
+ try {
+ const response = await getIncomeDetailApi(id)
+ if (response?.data || response) {
+ setIncomeDetail(response?.data || response)
+ setIncomeDetailModalVisible(true)
+ }
+ else {
+ toast.error(t('messages.getIncomeDetailFailed'))
+ }
+ }
+ catch (error) {
+ toast.error(t('messages.getIncomeDetailFailed'))
+ }
+ finally {
+ setIncomeDetailLoading(false)
+ }
+ }
+
+ // 获取提现记录
+ const fetchWithdrawRecords = async (page: number = 1, pageSize: number = 10) => {
+ setWithdrawLoading(true)
+ try {
+ const response = await getWithdrawListApi({ page, pageSize })
+ if (response?.data) {
+ // 转换新API数据格式为旧格式以兼容现有代码
+ const convertedRecords = (response.data.list || []).map((item: any) => ({
+ _id: item.id,
+ id: item.id,
+ userId: item.userId,
+ amount: item.amount,
+ type: item.type === 'task' ? 'task' : 'reward',
+ status: convertWithdrawStatus(item.status),
+ createdAt: new Date(item.createdAt),
+ updatedAt: new Date(item.updatedAt),
+ desc: item.adminNote || item.metadata?.desc,
+ flowId: item.flowId,
+ screenshotUrls: item.screenshotUrls,
+ }))
+ setWithdrawRecords(convertedRecords as any)
+ setWithdrawPagination({
+ current: page,
+ pageSize,
+ total: response.data.count || 0,
+ })
+ }
+ else {
+ toast.error(t('messages.getWithdrawRecordsFailed'))
+ }
+ }
+ catch (error) {
+ toast.error(t('messages.getWithdrawRecordsFailed'))
+ }
+ finally {
+ setWithdrawLoading(false)
+ }
+ }
+
+ // 转换新API状态为旧状态枚举
+ const convertWithdrawStatus = (status: string): WithdrawRecordStatus => {
+ const statusMap: Record<string, WithdrawRecordStatus> = {
+ pending: WithdrawRecordStatus.WAIT,
+ approved: WithdrawRecordStatus.WAIT,
+ paid: WithdrawRecordStatus.SUCCESS,
+ failed: WithdrawRecordStatus.FAIL,
+ rejected: WithdrawRecordStatus.FAIL,
+ }
+ return statusMap[status] || WithdrawRecordStatus.WAIT
+ }
+
+ // 提交提现申请
+ const handleWithdraw = async (incomeRecord: IncomeRecord) => {
+ setSelectedIncomeRecord(incomeRecord)
+ setWithdrawModalVisible(true)
+ }
+
+ // 确认提现申请
+ const handleConfirmWithdraw = async () => {
+ if (!selectedIncomeRecord || !selectedWalletAccountId) {
+ toast.error(t('messages.pleaseSelectWallet'))
+ return
+ }
+
+ setWithdrawSubmitting(true)
+ try {
+ const response = await createWithdrawApi({
+ amount: selectedIncomeRecord.amount,
+ currency: (selectedIncomeRecord.currency as 'CNY' | 'UNK' | 'USD') || 'CNY',
+ incomeRecordIds: [selectedIncomeRecord._id || selectedIncomeRecord.id],
+ type: selectedIncomeRecord.type === 'task' ? 'task' : 'reward',
+ walletAccountId: selectedWalletAccountId,
+ })
+ if (response) {
+ toast.success(t('messages.withdrawSubmitted'))
+ setWithdrawModalVisible(false)
+ setSelectedIncomeRecord(null)
+ setSelectedWalletAccountId('')
+ // 刷新收入记录和提现记录
+ fetchIncomeRecords(incomePagination.current, incomePagination.pageSize)
+ fetchWithdrawRecords(withdrawPagination.current, withdrawPagination.pageSize)
+ }
+ else {
+ toast.error(t('messages.withdrawFailed'))
+ }
+ }
+ catch (error) {
+ toast.error(t('messages.withdrawFailed'))
+ }
+ finally {
+ setWithdrawSubmitting(false)
+ }
+ }
+
+ // 获取收入类型显示文本
+ const getIncomeTypeText = (type: string) => {
+ const typeMap: { [key: string]: { color: string, text: string } } = {
+ task: { color: 'green', text: t('incomeTypes.task') },
+ task_back: { color: 'orange', text: t('incomeTypes.task_back') },
+ reward_back: { color: 'blue', text: t('incomeTypes.reward_back') },
+ task_withdraw: { color: 'purple', text: t('incomeTypes.task_withdraw' as any) },
+ }
+ const config = typeMap[type] || { color: 'default', text: type }
+ return getBadgeClassName(config.color)
+ }
+
+ // 将 antd Tag 的 color 转换为 Badge 的样式类
+ const getBadgeClassName = (color?: string) => {
+ const colorMap: Record<string, string> = {
+ orange: 'bg-orange-100 text-orange-800',
+ green: 'bg-green-100 text-green-800',
+ blue: 'bg-blue-100 text-blue-800',
+ purple: 'bg-purple-100 text-purple-800',
+ red: 'bg-red-100 text-red-800',
+ default: 'bg-gray-100 text-gray-800',
+ }
+ return colorMap[color || 'default'] || colorMap.default
+ }
+
+ // 获取提现状态显示
+ const getWithdrawStatusTag = (status: WithdrawRecordStatus) => {
+ const statusMap = {
+ [WithdrawRecordStatus.WAIT]: { color: 'orange', text: t('withdrawStatus.wait'), icon: <ClockCircleOutlined /> },
+ [WithdrawRecordStatus.SUCCESS]: { color: 'green', text: t('withdrawStatus.success'), icon: <CheckCircleOutlined /> },
+ [WithdrawRecordStatus.FAIL]: { color: 'red', text: t('withdrawStatus.fail'), icon: <CloseCircleOutlined /> },
+ [WithdrawRecordStatus.TASK_WITHDRAW]: { color: 'blue', text: t('withdrawStatus.task_withdraw' as any), icon: <DollarOutlined /> },
+ }
+ const config = statusMap[status] || { color: 'default', text: t('withdrawStatus.unknown') || 'Unknown', icon: null }
+ return {
+ className: getBadgeClassName(config.color),
+ text: config.text,
+ icon: config.icon,
+ }
+ }
+
+ // 检查是否可以提现
+ const canWithdraw = (record: IncomeRecord) => {
+ // 仅 status = pending 且 type = task 的收入记录可提现
+ return record.type === 'task' && (record.status === 'pending' || record.status === 0 || record.status === undefined)
+ }
+
+ useEffect(() => {
+ if (!token) {
+ toast.error(t('messages.pleaseLoginFirst'))
+ router.push('/login')
+ return
+ }
+
+ // 初始加载数据
+ fetchIncomeRecords(1, 10)
+ fetchWithdrawRecords(1, 10)
+ }, [token, router])
+
+ // 当筛选条件改变时重新获取数据
+ useEffect(() => {
+ if (token) {
+ fetchIncomeRecords(1, incomePagination.pageSize)
+ }
+ }, [incomeFilters])
+
+ return (
+ <div className={styles.container}>
+ {/* 页面头部 */}
+ <div className={styles.header}>
+ <div className={styles.headerContent}>
+ <div className={styles.headerLeft}>
+ <div className={styles.headerIcon}>
+ <DollarOutlined />
+ </div>
+ <div className={styles.headerText}>
+ <h1 className={styles.headerTitle}>{t('title')}</h1>
+ <p className={styles.headerSubtitle}>{t('subtitle')}</p>
+ </div>
+ </div>
+ <div className={styles.headerRight}>
+ <div className={styles.walletBlock}>
+ <div className={styles.walletBlockTop}>
+
+ <div className={styles.balanceInfo}>
+ <div className={styles.balanceAmount}>
+ CNY
+ {' '}
+ {((userInfo?.income as number) / 100 || 0).toFixed(2)}
+ </div>
+ </div>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className={styles.walletButton}
+ onClick={() => setWalletModalOpen(true)}
+ >
+ <WalletOutlined />
+ &nbsp;
+ {t('myWallet')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* 主要内容 */}
+ <div className={styles.content}>
+ <Tabs defaultValue="income" className="w-full">
+ <TabsList className="grid w-full grid-cols-2">
+ <TabsTrigger value="income">
+ <DollarOutlined />
+ &nbsp;
+ {t('incomeRecords')}
+ </TabsTrigger>
+ <TabsTrigger value="withdraw">
+ <HistoryOutlined />
+ &nbsp;
+ {t('withdrawRecords')}
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="income" className="mt-4">
+ {/* 筛选器 */}
+ <div className="flex gap-4 mb-6">
+ <div className="flex-1">
+ <Label className="mb-2 block">{t('type')}</Label>
+ <select
+ value={incomeFilters.type || 'all'}
+ onChange={(e) => {
+ setIncomeFilters(prev => ({
+ ...prev,
+ type: e.target.value === 'all' ? undefined : e.target.value as any,
+ }))
+ }}
+ className="h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
+ >
+ <option value="all">{t('all') || 'All'}</option>
+ <option value="task">{t('incomeTypes.task')}</option>
+ <option value="task_back">{t('incomeTypes.task_back')}</option>
+ <option value="reward_back">{t('incomeTypes.reward_back')}</option>
+ <option value="task_withdraw">{t('incomeTypes.task_withdraw' as any)}</option>
+ </select>
+ </div>
+ <div className="flex-1">
+ <Label className="mb-2 block">{t('statusLabel')}</Label>
+ <select
+ value={incomeFilters.status || 'all'}
+ onChange={(e) => {
+ setIncomeFilters(prev => ({
+ ...prev,
+ status: e.target.value === 'all' ? undefined : e.target.value as any,
+ }))
+ }}
+ className="h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
+ >
+ <option value="all">{t('all') || 'All'}</option>
+ <option value="pending">{t('status.pending')}</option>
+ <option value="withdrawn">{t('status.withdrawn')}</option>
+ </select>
+ </div>
+ </div>
+
+ <Spin spinning={incomeLoading}>
+ {incomeRecords.length > 0 ? (
+ <>
+ <div className="overflow-x-auto">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[200px]">{t('incomeId')}</TableHead>
+ <TableHead>{t('amount')}</TableHead>
+ <TableHead>{t('type')}</TableHead>
+ <TableHead>{t('statusLabel')}</TableHead>
+ <TableHead>{t('description')}</TableHead>
+ <TableHead>{t('createTime')}</TableHead>
+ <TableHead>{t('actions')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {incomeRecords.map((record) => (
+ <TableRow key={record._id || record.id}>
+ <TableCell className="font-mono text-xs">
+ <button
+ type="button"
+ onClick={() => fetchIncomeDetail(record._id || record.id)}
+ className="text-primary hover:underline"
+ >
+ {(record._id || record.id).slice(0, 8)}...
+ </button>
+ </TableCell>
+ <TableCell>
+ <span className="text-green-600 font-bold">
+ {record.currency || 'CNY'}
+ {' '}
+ {(record.amount / 100).toFixed(2)}
+ </span>
+ </TableCell>
+ <TableCell>
+ <Badge className={getIncomeTypeText(record.type)}>
+ {t(`incomeTypes.${record.type}` as any) || record.type}
+ </Badge>
+ </TableCell>
+ <TableCell>
+ {record.status === 'pending' || record.status === 0 || record.status === undefined
+ ? (
+ <Badge className={getBadgeClassName('orange')}>
+ {t('status.pending')}
+ </Badge>
+ )
+ : (
+ <Badge className={getBadgeClassName('green')}>
+ {t('status.withdrawn')}
+ </Badge>
+ )}
+ </TableCell>
+ <TableCell className="max-w-[200px] truncate">
+ {record.desc || '-'}
+ </TableCell>
+ <TableCell className="text-sm text-muted-foreground">
+ {new Date(record.createdAt).toLocaleString()}
+ </TableCell>
+ <TableCell>
+ {canWithdraw(record) && (
+ <Button
+ size="sm"
+ onClick={() => handleWithdraw(record)}
+ >
+ {t('applyWithdraw')}
+ </Button>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+
+ <div className="mt-4">
+ <Pagination
+ current={incomePagination.current}
+ pageSize={incomePagination.pageSize}
+ total={incomePagination.total}
+ onChange={(page, pageSize) => {
+ fetchIncomeRecords(page, pageSize || 10)
+ }}
+ onShowSizeChange={(current, size) => {
+ fetchIncomeRecords(current, size)
+ }}
+ showSizeChanger
+ showQuickJumper
+ showTotal={(total, range) => t('messages.totalRecords', { total })}
+ pageSizeOptions={['10', '20', '50']}
+ />
+ </div>
+ </>
+ ) : (
+ <Empty description={incomeLoading ? t('messages.loading') : t('messages.noIncomeRecords')} />
+ )}
+ </Spin>
+ </TabsContent>
+
+ <TabsContent value="withdraw" className="mt-4">
+ <Spin spinning={withdrawLoading}>
+ {withdrawRecords.length > 0 ? (
+ <>
+ <div className="overflow-x-auto">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[200px]">{t('withdrawId')}</TableHead>
+ <TableHead>{t('amount')}</TableHead>
+ <TableHead>{t('statusLabel')}</TableHead>
+ <TableHead>{t('description')}</TableHead>
+ <TableHead>{t('createTime')}</TableHead>
+ <TableHead>{t('updateTime')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {withdrawRecords.map((record) => {
+ const statusTag = getWithdrawStatusTag(record.status)
+ return (
+ <TableRow key={record._id || record.id}>
+ <TableCell className="font-mono text-xs">
+ {(record._id || record.id).slice(0, 8)}...
+ </TableCell>
+ <TableCell>
+ <span className="text-blue-600 font-bold">
+ {(record as any).currency || 'CNY'}
+ {' '}
+ {(record.amount / 100).toFixed(2)}
+ </span>
+ </TableCell>
+ <TableCell>
+ <Badge className={statusTag.className}>
+ {statusTag.icon}
+ &nbsp;
+ {statusTag.text}
+ </Badge>
+ </TableCell>
+ <TableCell className="max-w-[200px] truncate">
+ {record.desc || '-'}
+ </TableCell>
+ <TableCell className="text-sm text-muted-foreground">
+ {new Date(record.createdAt).toLocaleString()}
+ </TableCell>
+ <TableCell className="text-sm text-muted-foreground">
+ {new Date(record.updatedAt).toLocaleString()}
+ </TableCell>
+ </TableRow>
+ )
+ })}
+ </TableBody>
+ </Table>
+ </div>
+
+ <div className="mt-4">
+ <Pagination
+ current={withdrawPagination.current}
+ pageSize={withdrawPagination.pageSize}
+ total={withdrawPagination.total}
+ onChange={(page, pageSize) => {
+ fetchWithdrawRecords(page, pageSize || 10)
+ }}
+ onShowSizeChange={(current, size) => {
+ fetchWithdrawRecords(current, size)
+ }}
+ showSizeChanger
+ showQuickJumper
+ showTotal={(total, range) => t('messages.totalRecords', { total })}
+ pageSizeOptions={['10', '20', '50']}
+ />
+ </div>
+ </>
+ ) : (
+ <Empty description={withdrawLoading ? t('messages.loading') : t('messages.noWithdrawRecords')} />
+ )}
+ </Spin>
+ </TabsContent>
+ </Tabs>
+ </div>
+
+ {/* 提现确认弹窗 */}
+ <Modal
+ title={t('confirmWithdraw')}
+ open={withdrawModalVisible}
+ onCancel={() => {
+ setWithdrawModalVisible(false)
+ setSelectedIncomeRecord(null)
+ setSelectedWalletAccountId('')
+ }}
+ onOk={handleConfirmWithdraw}
+ okText={t('confirm')}
+ cancelText={t('cancel')}
+ confirmLoading={withdrawSubmitting}
+ width={500}
+ >
+ {selectedIncomeRecord && (
+ <div className={styles.withdrawModalContent}>
+ <div className={styles.withdrawInfo}>
+ <div className={styles.withdrawItem}>
+ <span className={styles.withdrawLabel}>
+ {t('incomeId')}
+ :
+ </span>
+ <span className={styles.withdrawValue}>{selectedIncomeRecord._id || selectedIncomeRecord.id}</span>
+ </div>
+ <div className={styles.withdrawItem}>
+ <span className={styles.withdrawLabel}>
+ {t('withdrawAmount')}
+ :
+ </span>
+ <span className={styles.withdrawAmount}>
+ {selectedIncomeRecord.currency || 'CNY'}
+ {' '}
+ {(selectedIncomeRecord.amount / 100).toFixed(2)}
+ </span>
+ </div>
+ <div className={styles.withdrawItem}>
+ <span className={styles.withdrawLabel}>
+ {t('incomeType')}
+ :
+ </span>
+ <Badge className={getIncomeTypeText(selectedIncomeRecord.type)}>
+ {t(`incomeTypes.${selectedIncomeRecord.type}` as any) || selectedIncomeRecord.type}
+ </Badge>
+ </div>
+ {selectedIncomeRecord.desc && (
+ <div className={styles.withdrawItem}>
+ <span className={styles.withdrawLabel}>
+ {t('description')}
+ :
+ </span>
+ <span className={styles.withdrawValue}>{selectedIncomeRecord.desc}</span>
+ </div>
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t('myWallet')}</Label>
+ <WalletAccountSelect
+ value={selectedWalletAccountId}
+ onChange={(val) => setSelectedWalletAccountId(val || '')}
+ />
+ </div>
+
+ <div className={styles.withdrawWarning}>
+ <p>{t('withdrawWarning')}</p>
+ <p>{t('withdrawWarning2')}</p>
+ </div>
+ </div>
+ )}
+ </Modal>
+
+ {/* 收入详情弹窗 */}
+ <Modal
+ title={t('incomeDetail')}
+ open={incomeDetailModalVisible}
+ onCancel={() => {
+ setIncomeDetailModalVisible(false)
+ setIncomeDetail(null)
+ }}
+ footer={null}
+ width={600}
+ >
+ <Spin spinning={incomeDetailLoading}>
+ {incomeDetail ? (
+ <div className="space-y-4">
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <Label className="text-muted-foreground">{t('incomeId')}</Label>
+ <p className="font-mono text-sm">{incomeDetail.id || incomeDetail._id}</p>
+ </div>
+ <div>
+ <Label className="text-muted-foreground">{t('amount')}</Label>
+ <p className="text-green-600 font-bold">
+ {incomeDetail.currency || 'CNY'}
+ {' '}
+ {(incomeDetail.amount / 100).toFixed(2)}
+ </p>
+ </div>
+ <div>
+ <Label className="text-muted-foreground">{t('type')}</Label>
+ <Badge className={getIncomeTypeText(incomeDetail.type)}>
+ {t(`incomeTypes.${incomeDetail.type}` as any) || incomeDetail.type}
+ </Badge>
+ </div>
+ <div>
+ <Label className="text-muted-foreground">{t('statusLabel')}</Label>
+ {incomeDetail.status === 'pending' || incomeDetail.status === 0 || incomeDetail.status === undefined
+ ? (
+ <Badge className={getBadgeClassName('orange')}>
+ {t('status.pending')}
+ </Badge>
+ )
+ : (
+ <Badge className={getBadgeClassName('green')}>
+ {t('status.withdrawn')}
+ </Badge>
+ )}
+ </div>
+ <div className="col-span-2">
+ <Label className="text-muted-foreground">{t('description')}</Label>
+ <p>{incomeDetail.desc || '-'}</p>
+ </div>
+ <div>
+ <Label className="text-muted-foreground">{t('createTime')}</Label>
+ <p className="text-sm">{new Date(incomeDetail.createdAt).toLocaleString()}</p>
+ </div>
+ <div>
+ <Label className="text-muted-foreground">{t('updateTime')}</Label>
+ <p className="text-sm">{new Date(incomeDetail.updatedAt).toLocaleString()}</p>
+ </div>
+ </div>
+ </div>
+ ) : !incomeDetailLoading && (
+ <Empty description={t('messages.noIncomeDetail')} />
+ )}
+ </Spin>
+ </Modal>
+
+ {/* 钱包管理弹窗 */}
+ <WalletModal
+ open={walletModalOpen}
+ onClose={() => setWalletModalOpen(false)}
+ />
+ </div>
+ )
+}
+
diff --git a/project/web/src/app/[lng]/page.tsx b/project/web/src/app/[lng]/page.tsx
index 300a0fe3..9ff24ea4 100644
--- a/project/web/src/app/[lng]/page.tsx
+++ b/project/web/src/app/[lng]/page.tsx
@@ -5,6 +5,7 @@
'use client'
import { useState, useCallback, useEffect, useRef } from 'react'
+import { useSearchParams, useRouter, useParams } from 'next/navigation'
import { ArrowUp } from 'lucide-react'
import { HomeChat } from '@/components/Home/HomeChat'
import { TaskPreview } from '@/components/Home/TaskPreview'
@@ -66,6 +67,31 @@ export default function Home() {
toast.success('Prompt applied!')
}, [])
+ // 从 URL query 读取 agentExternalPrompt 和 agentTaskId(由任务页通过 query 传参)
+ const searchParams = useSearchParams()
+ const router = useRouter()
+ const [agentTaskId, setAgentTaskId] = useState<string>('')
+ const params = useParams()
+ useEffect(() => {
+ try {
+ const prompt = searchParams.get('agentExternalPrompt')
+ const id = searchParams.get('agentTaskId')
+ if (prompt) {
+ setAppliedPrompt(prompt)
+ }
+ if (id) {
+ setAgentTaskId(id)
+ }
+ // 清理 URL 上的 query,避免重复
+ if (prompt || id) {
+ router.replace(`/${params.lng}`)
+ }
+ }
+ catch (e) {
+ // ignore
+ }
+ }, [searchParams, router, params.lng])
+
// 清除外部提示词
const handleClearExternalPrompt = useCallback(() => {
setAppliedPrompt('')
@@ -75,9 +101,10 @@ export default function Home() {
<div className="bg-background">
{/* 首屏 Chat 区域 */}
<section className="min-h-[60vh] flex items-center justify-center px-4 pt-16 pb-8 md:pt-24 md:pb-12">
- <HomeChat
+ <HomeChat
externalPrompt={appliedPrompt}
onClearExternalPrompt={handleClearExternalPrompt}
+ agentTaskId={agentTaskId}
/>
</section>
diff --git a/project/web/src/app/[lng]/tasks/taskPageCore.tsx b/project/web/src/app/[lng]/tasks/taskPageCore.tsx
index b7654827..55aeb5b9 100644
--- a/project/web/src/app/[lng]/tasks/taskPageCore.tsx
+++ b/project/web/src/app/[lng]/tasks/taskPageCore.tsx
@@ -11,10 +11,21 @@ import type {
} from '@/api/task'
import type { SocialAccount } from '@/api/types/account.type'
import type { PlatType } from '@/app/config/platConfig'
-import { CheckOutlined, ClockCircleOutlined, EyeOutlined, PlayCircleOutlined, UploadOutlined } from '@ant-design/icons'
-import { Button, Card, Col, Empty, Input, List, Pagination, Radio, Row, Spin, Steps, Tabs, Tag, Tooltip } from 'antd'
+import { ClockCircleOutlined, EyeOutlined, PlayCircleOutlined } from '@ant-design/icons'
import { toast } from '@/lib/toast'
import { Modal } from '@/components/ui/modal'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
+import { Badge } from '@/components/ui/badge'
+import { Spin } from '@/components/ui/spin'
+import { Empty } from '@/components/ui/empty'
+import { Card } from '@/components/ui/card'
+import { Steps } from '@/components/ui/steps'
+import { List } from '@/components/ui/list'
+import { Pagination } from '@/components/ui/pagination'
+import { Radio } from '@/components/ui/radio'
+import { Row, Col } from '@/components/ui/grid'
import Image from 'next/image'
import { useParams, useRouter } from 'next/navigation'
import React, { useEffect, useState } from 'react'
@@ -35,16 +46,16 @@ import { getAppDownloadConfig, getTasksRequiringApp } from '@/app/config/appDown
import { AccountPlatInfoMap } from '@/app/config/platConfig'
import { useTransClient } from '@/app/i18n/client'
import DownloadAppModal from '@/components/common/DownloadAppModal'
-import DraftSelectionModal from '@/components/PublishDialog/compoents/DraftSelectionModal'
import { useUserStore } from '@/store/user'
import { generateUUID } from '@/utils'
import { getOssUrl } from '@/utils/oss'
import styles from './taskPageCore.module.scss'
-
-const { TabPane } = Tabs
+import PublishDialog from '@/components/PublishDialog'
+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'
export default function TaskPageCore() {
const { t } = useTransClient('task' as any)
+ // use only task namespace translator `t` to avoid cross-namespace missing translations
const token = useUserStore(state => state.token)
const router = useRouter()
const params = useParams()
@@ -143,15 +154,19 @@ export default function TaskPageCore() {
total: 0,
})
- // 草稿选择状态
- const [draftSource, setDraftSource] = useState<'task' | 'own'>('task') // 'task': Task draft, 'own': My draft
- const [selectedMaterial, setSelectedMaterial] = useState<any>(null) // Selected task material
- const [draftModalOpen, setDraftModalOpen] = useState(false) // My draft selection modal
+ // 推荐草稿选择状态
+ const [selectedMaterial, setSelectedMaterial] = useState<any>(null) // 选中的推荐草稿
const [requiredAccountTypes, setRequiredAccountTypes] = useState<string[]>([])
// Accepted task detail material list state
const [acceptedTaskMaterialList, setAcceptedTaskMaterialList] = useState<any[]>([])
const [acceptedTaskMaterialLoading, setAcceptedTaskMaterialLoading] = useState(false)
+ // Publish dialog state
+ const [publishDialogOpen, setPublishDialogOpen] = useState(false)
+ const [publishDefaultAccountId, setPublishDefaultAccountId] = useState<string | undefined>(undefined)
+ const [pendingUserTaskIdForPublish, setPendingUserTaskIdForPublish] = useState<string | undefined>(undefined)
+ const [pendingTaskMaterialIdForPublish, setPendingTaskMaterialIdForPublish] = useState<string | undefined>(undefined)
+ const [pendingTaskForPublish, setPendingTaskForPublish] = useState<any | null>(null)
// Fetch pending tasks list
const fetchPendingTasks = async (page: number = 1, pageSize: number = 15) => {
@@ -233,8 +248,8 @@ export default function TaskPageCore() {
// 接受任务
const handleAcceptTask = async (task: any) => {
- // 暂时简化,直接接受任务
- await doAcceptTask(task)
+ // 打开任务详情让用户选择素材并完成接取/发布流程
+ await handleViewTaskDetail(task.id)
// TODO: 添加平台限制检查
// if (!task.accountTypes || task.accountTypes.length === 0) {
@@ -279,9 +294,6 @@ export default function TaskPageCore() {
// 切换到已接受任务标签
setActiveTab('accepted')
}
- else {
- toast.error(t('messages.acceptTaskFailed'))
- }
}
catch (error) {
toast.error(t('messages.acceptTaskFailed'))
@@ -352,15 +364,15 @@ export default function TaskPageCore() {
const days = Math.floor(diff / (1000 * 60 * 60 * 24))
if (minutes < 60)
- return `${minutes}分钟后`
+ return t('time.minutesLater' as any, { minutes })
if (hours < 24)
- return `${hours}小时后`
+ return t('time.hoursLater' as any, { hours })
if (days < 7)
- return `${days}天后`
+ return t('time.daysLater' as any, { days })
}
// 显示具体日期时间
- return date.toLocaleString('zh-CN', {
+ return date.toLocaleString(lng === 'zh-CN' ? 'zh-CN' : 'en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
@@ -381,6 +393,18 @@ export default function TaskPageCore() {
return statusMap[status] || { color: 'default', text: status }
}
+ // 将 antd Tag 的 color 转换为 Badge 的样式类
+ const getBadgeClassName = (color?: string) => {
+ const colorMap: Record<string, string> = {
+ orange: 'bg-orange-100 text-orange-800 border-orange-200',
+ green: 'bg-green-100 text-green-800 border-green-200',
+ blue: 'bg-blue-100 text-blue-800 border-blue-200',
+ red: 'bg-red-100 text-red-800 border-red-200',
+ default: 'bg-gray-100 text-gray-800 border-gray-200',
+ }
+ return colorMap[color || 'default'] || colorMap.default
+ }
+
// 根据accountId获取账号信息
const getAccountById = (accountId: string): SocialAccount | null => {
return accountList.find(account => account.id === accountId) || null
@@ -614,8 +638,7 @@ export default function TaskPageCore() {
setTaskDetail(response.data)
setTaskDetailModalVisible(true)
- // 重置草稿选择状态
- setDraftSource('task')
+ // 重置推荐草稿选择状态
setSelectedMaterial(null)
// 如果有 materialGroupId,获取素材列表
@@ -697,11 +720,8 @@ export default function TaskPageCore() {
if (!task)
return
- // Validate if material is selected
- if (!selectedMaterial) {
- toast.error('Please select a draft material')
- return
- }
+ // 使用选中的推荐草稿(如果有); 不要使用回退素材,直接发布模式下不自动填充
+ // const material will be read again after accept to ensure current selectedMaterial is used
// Close detail modal
setTaskDetailModalVisible(false)
@@ -711,119 +731,100 @@ export default function TaskPageCore() {
setTaskProgress({
currentStep: 0,
steps: [
- { title: 'Accepting task...', status: 'processing' },
- { title: 'Publishing task...', status: 'wait' },
- { title: 'Submitting task...', status: 'wait' },
- { title: 'Task completed', status: 'wait' },
+ { title: t('acceptingTask'), status: 'processing' },
+ { title: t('publishingTask'), status: 'wait' },
+ { title: t('submittingTask'), status: 'wait' },
+ { title: t('taskCompleted'), status: 'wait' },
],
})
try {
- // 第一步:接受任务
+ // 第一步:接受任务(只接受,不自动发布)
const response: any = await acceptTask(task.id, task.opportunityId, account?.id)
if (response && response.code === 0 && response.data.id) {
- // 更新进度:第一步完成,开始第二步
- setTaskProgress(prev => ({
- ...prev,
- currentStep: 1,
- steps: [
- { title: t('acceptingTask' as any), status: 'finish' },
- { title: t('publishingTask' as any), status: 'processing' },
- { title: t('submittingTask' as any), status: 'wait' },
- { title: t('taskCompleted' as any), status: 'wait' },
- ],
- }))
-
- // 第二步:发布任务
+ // 接受成功,准备打开发布弹窗以供用户确认发布
const publishAccount = account || getAccountById(task.accountId)
- if (publishAccount) {
- // 使用选中的素材
- const material = selectedMaterial
-
- // 处理媒体内容
- const videos = material.mediaList?.filter((m: any) => m.type === 'video') || []
- const images = material.mediaList?.filter((m: any) => m.type !== 'video') || []
-
- const publishData = {
- flowId: `${publishAccount.uid}_${generateUUID()}`, // 使用账号的uid作为flowId
- accountType: publishAccount.type,
- accountId: publishAccount.id,
- title: material.title || task.title,
- desc: material.desc || task.description,
- type: 'article' as any, // 固定为 article 类型
- // 处理素材数据
- videoUrl: videos.length > 0 ? getOssUrl(videos[0].url) : undefined,
- coverUrl: material.coverUrl ? getOssUrl(material.coverUrl) : undefined,
- imgUrlList: images.map((img: any) => getOssUrl(img.url)),
- option: {},
- topics: [],
- publishTime: getUtcDays(getDays().add(6, 'minute')).format(),
- userTaskId: response.data.id,
- taskMaterialId: material._id, // 使用选中素材的ID
- }
+ const material = selectedMaterial
- const publishResponse: any = await apiCreatePublish(publishData)
+ // 保存待提交任务信息,等待用户在发布弹窗发布后调用提交接口(可能没有 material)
+ setPendingUserTaskIdForPublish(response.data.id)
+ setPendingTaskMaterialIdForPublish(material?._id)
+ setPendingTaskForPublish(task)
- console.log('publishResponse', publishResponse)
- // return false;
+ // 初始化发布弹窗的数据(传入当前的账号列表并默认选中发布账号)
+ try {
+ usePublishDialog.getState().init(accountList.length > 0 ? accountList : (publishAccount ? [publishAccount] : []), publishAccount?.id)
+
+ // 预填充当前账号的发布参数(优先使用推荐草稿 material,否则使用 task 的描述/标题)
+ const videos = material?.mediaList?.filter((m: any) => m.type === 'video') || []
+ const images = material?.mediaList?.filter((m: any) => m.type !== 'video') || []
+
+ const imgFiles = images.map((img: any) => ({
+ id: generateUUID(),
+ size: 0,
+ file: {} as any,
+ imgUrl: getOssUrl(img.url),
+ filename: '',
+ imgPath: '',
+ width: 0,
+ height: 0,
+ ossUrl: getOssUrl(img.url),
+ }))
- if (publishResponse && publishResponse.code === 0) {
- // 更新进度:第二步完成,开始第三步
- setTaskProgress(prev => ({
- ...prev,
- currentStep: 2,
- steps: [
- { title: t('acceptingTask' as any), status: 'finish' },
- { title: t('publishingTask' as any), status: 'finish' },
- { title: t('submittingTask' as any), status: 'processing' },
- { title: t('taskCompleted' as any), status: 'wait' },
- ],
- }))
+ const videoFile = videos.length > 0 ? {
+ size: 0,
+ file: {} as any,
+ videoUrl: '',
+ ossUrl: getOssUrl(videos[0].url),
+ filename: '',
+ width: 0,
+ height: 0,
+ duration: 0,
+ cover: {
+ id: generateUUID(),
+ size: 0,
+ file: {} as any,
+ imgUrl: material?.coverUrl ? getOssUrl(material.coverUrl) : (videos[0].cover ? getOssUrl(videos[0].cover) : ''),
+ filename: '',
+ imgPath: '',
+ width: 0,
+ height: 0,
+ ossUrl: material?.coverUrl ? getOssUrl(material.coverUrl) : (videos[0].cover ? getOssUrl(videos[0].cover) : ''),
+ },
+ } as any : undefined
+
+ const pubParmas: any = {
+ des: material?.desc || task.description || '',
+ title: material?.title || task.title || '',
+ images: imgFiles.length > 0 ? imgFiles : undefined,
+ video: videoFile,
+ option: {},
+ }
- // 第三步:提交任务
- const userTaskId = response.data.id
- const submitResponse: any = await submitTask(userTaskId, material._id)
-
- if (submitResponse && submitResponse.code === 0) {
- // 更新进度:第三步完成,开始第四步
- setTaskProgress(prev => ({
- ...prev,
- currentStep: 3,
- steps: [
- { title: t('acceptingTask' as any), status: 'finish' },
- { title: t('publishingTask' as any), status: 'finish' },
- { title: t('submittingTask' as any), status: 'finish' },
- { title: t('taskCompleted' as any), status: 'finish' },
- ],
- }))
-
- // 延迟1秒后关闭进度窗口并刷新任务列表
- setTimeout(() => {
- setTaskProgressVisible(false)
- setTaskDetail(null)
- fetchPendingTasks()
- fetchAcceptedTasks()
- setActiveTab('accepted')
- }, 1000)
- }
- else {
- throw new Error('Failed to submit task')
+ if (publishAccount) {
+ // 如果选择了草稿则预填参数,否则不预填
+ if (material) {
+ usePublishDialog.getState().setOnePubParams(pubParmas, publishAccount.id)
}
- }
- else {
- throw new Error('Failed to publish task')
+ setPublishDefaultAccountId(publishAccount.id)
}
}
- else {
- throw new Error('Cannot find publish account info')
+ catch (err) {
+ console.error('初始化发布弹窗数据失败', err)
}
- }
- else {
- throw new Error('Failed to accept task')
+
+ // 打开发布弹窗,用户手动确认发布
+ setTaskDetailModalVisible(false)
+ // 把 taskId 传入 PublishDialog,供其在发布完成时调用回调
+ setPublishDialogOpen(true)
+ // 切换到已接受任务标签
+ setActiveTab('accepted')
+ // 刷新任务列表
+ fetchPendingTasks()
+ fetchAcceptedTasks()
}
}
catch (error) {
- console.error('Task processing failed:', error)
toast.error('Task processing failed')
setTaskProgressVisible(false)
}
@@ -875,10 +876,10 @@ export default function TaskPageCore() {
...prev,
currentStep: 1,
steps: [
- { title: 'Completing task...', status: 'finish' },
- { title: 'Publishing task...', status: 'processing' },
- { title: 'Submitting task...', status: 'wait' },
- { title: 'Task completed', status: 'wait' },
+ { title: t('completeTask'), status: 'finish' },
+ { title: t('publishingTask'), status: 'processing' },
+ { title: t('submittingTask'), status: 'wait' },
+ { title: t('taskCompleted'), status: 'wait' },
],
}))
@@ -927,10 +928,10 @@ export default function TaskPageCore() {
...prev,
currentStep: 2,
steps: [
- { title: 'Completing task...', status: 'finish' },
- { title: 'Publishing task...', status: 'finish' },
- { title: 'Submitting task...', status: 'processing' },
- { title: 'Task completed', status: 'wait' },
+ { title: t('completeTask'), status: 'finish' },
+ { title: t('publishingTask'), status: 'finish' },
+ { title: t('submittingTask'), status: 'processing' },
+ { title: t('taskCompleted'), status: 'wait' },
],
}))
@@ -944,10 +945,10 @@ export default function TaskPageCore() {
...prev,
currentStep: 3,
steps: [
- { title: 'Completing task...', status: 'finish' },
- { title: 'Publishing task...', status: 'finish' },
- { title: 'Submitting task...', status: 'finish' },
- { title: 'Task completed', status: 'finish' },
+ { title: t('completeTask'), status: 'finish' },
+ { title: t('publishingTask'), status: 'finish' },
+ { title: t('submittingTask'), status: 'finish' },
+ { title: t('taskCompleted'), status: 'finish' },
],
}))
@@ -1045,6 +1046,71 @@ export default function TaskPageCore() {
}
}, [accountList, requiredAccountTypes, taskDetail])
+ // 发布弹窗发布成功回调:校验选中账户是否符合任务要求,符合则提交任务
+ const handlePublishSuccess = async () => {
+ try {
+ // 取得发布时选中的账户
+ const pubListChoosed = usePublishDialog.getState().pubListChoosed || []
+ if (pubListChoosed.length === 0) {
+ toast.error(t('publish.noAccountSelected' as any) || 'No account selected for publish')
+ return
+ }
+
+ const usedAccount = pubListChoosed[0].account
+
+ // 校验:如果任务指定了 accountId,则必须一致;否则检查账户类型是否被任务接受
+ const task = pendingTaskForPublish
+ let ok = false
+ if (task) {
+ if (task.accountId) {
+ ok = usedAccount.id === task.accountId
+ }
+ else if (task.accountTypes && task.accountTypes.length > 0) {
+ ok = task.accountTypes.includes(usedAccount.type)
+ }
+ else {
+ ok = true
+ }
+ }
+
+ if (!ok) {
+ toast.error(t('publish.accountNotMatchTask' as any) || 'Selected account does not match task requirement')
+ return
+ }
+
+ // 直接调用提交任务接口(不再弹出“任务处理中”弹窗)
+ if (pendingUserTaskIdForPublish && pendingTaskMaterialIdForPublish) {
+ const submitResp: any = await submitTask(pendingUserTaskIdForPublish, pendingTaskMaterialIdForPublish)
+ if (submitResp && submitResp.code === 0) {
+ toast.success(t('messages.submitTaskSuccess' as any) || 'Submit task success')
+ fetchAcceptedTasks()
+ }
+ else {
+ toast.error(t('messages.submitTaskFailed' as any) || 'Submit task failed')
+ }
+ }
+ }
+ catch (err) {
+ console.error('handlePublishSuccess failed', err)
+ toast.error(t('messages.submitTaskFailed' as any) || 'Submit task failed')
+ }
+ finally {
+ // 清理临时状态并关闭发布弹窗
+ setPublishDialogOpen(false)
+ setPublishDefaultAccountId(undefined)
+ setPendingUserTaskIdForPublish(undefined)
+ setPendingTaskMaterialIdForPublish(undefined)
+ setPendingTaskForPublish(null)
+ try {
+ usePublishDialog.getState().clear()
+ usePublishDialog.getState().setPubListChoosed([])
+ }
+ catch (e) {
+ // ignore
+ }
+ }
+ }
+
return (
<div className={styles.taskPage}>
{/* <div className={styles.header}>
@@ -1053,21 +1119,23 @@ export default function TaskPageCore() {
</div> */}
<Tabs
- activeKey={activeTab}
- onChange={setActiveTab}
+ value={activeTab}
+ onValueChange={setActiveTab}
className={styles.tabs}
>
- <TabPane
- tab={(
- <span>
- <ClockCircleOutlined />
- &nbsp;
- {' '}
- {t('pendingTasks')}
- </span>
- )}
- key="pending"
- >
+ <TabsList className="grid w-full grid-cols-2">
+ <TabsTrigger value="pending">
+ <ClockCircleOutlined />
+ &nbsp;
+ {t('pendingTasks')}
+ </TabsTrigger>
+ <TabsTrigger value="accepted">
+ <PlayCircleOutlined />
+ &nbsp;
+ {t('acceptedTasks')}
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="pending">
<Spin spinning={loading}>
{pendingTasks.length > 0 ? (
<div>
@@ -1116,7 +1184,7 @@ export default function TaskPageCore() {
: `${getPlatformName(task.accountType)} Task`}
</h3>
</div>
- <Tag color="orange">{t('taskStatus.pending' as any)}</Tag>
+ <Badge className={getBadgeClassName('orange')}>{t('taskStatus.pending' as any)}</Badge>
</div>
<div className={styles.taskContent}>
@@ -1201,12 +1269,12 @@ export default function TaskPageCore() {
</div>
<div className={styles.taskActions}>
- <Button
- type="primary"
- onClick={() => handleViewTaskDetail(task.id)}
- icon={<EyeOutlined />}
- style={{ width: '100%' }}
- >
+ <Button
+ onClick={(e) => { e.stopPropagation(); handleViewTaskDetail(task.id) }}
+ style={{ width: '100%' }}
+ >
+ <EyeOutlined />
+ &nbsp;
{t('viewDetails')}
</Button>
</div>
@@ -1232,19 +1300,9 @@ export default function TaskPageCore() {
<Empty description={t('messages.noPendingTasks')} />
)}
</Spin>
- </TabPane>
-
- <TabPane
- tab={(
- <span>
- <PlayCircleOutlined />
- &nbsp;
- {' '}
- {t('acceptedTasks')}
- </span>
- )}
- key="accepted"
- >
+ </TabsContent>
+
+ <TabsContent value="accepted">
<Spin spinning={loading}>
{acceptedTasks.length > 0 ? (
<div>
@@ -1277,9 +1335,9 @@ export default function TaskPageCore() {
: `${getPlatformName(task.accountType)}Task`}
</h3>
</div>
- <Tag color={getTaskStatusTag(task.status).color}>
+ <Badge className={getBadgeClassName(getTaskStatusTag(task.status).color)}>
{getTaskStatusTag(task.status).text}
- </Tag>
+ </Badge>
</div>
<div className={styles.taskContent}>
@@ -1359,11 +1417,11 @@ export default function TaskPageCore() {
<div className={styles.taskActions}>
<Button
- type="primary"
- onClick={() => handleViewAcceptedTaskDetail(task.id)}
- icon={<EyeOutlined />}
+ onClick={(e) => { e.stopPropagation(); handleViewAcceptedTaskDetail(task.id) }}
style={{ width: '100%' }}
>
+ <EyeOutlined />
+ &nbsp;
{t('viewDetails')}
</Button>
</div>
@@ -1389,7 +1447,7 @@ export default function TaskPageCore() {
<Empty description={t('messages.noAcceptedTasks')} />
)}
</Spin>
- </TabPane>
+ </TabsContent>
</Tabs>
{/* 提交任务弹窗 */}
@@ -1427,7 +1485,6 @@ export default function TaskPageCore() {
setTaskDetail(null)
setMaterialList([])
setSelectedMaterial(null)
- setDraftSource('task')
}}
footer={null}
width={1200}
@@ -1541,161 +1598,139 @@ export default function TaskPageCore() {
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <span style={{ fontSize: '16px', fontWeight: '600' }}>{t('draft.selectDraft')}</span>
- <Radio.Group
- value={draftSource}
- onChange={(e) => {
- setDraftSource(e.target.value)
- if (e.target.value === 'own') {
- setDraftModalOpen(true)
- }
- }}
- >
- <Radio value="task">{t('draft.taskDraft')}</Radio>
- <Radio value="own">{t('draft.myDraft')}</Radio>
- </Radio.Group>
+ <span style={{ fontSize: '16px', fontWeight: '600' }}>{t('draft.recommendedDraft' as any) || t('draft.selectDraft')}</span>
</div>
- {draftSource === 'own' && selectedMaterial && (
- <Button
- type="link"
- onClick={() => setDraftModalOpen(true)}
- >
- {t('draft.reselect')}
- </Button>
- )}
</div>
- {/* 任务草稿列表 */}
- {draftSource === 'task' && (
- <Spin spinning={materialLoading}>
- {materialList.length > 0 ? (
- <>
- <div style={{
- display: 'grid',
- gridTemplateColumns: 'repeat(3, 1fr)',
- gap: '16px',
- marginBottom: '16px',
- }}
- >
+ {/* 推荐任务草稿列表 */}
+ <Spin spinning={materialLoading}>
+ {materialList.length > 0 ? (
+ <>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: '16px',
+ marginBottom: '16px',
+ }}
+ >
{materialList.map((material: any) => (
<div
key={material._id}
- onClick={() => setSelectedMaterial(material)}
- style={{
- border: selectedMaterial?._id === material._id ? '2px solid #1890ff' : '1px solid #e8e8e8',
- borderRadius: '8px',
- overflow: 'hidden',
- cursor: 'pointer',
- transition: 'all 0.3s ease',
- backgroundColor: selectedMaterial?._id === material._id ? '#e6f7ff' : '#fff',
- }}
+ onClick={(e) => { e.stopPropagation(); setSelectedMaterial(material) }}
+ style={{
+ border: selectedMaterial?._id === material._id ? '2px solid #1890ff' : '1px solid #e8e8e8',
+ borderRadius: '8px',
+ overflow: 'hidden',
+ cursor: 'pointer',
+ transition: 'all 0.3s ease',
+ backgroundColor: selectedMaterial?._id === material._id ? '#e6f7ff' : '#fff',
+ }}
+ >
+ {/* 素材封面 */}
+ <div style={{
+ position: 'relative',
+ paddingTop: '56.25%',
+ background: '#f0f0f0',
+ }}
>
- {/* 素材封面 */}
- <div style={{
- position: 'relative',
- paddingTop: '56.25%',
- background: '#f0f0f0',
- }}
- >
- {material.coverUrl && (
- <Image
- src={getOssUrl(material.coverUrl)}
- alt={material.title}
- fill
- sizes="(max-width: 768px) 100vw, 33vw"
- style={{
- objectFit: 'cover',
- }}
- />
- )}
- {material.mediaList && material.mediaList[0]?.type === 'video' && (
- <div style={{
- position: 'absolute',
- top: '50%',
- left: '50%',
- transform: 'translate(-50%, -50%)',
- color: 'white',
- fontSize: '32px',
- textShadow: '0 2px 4px rgba(0,0,0,0.5)',
- }}
- >
- ▶
- </div>
- )}
- {selectedMaterial?._id === material._id && (
- <div style={{
- position: 'absolute',
- top: '8px',
- right: '8px',
- width: '24px',
- height: '24px',
- borderRadius: '50%',
- backgroundColor: '#1890ff',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- color: 'white',
- fontSize: '14px',
+ {material.coverUrl && (
+ <Image
+ src={getOssUrl(material.coverUrl)}
+ alt={material.title}
+ fill
+ sizes="(max-width: 768px) 100vw, 33vw"
+ style={{
+ objectFit: 'cover',
}}
- >
- ✓
- </div>
- )}
- </div>
-
- {/* 素材信息 */}
- <div style={{ padding: '12px' }}>
+ />
+ )}
+ {material.mediaList && material.mediaList[0]?.type === 'video' && (
<div style={{
- fontSize: '14px',
- fontWeight: '500',
- marginBottom: '4px',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
+ position: 'absolute',
+ top: '50%',
+ left: '50%',
+ transform: 'translate(-50%, -50%)',
+ color: 'white',
+ fontSize: '32px',
+ textShadow: '0 2px 4px rgba(0,0,0,0.5)',
}}
>
- {material.title || 'no title'}
+ ▶
</div>
+ )}
+ {selectedMaterial?._id === material._id && (
<div style={{
- fontSize: '12px',
- color: '#999',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
+ position: 'absolute',
+ top: '8px',
+ right: '8px',
+ width: '24px',
+ height: '24px',
+ borderRadius: '50%',
+ backgroundColor: '#1890ff',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: 'white',
+ fontSize: '14px',
}}
>
- {material.desc || 'no description'}
+ ✓
</div>
- </div>
+ )}
</div>
- ))}
- </div>
- {/* 分页 */}
- {materialPagination.total > materialPagination.pageSize && (
- <div style={{ textAlign: 'center' }}>
- <Pagination
- current={materialPagination.current}
- pageSize={materialPagination.pageSize}
- total={materialPagination.total}
- onChange={(page, pageSize) => {
- if (taskDetail.materialGroupId) {
- fetchMaterialList(taskDetail.materialGroupId, page, pageSize)
- }
+ {/* 素材信息 */}
+ <div style={{ padding: '12px' }}>
+ <div style={{
+ fontSize: '14px',
+ fontWeight: '500',
+ marginBottom: '4px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
}}
- showSizeChanger={false}
- />
+ >
+ {material.title || t('draft.noTitle')}
+ </div>
+ <div style={{
+ fontSize: '12px',
+ color: '#999',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ }}
+ >
+ {material.desc || t('draft.noDescription')}
+ </div>
+ </div>
</div>
- )}
- </>
- ) : (
- <Empty description="no draft material" />
- )}
- </Spin>
- )}
+ ))}
+ </div>
+
+ {/* 分页 */}
+ {materialPagination.total > materialPagination.pageSize && (
+ <div style={{ textAlign: 'center' }}>
+ <Pagination
+ current={materialPagination.current}
+ pageSize={materialPagination.pageSize}
+ total={materialPagination.total}
+ onChange={(page, pageSize) => {
+ if (taskDetail.materialGroupId) {
+ fetchMaterialList(taskDetail.materialGroupId, page, pageSize)
+ }
+ }}
+ showSizeChanger={false}
+ />
+ </div>
+ )}
+ </>
+ ) : (
+ <Empty description={t('draft.noDrafts')} />
+ )}
+ </Spin>
- {/* 我的草稿选择结果 */}
- {draftSource === 'own' && selectedMaterial && (
+ {/* 选中的推荐草稿信息展示 */}
+ {selectedMaterial && (
<div style={{
border: '2px solid #1890ff',
borderRadius: '8px',
@@ -1717,10 +1752,12 @@ export default function TaskPageCore() {
<Image
src={getOssUrl(selectedMaterial.coverUrl)}
alt={selectedMaterial.title}
- fill
- sizes="120px"
+ width={120}
+ height={120}
style={{
objectFit: 'cover',
+ width: '100%',
+ height: '100%',
}}
/>
</div>
@@ -1736,10 +1773,6 @@ export default function TaskPageCore() {
</div>
</div>
)}
-
- {draftSource === 'own' && !selectedMaterial && (
- <Empty description={t('draft.pleaseSelectDraft')} />
- )}
</div>
{/* 底部按钮 */}
@@ -1748,21 +1781,53 @@ export default function TaskPageCore() {
textAlign: 'center',
paddingTop: '16px',
borderTop: '1px solid #e8e8e8',
+ display: 'flex',
+ gap: '12px',
+ justifyContent: 'center',
}}
>
+ {materialList.length > 0 && (
+ <Button
+ size="lg"
+ onClick={() => {
+ // 模式1:使用推荐草稿发布(必须选中推荐草稿)
+ if (!selectedMaterial) {
+ toast.error(t('draft.pleaseSelectDraftMaterial'))
+ return
+ }
+ // 复用账号选择流程
+ handleTaskAction(taskDetail)
+ }}
+ >
+ {t('publish.useRecommended' as any) || '推荐草稿发布'}
+ </Button>
+ )}
+
<Button
- type="primary"
- size="large"
- onClick={() => handleTaskAction(taskDetail)}
- disabled={!selectedMaterial}
+ size="lg"
+ onClick={() => {
+ // 模式2:直接发布(不使用推荐草稿)
+ setSelectedMaterial(null)
+ handleTaskAction(taskDetail)
+ }}
>
- {t('acceptTask')}
+ {t('publish.directPublish' as any) || '直接发布'}
+ </Button>
+
+ <Button
+ size="lg"
+ onClick={() => {
+ // 模式3:Agent 发布,跳转到首页并填充输入
+ const prompt = taskDetail.description || taskDetail.title || ''
+ // 通过 URL query 传参到首页,避免使用 localStorage
+ const params = new URLSearchParams()
+ if (prompt) params.set('agentExternalPrompt', prompt)
+ if (taskDetail?.id) params.set('agentTaskId', taskDetail.id)
+ router.push(`/${lng}?${params.toString()}`)
+ }}
+ >
+ {t('publish.agentPublish' as any) || 'Agent 发布'}
</Button>
- {!selectedMaterial && (
- <div style={{ marginTop: '8px', color: '#ff4d4f', fontSize: '12px' }}>
- {t('draft.pleaseSelectDraftMaterial')}
- </div>
- )}
</div>
)}
</div>
@@ -1774,21 +1839,7 @@ export default function TaskPageCore() {
</Spin>
</Modal>
- {/* DraftSelectionModal 用于选择自己的草稿 */}
- <DraftSelectionModal
- draftModalOpen={draftModalOpen}
- onCancel={() => {
- setDraftModalOpen(false)
- // 如果取消选择且当前选择的是自己的草稿,切换回任务草稿
- if (draftSource === 'own' && !selectedMaterial) {
- setDraftSource('task')
- }
- }}
- onSelectDraft={(draft) => {
- setSelectedMaterial(draft)
- setDraftSource('own')
- }}
- />
+ {/* 已移除:我的草稿选择,当前仅支持推荐草稿和直接发布/Agent 发布 */}
{/* 已接受任务详情弹窗 */}
<Modal
@@ -1830,7 +1881,7 @@ export default function TaskPageCore() {
position: 'relative',
overflow: 'hidden',
}}
- onClick={() => handleVideoCoverClick(acceptedTaskMaterialList[0].mediaList[0], acceptedTaskDetail.task.title)}
+ onClick={(e) => { e.stopPropagation(); handleVideoCoverClick(acceptedTaskMaterialList[0].mediaList[0], acceptedTaskDetail.task.title) }}
>
{/* Video cover image */}
<Image
@@ -1877,7 +1928,7 @@ export default function TaskPageCore() {
height: 'auto',
display: 'block',
}}
- onClick={() => handleMediaClick(acceptedTaskMaterialList[0].mediaList[0], acceptedTaskDetail.task.title)}
+ onClick={(e) => { e.stopPropagation(); handleMediaClick(acceptedTaskMaterialList[0].mediaList[0], acceptedTaskDetail.task.title) }}
/>
) : null}
</div>
@@ -2087,7 +2138,7 @@ export default function TaskPageCore() {
marginBottom: '4px',
}}
>
- 接受时间
+ {t('taskInfo.acceptTime')}
</div>
<div style={{
fontSize: '12px',
@@ -2114,7 +2165,7 @@ export default function TaskPageCore() {
marginBottom: '4px',
}}
>
- 提交时间
+ {t('taskInfo.submitTime')}
</div>
<div style={{
fontSize: '12px',
@@ -2122,7 +2173,7 @@ export default function TaskPageCore() {
color: '#495057',
}}
>
- {acceptedTaskDetail.submissionTime ? formatTime(acceptedTaskDetail.submissionTime) : '未提交'}
+ {acceptedTaskDetail.submissionTime ? formatTime(acceptedTaskDetail.submissionTime) : t('notSubmitted')}
</div>
</div>
</div>
@@ -2140,25 +2191,25 @@ export default function TaskPageCore() {
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <Tag
- color={getTaskStatusTag(acceptedTaskDetail.status).color}
+ <Badge
+ className={getBadgeClassName(getTaskStatusTag(acceptedTaskDetail.status).color)}
style={{
fontSize: '12px',
padding: '4px 8px',
}}
>
{getTaskStatusTag(acceptedTaskDetail.status).text}
- </Tag>
+ </Badge>
<span style={{
fontSize: '12px',
color: '#666',
}}
>
{acceptedTaskDetail.status === 'doing'
- ? 'task pending'
+ ? t('taskStatuses.taskPending')
: acceptedTaskDetail.status === 'pending'
- ? 'task completed'
- : `task status: ${acceptedTaskDetail.status}`}
+ ? t('taskStatuses.taskCompleted')
+ : `${t('taskStatuses.taskStatus')}: ${getTaskStatusTag(acceptedTaskDetail.status).text}`}
</span>
</div>
@@ -2168,7 +2219,7 @@ export default function TaskPageCore() {
}}
>
{acceptedTaskDetail.isFirstTimeSubmission && (
- <span style={{ color: '#52c41a' }}>first submission</span>
+ <span style={{ color: '#52c41a' }}>{t('taskInfo.firstSubmission')}</span>
)}
</div>
</div>
@@ -2180,8 +2231,7 @@ export default function TaskPageCore() {
return (
<div style={{ textAlign: 'center', marginTop: '16px' }}>
<Button
- type="primary"
- size="large"
+ size="lg"
onClick={handleCompleteTask}
style={{ marginTop: '12px' }}
>
@@ -2253,32 +2303,7 @@ export default function TaskPageCore() {
)}
</Modal>
- {/* 任务进度弹窗 */}
- <Modal
- title={t('taskProcessing')}
- open={taskProgressVisible}
- closable={false}
- maskClosable={false}
- footer={null}
- width={500}
- zIndex={3000}
- >
- <Steps
- direction="vertical"
- current={taskProgress.currentStep}
- items={taskProgress.steps.map((step, index) => ({
- title: step.title,
- status: step.status as 'wait' | 'process' | 'finish' | 'error',
- description: index === 0
- ? (step.title.includes(t('completeTask' as any)) ? t('messages.taskProcessFailed') : t('messages.taskProcessFailed'))
- : index === 1
- ? t('messages.taskProcessFailed')
- : index === 2
- ? t('messages.taskProcessFailed')
- : t('messages.taskProcessFailed'),
- }))}
- />
- </Modal>
+ {/* 任务进度弹窗(已移除,提交后只显示 Toast 提示) */}
{/* 账号选择弹窗 */}
<Modal
@@ -2335,7 +2360,7 @@ export default function TaskPageCore() {
title={(
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{ fontWeight: '500' }}>{account.nickname}</span>
- <Tag color="blue">{getPlatformName(account.type)}</Tag>
+ <Badge className={getBadgeClassName('blue')}>{getPlatformName(account.type)}</Badge>
</div>
)}
description={(
@@ -2348,7 +2373,9 @@ export default function TaskPageCore() {
</div>
{account.nickname && (
<div>
- nickname:
+ {t('accountSelect.nickname' as any)}
+ :
+ {' '}
{account.nickname}
</div>
)}
@@ -2370,6 +2397,28 @@ export default function TaskPageCore() {
qrCodeUrl={downloadAppConfig.qrCodeUrl}
zIndex={3000}
/>
+ {/* 发布作品弹窗(用于任务流程触发) */}
+ {accountList.length > 0 && (
+ <PublishDialog
+ open={publishDialogOpen}
+ onClose={() => {
+ setPublishDialogOpen(false)
+ setPublishDefaultAccountId(undefined)
+ setPendingUserTaskIdForPublish(undefined)
+ setPendingTaskMaterialIdForPublish(undefined)
+ setPendingTaskForPublish(null)
+ }}
+ accounts={accountList}
+ defaultAccountId={publishDefaultAccountId}
+ onPubSuccess={handlePublishSuccess}
+ suppressAutoPublish={true}
+ taskIdForPublish={pendingUserTaskIdForPublish}
+ onPublishConfirmed={(taskId?: string) => {
+ // 当 PublishDialog 内部确认发布完成时触发,继续提交任务
+ handlePublishSuccess()
+ }}
+ />
+ )}
</div>
)
}
diff --git a/project/web/src/app/i18n/locales/en/common.json b/project/web/src/app/i18n/locales/en/common.json
index 132dbf16..93d5388e 100644
--- a/project/web/src/app/i18n/locales/en/common.json
+++ b/project/web/src/app/i18n/locales/en/common.json
@@ -35,6 +35,12 @@
"noDescription": "No description",
"noContent": "No content"
},
+ "pagination": {
+ "perPage": "Per page",
+ "items": "items",
+ "jumpTo": "Jump to",
+ "page": "page"
+ },
"notificationTypes": {
"system": "System Notification",
"user": "User Notification",
diff --git a/project/web/src/app/i18n/locales/en/income.json b/project/web/src/app/i18n/locales/en/income.json
index ad00fe38..734df75a 100644
--- a/project/web/src/app/i18n/locales/en/income.json
+++ b/project/web/src/app/i18n/locales/en/income.json
@@ -12,7 +12,7 @@
"actions": "Actions",
"applyWithdraw": "Apply Withdrawal",
"withdrawId": "Withdrawal ID",
- "status": "Status",
+ "statusLabel": "Status",
"updateTime": "Update Time",
"confirmWithdraw": "Confirm Withdrawal Application",
"cancel": "Cancel",
@@ -27,6 +27,10 @@
"reward_back": "Reward Refund",
"task_withdraw": "Task Withdrawal"
},
+ "status": {
+ "pending": "Pending",
+ "withdrawn": "Withdrawn"
+ },
"withdrawStatus": {
"wait": "Waiting",
"success": "Withdrawal Successful",
diff --git a/project/web/src/app/i18n/locales/en/task.json b/project/web/src/app/i18n/locales/en/task.json
index 3b775d80..c6fe752a 100644
--- a/project/web/src/app/i18n/locales/en/task.json
+++ b/project/web/src/app/i18n/locales/en/task.json
@@ -93,7 +93,10 @@
"justNow": "Just now",
"minutesAgo": "{{minutes}} minutes ago",
"hoursAgo": "{{hours}} hours ago",
- "daysAgo": "{{days}} days ago"
+ "daysAgo": "{{days}} days ago",
+ "minutesLater": "{{minutes}} minutes later",
+ "hoursLater": "{{hours}} hours later",
+ "daysLater": "{{days}} days later"
},
"accountSelect": {
"title": "Select Account",
@@ -104,6 +107,7 @@
},
"draft": {
"selectDraft": "Select Draft:",
+ "recommendedDraft": "Recommended Draft",
"taskDraft": "Task Draft",
"myDraft": "My Draft",
"reselect": "Reselect",
@@ -113,6 +117,13 @@
"pleaseSelectDraft": "Please select a draft",
"pleaseSelectDraftMaterial": "Please select a draft material first"
},
+ "publish": {
+ "useRecommended": "Publish with recommended draft",
+ "directPublish": "Publish directly",
+ "agentPublish": "Agent Publish",
+ "noAccountSelected": "Please select an account",
+ "accountNotMatchTask": "Selected account does not match task requirement"
+ },
"progress": {
"acceptingTask": "Accepting task...",
"publishingTask": "Publishing task...",
@@ -122,7 +133,12 @@
},
"taskStatuses": {
"pending": "Task Pending",
- "completed": "Task Completed"
+ "completed": "Task Completed",
+ "taskPending": "Task Pending",
+ "taskCompleted": "Task Completed",
+ "taskStatus": "Task Status"
},
- "accountAvatar": "Account Avatar"
+ "accountAvatar": "Account Avatar",
+ "notSubmitted": "Not Submitted",
+ "pleaseSelectDraftMaterial": "Please select a draft material"
}
diff --git a/project/web/src/app/i18n/locales/zh-CN/common.json b/project/web/src/app/i18n/locales/zh-CN/common.json
index 9f6aa5b7..e43f6a22 100644
--- a/project/web/src/app/i18n/locales/zh-CN/common.json
+++ b/project/web/src/app/i18n/locales/zh-CN/common.json
@@ -35,6 +35,12 @@
"noDescription": "暂无描述",
"noContent": "暂无内容"
},
+ "pagination": {
+ "perPage": "每页",
+ "items": "条",
+ "jumpTo": "跳至",
+ "page": "页"
+ },
"notificationTypes": {
"system": "系统通知",
"user": "用户通知",
diff --git a/project/web/src/app/i18n/locales/zh-CN/income.json b/project/web/src/app/i18n/locales/zh-CN/income.json
index bd1583c9..5df5ecd6 100644
--- a/project/web/src/app/i18n/locales/zh-CN/income.json
+++ b/project/web/src/app/i18n/locales/zh-CN/income.json
@@ -12,7 +12,7 @@
"actions": "操作",
"applyWithdraw": "申请提现",
"withdrawId": "提现ID",
- "status": "状态",
+ "statusLabel": "状态",
"updateTime": "更新时间",
"confirmWithdraw": "确认提现申请",
"cancel": "取消",
@@ -27,6 +27,10 @@
"reward_back": "奖励回退",
"task_withdraw": "任务提现"
},
+ "status": {
+ "pending": "待提现",
+ "withdrawn": "已提现"
+ },
"withdrawStatus": {
"wait": "等待处理",
"success": "提现成功",
diff --git a/project/web/src/app/i18n/locales/zh-CN/task.json b/project/web/src/app/i18n/locales/zh-CN/task.json
index 18d9866e..3e4aa64c 100644
--- a/project/web/src/app/i18n/locales/zh-CN/task.json
+++ b/project/web/src/app/i18n/locales/zh-CN/task.json
@@ -93,7 +93,10 @@
"justNow": "刚刚",
"minutesAgo": "{{minutes}}分钟前",
"hoursAgo": "{{hours}}小时前",
- "daysAgo": "{{days}}天前"
+ "daysAgo": "{{days}}天前",
+ "minutesLater": "{{minutes}}分钟后",
+ "hoursLater": "{{hours}}小时后",
+ "daysLater": "{{days}}天后"
},
"accountSelect": {
"title": "选择账号",
@@ -104,6 +107,7 @@
},
"draft": {
"selectDraft": "选择草稿:",
+ "recommendedDraft": "推荐草稿",
"taskDraft": "任务草稿",
"myDraft": "我的草稿",
"reselect": "重新选择",
@@ -113,6 +117,13 @@
"pleaseSelectDraft": "请选择一个草稿",
"pleaseSelectDraftMaterial": "请先选择一个草稿素材"
},
+ "publish": {
+ "useRecommended": "使用推荐草稿发布",
+ "directPublish": "发布完成",
+ "agentPublish": "Agent 完成",
+ "noAccountSelected": "请先选择发布账户",
+ "accountNotMatchTask": "所选账户与任务要求不符"
+ },
"progress": {
"acceptingTask": "正在接受任务...",
"publishingTask": "正在发布任务...",
@@ -122,7 +133,12 @@
},
"taskStatuses": {
"pending": "任务待完成",
- "completed": "任务已完成"
+ "completed": "任务已完成",
+ "taskPending": "任务待完成",
+ "taskCompleted": "任务已完成",
+ "taskStatus": "任务状态"
},
- "accountAvatar": "账号头像"
+ "accountAvatar": "账号头像",
+ "notSubmitted": "未提交",
+ "pleaseSelectDraftMaterial": "请选择一个草稿素材"
}
diff --git a/project/web/src/components/Home/HomeChat/index.tsx b/project/web/src/components/Home/HomeChat/index.tsx
index 75763647..4ba0768c 100644
--- a/project/web/src/components/Home/HomeChat/index.tsx
+++ b/project/web/src/components/Home/HomeChat/index.tsx
@@ -29,6 +29,8 @@ export interface IHomeChatProps {
externalPrompt?: string
/** 清除外部提示词的回调 */
onClearExternalPrompt?: () => void
+ /** 从任务页面跳转带来的任务ID,优先显示在输入框 */
+ agentTaskId?: string
}
/**
@@ -39,6 +41,7 @@ export function HomeChat({
className,
externalPrompt,
onClearExternalPrompt,
+ agentTaskId,
}: IHomeChatProps) {
const { t } = useTransClient('chat')
const { t: tHome } = useTransClient('home')
@@ -52,13 +55,37 @@ export function HomeChat({
// 状态 - 默认显示提示文本
const [inputValue, setInputValue] = useState(defaultPrompt)
- // 当外部提示词变化时更新输入框
+ // 当外部提示词或 agentTaskId 变化时更新输入框
useEffect(() => {
+ if (agentTaskId) {
+ // 优先从 localStorage 读取 agentExternalPrompt(任务页可能在跳转前写入)
+ let desc = ''
+ try {
+ const stored = localStorage.getItem('agentExternalPrompt')
+ if (stored) {
+ desc = stored
+ localStorage.removeItem('agentExternalPrompt')
+ }
+ }
+ catch (e) {
+ // ignore
+ }
+
+ console.log('desc', desc)
+
+ desc = externalPrompt || defaultPrompt
+
+
+ setInputValue(`${desc} TaskId: ${agentTaskId}`)
+ onClearExternalPrompt?.()
+ return
+ }
+
if (externalPrompt) {
setInputValue(externalPrompt)
onClearExternalPrompt?.()
}
- }, [externalPrompt, onClearExternalPrompt])
+ }, [externalPrompt, onClearExternalPrompt, agentTaskId])
const [isSubmitting, setIsSubmitting] = useState(false)
const [addAccountVisible, setAddAccountVisible] = useState(false)
diff --git a/project/web/src/components/PublishDialog/index.tsx b/project/web/src/components/PublishDialog/index.tsx
index 6aad4278..7237afdb 100644
--- a/project/web/src/components/PublishDialog/index.tsx
+++ b/project/web/src/components/PublishDialog/index.tsx
@@ -98,6 +98,12 @@ export interface IPublishDialogProps {
onPubSuccess?: () => void
// 默认选中的账户Id
defaultAccountId?: string
+ // 是否抑制自动发布(用于从任务页面打开,先让用户确认后再发布)
+ suppressAutoPublish?: boolean
+ // 关联的任务ID(如果是从任务流程打开)
+ taskIdForPublish?: string
+ // 发布确认回调(发布完成时触发,并携带 taskIdForPublish)
+ onPublishConfirmed?: (taskId?: string) => void
}
// 发布作品弹框
@@ -110,6 +116,9 @@ const PublishDialog = memo(
accounts,
onPubSuccess,
defaultAccountId,
+ suppressAutoPublish,
+ taskIdForPublish,
+ onPublishConfirmed,
}: IPublishDialogProps,
ref: ForwardedRef<IPublishDialogRef>,
) => {
@@ -710,14 +719,25 @@ const PublishDialog = memo(
})
}
- // 关闭发布弹框
- onClose()
+ // 如果抑制自动发布,跳过自动发布流程
+ if (suppressAutoPublish) {
setCreateLoading(false)
+ return
+ }
- if (onPubSuccess) {
- onPubSuccess()
- }
- usePublishDialogStorageStore.getState().clearPubData()
+ // 关闭发布弹框
+ onClose()
+ setCreateLoading(false)
+
+ // 通知外部发布已完成(携带任务 id,如果有)
+ if (onPublishConfirmed) {
+ onPublishConfirmed(taskIdForPublish)
+ }
+
+ if (onPubSuccess) {
+ onPubSuccess()
+ }
+ usePublishDialogStorageStore.getState().clearPubData()
}, [pubListChoosed, pubTime, isPluginSupportedPlatform, t])
// 处理划词操作
diff --git a/project/web/src/components/SettingsModal/tabs/ProfileTab.tsx b/project/web/src/components/SettingsModal/tabs/ProfileTab.tsx
index 35f3ae34..02b23a4b 100644
--- a/project/web/src/components/SettingsModal/tabs/ProfileTab.tsx
+++ b/project/web/src/components/SettingsModal/tabs/ProfileTab.tsx
@@ -231,7 +231,7 @@ export function ProfileTab({ onClose }: ProfileTabProps) {
{/* 收入信息 */}
<div className="grid grid-cols-2 gap-4">
- <div className="rounded-xl border border-border bg-muted p-4">
+ <div className="rounded-xl border border-border bg-muted p-4 cursor-pointer" onClick={() => { router.push('/income'); onClose() }}>
<p className="mb-1 text-sm text-muted-foreground">{t('profile.totalIncome')}</p>
<p className="text-2xl font-bold text-foreground">{totalIncome.toFixed(2)} USD</p>
</div>
diff --git a/project/web/src/components/WalletModal/index.tsx b/project/web/src/components/WalletModal/index.tsx
new file mode 100644
index 00000000..d6f0909a
--- /dev/null
+++ b/project/web/src/components/WalletModal/index.tsx
@@ -0,0 +1,559 @@
+/**
+ * WalletModal - 钱包管理弹窗组件
+ * 用于管理用户钱包账户,可在其他页面调用
+ */
+
+'use client'
+
+import type { WalletAccount, WalletAccountRequest, WalletAccountUpdateRequest } from '@/api/types/userWalletAccount'
+import { WalletAccountType } from '@/api/types/userWalletAccount'
+import { useEffect, useState } from 'react'
+import {
+ createWalletAccountApi,
+ deleteWalletAccountApi,
+ getWalletAccountListApi,
+ updateWalletAccountApi,
+ setDefaultWalletAccountApi,
+} from '@/api/payment'
+// 邮箱正则表达式
+const EMAIL_REGEX = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/
+
+// 中国手机号正则表达式(11位数字,1开头)
+const PHONE_REGEX = /^1[3-9]\d{9}$/
+
+// 身份证号正则表达式(支持国际身份证,限制宽松:6-30位字母数字组合,允许横线和空格)
+const ID_CARD_REGEX = /^[A-Za-z0-9\s\-]{6,30}$/
+import { useTransClient } from '@/app/i18n/client'
+import { useUserStore } from '@/store/user'
+import { toast } from '@/lib/toast'
+import { confirm } from '@/lib/confirm'
+import { Button } from '@/components/ui/button'
+import { Modal } from '@/components/ui/modal'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Card } from '@/components/ui/card'
+import { Pagination } from '@/components/ui/pagination'
+import { Spin } from '@/components/ui/spin'
+import { Empty } from '@/components/ui/empty'
+import { Badge } from '@/components/ui/badge'
+import { MoreVertical, Edit, Trash2, Star } from 'lucide-react'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+
+interface WalletModalProps {
+ open: boolean
+ onClose: () => void
+}
+
+export default function WalletModal({ open, onClose }: WalletModalProps) {
+ const { t } = useTransClient('wallet')
+ const { userInfo } = useUserStore()
+
+ const [list, setList] = useState<WalletAccount[]>([])
+ const [loading, setLoading] = useState(false)
+ const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 })
+
+ const [formData, setFormData] = useState<Partial<WalletAccountRequest>>({
+ email: '',
+ userName: '',
+ account: '',
+ idCard: '',
+ phone: '',
+ type: WalletAccountType.Alipay,
+ })
+ const [modalOpen, setModalOpen] = useState(false)
+ const [editing, setEditing] = useState<WalletAccount | null>(null)
+ const [submitting, setSubmitting] = useState(false)
+ const [formErrors, setFormErrors] = useState<Record<string, string>>({})
+
+ useEffect(() => {
+ if (open) {
+ fetchList(1, 10)
+ }
+ }, [open])
+
+ async function fetchList(page: number, pageSize: number) {
+ setLoading(true)
+ try {
+ const res = await getWalletAccountListApi({ page, pageSize })
+ if (res?.data) {
+ setList(res.data.list || [])
+ setPagination({ current: page, pageSize, total: res.data.total || 0 })
+ }
+ }
+ finally {
+ setLoading(false)
+ }
+ }
+
+ function openCreate() {
+ setEditing(null)
+ setFormData({
+ email: '',
+ userName: '',
+ account: '',
+ idCard: '',
+ phone: '',
+ type: WalletAccountType.Alipay,
+ })
+ setFormErrors({})
+ setModalOpen(true)
+ }
+
+ function onEdit(record: WalletAccount) {
+ setEditing(record)
+ // 编辑模式下只设置可编辑的字段
+ setFormData({
+ email: record.email || '',
+ userName: record.userName || '',
+ idCard: record.idCard || '',
+ phone: record.phone || '',
+ })
+ setFormErrors({})
+ setModalOpen(true)
+ }
+
+ async function onDelete(record: WalletAccount) {
+ const deleteConfirmDesc = t('actions.deleteConfirmDesc')
+ const result = await confirm({
+ title: t('actions.deleteConfirm'),
+ content: deleteConfirmDesc && deleteConfirmDesc !== 'actions.deleteConfirmDesc' ? deleteConfirmDesc : 'This operation cannot be undone. Are you sure you want to delete this wallet account?',
+ okType: 'destructive',
+ okText: t('actions.confirm' as any),
+ cancelText: t('actions.cancel' as any),
+ })
+
+ console.log('result', result)
+
+ if (result) {
+ try {
+ console.log('Deleting wallet account:', record.id)
+ const res = await deleteWalletAccountApi(record.id)
+ console.log('Delete response:', res)
+
+ // request 函数返回格式:{ code, data, message, url } 或 null
+ // 成功时 code === 0,返回整个响应对象
+ // 失败时返回 null(request 函数内部已显示错误提示)
+ if (res) {
+ // 检查 code 是否为 0(成功)
+ if (res.code === 0 || res.code === '0') {
+ toast.success(t('messages.deleteSuccess'))
+ fetchList(pagination.current, pagination.pageSize)
+ }
+ else {
+ // code 不为 0,显示错误信息
+ const errorMsg = res.message || t('messages.deleteFailed') || 'Delete failed'
+ toast.error(errorMsg)
+ }
+ }
+ else {
+ // res 为 null,说明请求失败(request 函数已显示错误提示)
+ console.warn('Delete wallet account failed: request returned null')
+ }
+ }
+ catch (error) {
+ console.error('Delete wallet account error:', error)
+ toast.error(t('messages.deleteFailed') || 'Delete failed')
+ }
+ }
+ }
+
+ async function onSetDefault(record: WalletAccount) {
+ try {
+ const res = await setDefaultWalletAccountApi(record.id)
+ if (res) {
+ toast.success(t('messages.setDefaultSuccess') || 'Set as default successfully')
+ fetchList(pagination.current, pagination.pageSize)
+ }
+ }
+ catch (error) {
+ toast.error(t('messages.setDefaultFailed') || 'Set as default failed')
+ }
+ }
+
+ function validateForm(): boolean {
+ const errors: Record<string, string> = {}
+
+ // 邮箱校验
+ if (formData.email && !EMAIL_REGEX.test(formData.email)) {
+ errors.email = t('form.mailInvalid') || 'Invalid email format'
+ }
+
+ // 创建模式下才需要验证账号和类型
+ if (!editing) {
+ // 账号必填
+ if (!formData.account) {
+ errors.account = t('form.required') || 'Account is required'
+ }
+
+ // 类型必填
+ if (!formData.type) {
+ errors.type = t('form.required') || 'Type is required'
+ }
+ }
+
+ // 手机号校验
+ if (formData.phone && formData.phone.trim() !== '') {
+ if (!PHONE_REGEX.test(formData.phone.trim())) {
+ errors.phone = 'Invalid phone number format. Please enter a valid 11-digit phone number'
+ }
+ }
+
+ // 身份证号校验
+ if (formData.idCard && formData.idCard.trim() !== '') {
+ const trimmedIdCard = formData.idCard.trim()
+ if (!ID_CARD_REGEX.test(trimmedIdCard)) {
+ errors.idCard = 'Invalid ID number format. Please enter 6-30 alphanumeric characters'
+ }
+ }
+
+ setFormErrors(errors)
+ return Object.keys(errors).length === 0
+ }
+
+ async function onSubmit() {
+ if (!validateForm()) {
+ return
+ }
+
+ setSubmitting(true)
+ try {
+ if (editing) {
+ const updateData: WalletAccountUpdateRequest = {
+ email: formData.email,
+ userName: formData.userName,
+ phone: formData.phone,
+ idCard: formData.idCard,
+ }
+ const res = await updateWalletAccountApi(editing.id, updateData)
+ if (res) {
+ toast.success(t('messages.updateSuccess'))
+ setModalOpen(false)
+ fetchList(pagination.current, pagination.pageSize)
+ }
+ }
+ else {
+ const createData: WalletAccountRequest = {
+ account: formData.account,
+ email: formData.email,
+ userName: formData.userName,
+ phone: formData.phone,
+ idCard: formData.idCard,
+ type: formData.type!,
+ }
+ const res = await createWalletAccountApi(createData)
+ if (res) {
+ toast.success(t('messages.createSuccess'))
+ setModalOpen(false)
+ fetchList(pagination.current, pagination.pageSize)
+ }
+ }
+ }
+ finally {
+ setSubmitting(false)
+ }
+ }
+
+ // 获取类型显示文本
+ const getTypeText = (type: WalletAccountType) => {
+ const typeMap: Record<WalletAccountType, string> = {
+ [WalletAccountType.Alipay]: t('types.ZFB') || 'Alipay',
+ [WalletAccountType.WechatPay]: t('types.WX_PAY') || 'WeChat Pay',
+ [WalletAccountType.StripeConnect]: 'Stripe Connect',
+ }
+ return typeMap[type] || type
+ }
+
+ return (
+ <>
+ <Modal
+ title={t('title')}
+ open={open}
+ onCancel={onClose}
+ footer={null}
+ width="90%"
+ >
+ <div className="space-y-4">
+ <div className="flex justify-end">
+ <Button onClick={openCreate} size="sm">
+ {t('actions.create')}
+ </Button>
+ </div>
+
+ <Spin spinning={loading}>
+ {list.length > 0 ? (
+ <>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {list.map((record) => (
+ <Card key={record.id} className="relative">
+ {/* 右上角状态标识 */}
+ <div className="absolute top-4 right-4 flex gap-2 z-10">
+ {record.isDefault && (
+ <Badge className="bg-primary text-primary-foreground">
+ <Star className="w-3 h-3 mr-1 fill-current" />
+ Default
+ </Badge>
+ )}
+ {record.isVerified && (
+ <Badge className="bg-green-100 text-green-800 border-green-200">
+ Verified
+ </Badge>
+ )}
+ </div>
+
+ {/* 卡片内容 */}
+ <div className="p-4 space-y-3">
+ {/* 类型和操作按钮 */}
+ <div className="flex items-start justify-between">
+ <div>
+ <div className="font-semibold text-lg mb-1">
+ {getTypeText(record.type)}
+ </div>
+ {record.userName && (
+ <div className="text-sm text-muted-foreground">
+ {record.userName}
+ </div>
+ )}
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {!record.isDefault && (
+ <DropdownMenuItem onClick={() => onSetDefault(record)}>
+ <Star className="mr-2 h-4 w-4" />
+ Set as Default
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem onClick={() => onEdit(record)}>
+ <Edit className="mr-2 h-4 w-4" />
+ {t('actions.edit')}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => onDelete(record)}
+ className="text-destructive"
+ >
+ <Trash2 className="mr-2 h-4 w-4" />
+ {t('actions.delete')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ {/* 账号信息 */}
+ <div className="space-y-2 pt-2 border-t">
+ <div>
+ <div className="text-xs text-muted-foreground mb-1">
+ {t('columns.account')}
+ </div>
+ <div className="font-mono text-sm break-all">
+ {record.account}
+ </div>
+ </div>
+
+ {record.email && (
+ <div>
+ <div className="text-xs text-muted-foreground mb-1">
+ {t('columns.mail')}
+ </div>
+ <div className="text-sm break-all">
+ {record.email}
+ </div>
+ </div>
+ )}
+
+ <div className="grid grid-cols-2 gap-3">
+ {record.phone && (
+ <div>
+ <div className="text-xs text-muted-foreground mb-1">
+ {t('columns.phone')}
+ </div>
+ <div className="text-sm">
+ {record.phone}
+ </div>
+ </div>
+ )}
+ {record.idCard && (
+ <div>
+ <div className="text-xs text-muted-foreground mb-1">
+ {t('columns.cardNum')}
+ </div>
+ <div className="text-sm break-all">
+ {record.idCard}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </Card>
+ ))}
+ </div>
+
+ <div className="flex justify-center mt-6">
+ <Pagination
+ current={pagination.current}
+ pageSize={pagination.pageSize}
+ total={pagination.total}
+ onChange={(page, pageSize) => {
+ fetchList(page, pageSize || 10)
+ }}
+ showSizeChanger={false}
+ showQuickJumper={false}
+ showTotal={(total, range) => `${range[0]}-${range[1]} / ${total}`}
+ pageSizeOptions={['5', '10', '20']}
+ />
+ </div>
+ </>
+ ) : (
+ <Empty description={loading ? t('messages.loading') : t('messages.noData')} />
+ )}
+ </Spin>
+ </div>
+ </Modal>
+
+ {/* 创建/编辑弹窗 */}
+ <Modal
+ title={editing ? t('dialogs.editTitle') : t('dialogs.createTitle')}
+ open={modalOpen}
+ onCancel={() => setModalOpen(false)}
+ onOk={onSubmit}
+ okText={t('actions.confirm' as any)}
+ cancelText={t('actions.cancel' as any)}
+ confirmLoading={submitting}
+ width="90%"
+ >
+ <div className="space-y-4 max-h-[70vh] overflow-y-auto">
+ <div className="space-y-2">
+ <Label>
+ {t('form.mail')}
+ </Label>
+ <Input
+ value={formData.email || ''}
+ onChange={(e) => {
+ setFormData({ ...formData, email: e.target.value })
+ if (formErrors.email) {
+ setFormErrors({ ...formErrors, email: '' })
+ }
+ }}
+ placeholder={t('form.mailPlaceholder')}
+ className={formErrors.email ? 'border-destructive' : ''}
+ />
+ {formErrors.email && (
+ <p className="text-sm text-destructive">{formErrors.email}</p>
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t('form.userName')}</Label>
+ <Input
+ value={formData.userName}
+ onChange={(e) => setFormData({ ...formData, userName: e.target.value })}
+ placeholder={t('form.userNamePlaceholder')}
+ />
+ </div>
+
+ {/* 创建模式下显示账号字段 */}
+ {!editing && (
+ <div className="space-y-2">
+ <Label>
+ {t('form.account')}
+ <span className="text-destructive">*</span>
+ </Label>
+ <Input
+ value={formData.account}
+ onChange={(e) => {
+ setFormData({ ...formData, account: e.target.value })
+ if (formErrors.account) {
+ setFormErrors({ ...formErrors, account: '' })
+ }
+ }}
+ placeholder={t('form.accountPlaceholder')}
+ className={formErrors.account ? 'border-destructive' : ''}
+ />
+ {formErrors.account && (
+ <p className="text-sm text-destructive">{formErrors.account}</p>
+ )}
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <Label>{t('form.cardNum')}</Label>
+ <Input
+ value={formData.idCard || ''}
+ onChange={(e) => {
+ setFormData({ ...formData, idCard: e.target.value })
+ if (formErrors.idCard) {
+ setFormErrors({ ...formErrors, idCard: '' })
+ }
+ }}
+ placeholder={t('form.cardNumPlaceholder')}
+ className={formErrors.idCard ? 'border-destructive' : ''}
+ maxLength={30}
+ />
+ {formErrors.idCard && (
+ <p className="text-sm text-destructive">{formErrors.idCard}</p>
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t('form.phone')}</Label>
+ <Input
+ type="tel"
+ value={formData.phone || ''}
+ onChange={(e) => {
+ // 只允许输入数字
+ const value = e.target.value.replace(/\D/g, '')
+ setFormData({ ...formData, phone: value })
+ if (formErrors.phone) {
+ setFormErrors({ ...formErrors, phone: '' })
+ }
+ }}
+ placeholder={t('form.phonePlaceholder')}
+ className={formErrors.phone ? 'border-destructive' : ''}
+ maxLength={11}
+ />
+ {formErrors.phone && (
+ <p className="text-sm text-destructive">{formErrors.phone}</p>
+ )}
+ </div>
+
+ {/* 创建模式下显示类型字段 */}
+ {!editing && (
+ <div className="space-y-2">
+ <Label>
+ {t('form.type')}
+ <span className="text-destructive">*</span>
+ </Label>
+ <select
+ value={formData.type}
+ onChange={(e) => {
+ setFormData({ ...formData, type: e.target.value as WalletAccountType })
+ if (formErrors.type) {
+ setFormErrors({ ...formErrors, type: '' })
+ }
+ }}
+ className="h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
+ >
+ <option value={WalletAccountType.Alipay}>{t('types.ZFB') || 'Alipay'}</option>
+ <option value={WalletAccountType.WechatPay}>{t('types.WX_PAY') || 'WeChat Pay'}</option>
+ <option value={WalletAccountType.StripeConnect}>Stripe Connect</option>
+ </select>
+ {formErrors.type && (
+ <p className="text-sm text-destructive">{formErrors.type}</p>
+ )}
+ </div>
+ )}
+ </div>
+ </Modal>
+ </>
+ )
+}
+
diff --git a/project/web/src/components/ui/card.tsx b/project/web/src/components/ui/card.tsx
new file mode 100644
index 00000000..86cd9847
--- /dev/null
+++ b/project/web/src/components/ui/card.tsx
@@ -0,0 +1,38 @@
+/**
+ * Card - 卡片组件
+ * 用于显示卡片内容
+ */
+
+'use client'
+
+import { cn } from '@/lib/utils'
+
+interface CardProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> {
+ /** 标题 */
+ title?: React.ReactNode
+ /** 额外内容 */
+ extra?: React.ReactNode
+}
+
+export function Card({ className, title, extra, children, ...props }: CardProps) {
+ return (
+ <div
+ className={cn(
+ 'rounded-lg border bg-card text-card-foreground shadow-sm',
+ className
+ )}
+ {...props}
+ >
+ {(title || extra) && (
+ <div className="flex items-center justify-between p-6 pb-4">
+ {title && <h3 className="text-lg font-semibold">{title}</h3>}
+ {extra && <div>{extra}</div>}
+ </div>
+ )}
+ <div className={cn('p-6', !title && !extra && 'p-6')}>
+ {children}
+ </div>
+ </div>
+ )
+}
+
diff --git a/project/web/src/components/ui/dialog.tsx b/project/web/src/components/ui/dialog.tsx
index 474448f6..456ec156 100644
--- a/project/web/src/components/ui/dialog.tsx
+++ b/project/web/src/components/ui/dialog.tsx
@@ -29,12 +29,20 @@ const DialogOverlay = React.forwardRef<
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
+interface DialogContentProps extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
+ overlayStyle?: React.CSSProperties
+ overlayClassName?: string
+}
+
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
->(({ className, children, ...props }, ref) => (
+ DialogContentProps
+>(({ className, children, overlayStyle, overlayClassName, ...props }, ref) => (
<DialogPortal>
- <DialogOverlay />
+ <DialogOverlay
+ className={overlayClassName}
+ style={overlayStyle}
+ />
<DialogPrimitive.Content
ref={ref}
className={cn(
diff --git a/project/web/src/components/ui/empty.tsx b/project/web/src/components/ui/empty.tsx
new file mode 100644
index 00000000..ce749df4
--- /dev/null
+++ b/project/web/src/components/ui/empty.tsx
@@ -0,0 +1,29 @@
+/**
+ * Empty - 空状态组件
+ * 用于显示空数据状态
+ */
+
+'use client'
+
+import { cn } from '@/lib/utils'
+
+interface EmptyProps {
+ /** 描述文字 */
+ description?: React.ReactNode
+ /** 自定义图标 */
+ image?: React.ReactNode
+ /** 自定义类名 */
+ className?: string
+}
+
+export function Empty({ description = '暂无数据', image, className }: EmptyProps) {
+ return (
+ <div className={cn('flex flex-col items-center justify-center py-12 px-4', className)}>
+ {image || (
+ <div className="text-6xl mb-4 opacity-30">📭</div>
+ )}
+ <p className="text-sm text-muted-foreground">{description}</p>
+ </div>
+ )
+}
+
diff --git a/project/web/src/components/ui/grid.tsx b/project/web/src/components/ui/grid.tsx
new file mode 100644
index 00000000..4361c8af
--- /dev/null
+++ b/project/web/src/components/ui/grid.tsx
@@ -0,0 +1,77 @@
+/**
+ * Grid - 栅格布局组件
+ * 用于替代 antd 的 Row/Col
+ */
+
+'use client'
+
+import * as React from 'react'
+import { cn } from '@/lib/utils'
+
+interface RowProps extends React.HTMLAttributes<HTMLDivElement> {
+ /** 栅格间隔 */
+ gutter?: number | [number, number]
+ /** 子元素 */
+ children?: React.ReactNode
+}
+
+function Row({ gutter = 0, className, children, style, ...props }: RowProps) {
+ const [gutterX, gutterY] = Array.isArray(gutter) ? gutter : [gutter, gutter]
+
+ return (
+ <div
+ className={cn('flex flex-wrap', className)}
+ style={{
+ marginLeft: gutterX ? `-${gutterX / 2}px` : undefined,
+ marginRight: gutterX ? `-${gutterX / 2}px` : undefined,
+ marginTop: gutterY ? `-${gutterY / 2}px` : undefined,
+ marginBottom: gutterY ? `-${gutterY / 2}px` : undefined,
+ ...style,
+ }}
+ {...props}
+ >
+ {React.Children.map(children, (child) => {
+ if (React.isValidElement(child)) {
+ return React.cloneElement(child, {
+ style: {
+ paddingLeft: gutterX ? `${gutterX / 2}px` : undefined,
+ paddingRight: gutterX ? `${gutterX / 2}px` : undefined,
+ paddingTop: gutterY ? `${gutterY / 2}px` : undefined,
+ paddingBottom: gutterY ? `${gutterY / 2}px` : undefined,
+ ...(child.props.style || {}),
+ },
+ } as any)
+ }
+ return child
+ })}
+ </div>
+ )
+}
+
+interface ColProps extends React.HTMLAttributes<HTMLDivElement> {
+ /** 栅格占位格数,为 0 时不占位 */
+ span?: number
+ /** 子元素 */
+ children?: React.ReactNode
+}
+
+function Col({ span = 24, className, children, style, ...props }: ColProps) {
+ // 将 antd 的 24 栅格系统转换为百分比
+ const widthPercent = (span / 24) * 100
+
+ return (
+ <div
+ className={cn('flex-shrink-0', className)}
+ style={{
+ width: `${widthPercent}%`,
+ ...style,
+ }}
+ {...props}
+ >
+ {children}
+ </div>
+ )
+}
+
+export { Row, Col }
+
diff --git a/project/web/src/components/ui/list.tsx b/project/web/src/components/ui/list.tsx
new file mode 100644
index 00000000..5169cfa8
--- /dev/null
+++ b/project/web/src/components/ui/list.tsx
@@ -0,0 +1,83 @@
+/**
+ * List - 列表组件
+ * 用于显示列表数据
+ */
+
+'use client'
+
+import { cn } from '@/lib/utils'
+
+interface ListItemMetaProps {
+ avatar?: React.ReactNode
+ title?: React.ReactNode
+ description?: React.ReactNode
+}
+
+function ListItemMeta({ avatar, title, description }: ListItemMetaProps) {
+ return (
+ <div className="flex gap-3">
+ {avatar && (
+ <div className="shrink-0">
+ {avatar}
+ </div>
+ )}
+ <div className="flex-1 min-w-0">
+ {title && (
+ <div className="font-medium mb-1">{title}</div>
+ )}
+ {description && (
+ <div className="text-sm text-muted-foreground">{description}</div>
+ )}
+ </div>
+ </div>
+ )
+}
+
+interface ListItemProps extends React.HTMLAttributes<HTMLDivElement> {
+ children?: React.ReactNode
+}
+
+function ListItem({ className, children, ...props }: ListItemProps) {
+ return (
+ <div
+ className={cn('p-4 border rounded-lg mb-2 cursor-pointer transition-all', className)}
+ {...props}
+ >
+ {children}
+ </div>
+ )
+}
+
+ListItem.Meta = ListItemMeta
+
+interface ListProps<T = any> {
+ dataSource?: T[]
+ renderItem?: (item: T, index: number) => React.ReactNode
+ className?: string
+ children?: React.ReactNode
+}
+
+function List<T = any>({ dataSource, renderItem, className, children }: ListProps<T>) {
+ if (children) {
+ return <div className={cn('space-y-2', className)}>{children}</div>
+ }
+
+ if (!dataSource || !renderItem) {
+ return null
+ }
+
+ return (
+ <div className={cn('space-y-2', className)}>
+ {dataSource.map((item, index) => (
+ <div key={index}>
+ {renderItem(item, index)}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+List.Item = ListItem
+
+export { List, ListItem, ListItemMeta }
+
diff --git a/project/web/src/components/ui/modal.tsx b/project/web/src/components/ui/modal.tsx
index 778a4f2c..bc5e26df 100644
--- a/project/web/src/components/ui/modal.tsx
+++ b/project/web/src/components/ui/modal.tsx
@@ -122,6 +122,9 @@ export const Modal: React.FC<ModalProps> = ({
}
}
+ // 计算 overlay 的 z-index(比 content 小 1)
+ const overlayZIndex = zIndex ? zIndex - 1 : undefined
+
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent
@@ -139,6 +142,7 @@ export const Modal: React.FC<ModalProps> = ({
maxWidth: shouldSetWidthStyle ? 'min(var(--modal-width), calc(100vw - 24px))' : undefined,
...(zIndex ? { zIndex } : {}),
} as React.CSSProperties}
+ overlayStyle={overlayZIndex ? { zIndex: overlayZIndex } : undefined}
onInteractOutside={handleInteractOutside}
onEscapeKeyDown={!closable ? (e) => e.preventDefault() : undefined}
aria-describedby={title ? undefined : undefined}
diff --git a/project/web/src/components/ui/pagination.tsx b/project/web/src/components/ui/pagination.tsx
new file mode 100644
index 00000000..5de0921a
--- /dev/null
+++ b/project/web/src/components/ui/pagination.tsx
@@ -0,0 +1,207 @@
+/**
+ * Pagination - 分页组件
+ * 用于显示分页导航
+ */
+
+'use client'
+
+import { cn } from '@/lib/utils'
+import { ChevronLeft, ChevronRight } from 'lucide-react'
+import { Button } from './button'
+import { useTransClient } from '@/app/i18n/client'
+
+interface PaginationProps {
+ /** 当前页码 */
+ current?: number
+ /** 每页条数 */
+ pageSize?: number
+ /** 总条数 */
+ total?: number
+ /** 页码改变回调 */
+ onChange?: (page: number, pageSize?: number) => void
+ /** 每页条数改变回调 */
+ onShowSizeChange?: (current: number, size: number) => void
+ /** 是否显示每页条数选择器 */
+ showSizeChanger?: boolean
+ /** 是否显示快速跳转 */
+ showQuickJumper?: boolean
+ /** 显示总数 */
+ showTotal?: (total: number, range: [number, number]) => React.ReactNode
+ /** 每页条数选项 */
+ pageSizeOptions?: string[]
+ /** 自定义类名 */
+ className?: string
+}
+
+export function Pagination({
+ current = 1,
+ pageSize = 10,
+ total = 0,
+ onChange,
+ onShowSizeChange,
+ showSizeChanger = false,
+ showQuickJumper = false,
+ showTotal,
+ pageSizeOptions = ['10', '20', '50', '100'],
+ className,
+}: PaginationProps) {
+ const { t } = useTransClient('common')
+ const totalPages = Math.ceil(total / pageSize)
+ const start = (current - 1) * pageSize + 1
+ const end = Math.min(current * pageSize, total)
+
+ const handlePageChange = (page: number) => {
+ if (page >= 1 && page <= totalPages) {
+ onChange?.(page, pageSize)
+ }
+ }
+
+ const handleSizeChange = (size: number) => {
+ onShowSizeChange?.(current, size)
+ onChange?.(1, size)
+ }
+
+ const getPageNumbers = () => {
+ const pages: (number | string)[] = []
+ const maxVisible = 7
+
+ if (totalPages <= maxVisible) {
+ for (let i = 1; i <= totalPages; i++) {
+ pages.push(i)
+ }
+ } else {
+ if (current <= 3) {
+ for (let i = 1; i <= 5; i++) {
+ pages.push(i)
+ }
+ pages.push('ellipsis')
+ pages.push(totalPages)
+ } else if (current >= totalPages - 2) {
+ pages.push(1)
+ pages.push('ellipsis')
+ for (let i = totalPages - 4; i <= totalPages; i++) {
+ pages.push(i)
+ }
+ } else {
+ pages.push(1)
+ pages.push('ellipsis')
+ for (let i = current - 1; i <= current + 1; i++) {
+ pages.push(i)
+ }
+ pages.push('ellipsis')
+ pages.push(totalPages)
+ }
+ }
+
+ return pages
+ }
+
+ if (total === 0) {
+ return null
+ }
+
+ return (
+ <div className={cn('flex flex-wrap items-center justify-center gap-3', className)}>
+ {/* 显示总数 */}
+ {showTotal && (
+ <div className="text-sm text-muted-foreground whitespace-nowrap">
+ {showTotal(total, [start, end])}
+ </div>
+ )}
+
+ {/* 分页按钮组 */}
+ <div className="flex items-center gap-1">
+ {/* 上一页 */}
+ <Button
+ variant="outline"
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => handlePageChange(current - 1)}
+ disabled={current === 1}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+
+ {/* 页码 */}
+ {getPageNumbers().map((page, index) => {
+ if (page === 'ellipsis') {
+ return (
+ <span
+ key={`ellipsis-${index}`}
+ className="px-2 h-8 flex items-center justify-center text-muted-foreground"
+ >
+ ...
+ </span>
+ )
+ }
+
+ const pageNum = page as number
+ return (
+ <Button
+ key={pageNum}
+ variant={current === pageNum ? 'default' : 'outline'}
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => handlePageChange(pageNum)}
+ >
+ {pageNum}
+ </Button>
+ )
+ })}
+
+ {/* 下一页 */}
+ <Button
+ variant="outline"
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => handlePageChange(current + 1)}
+ disabled={current === totalPages}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </div>
+
+ {/* 每页条数选择器 */}
+ {showSizeChanger && (
+ <div className="flex items-center gap-2 text-sm whitespace-nowrap">
+ <span className="text-muted-foreground">{t('pagination.perPage')}</span>
+ <select
+ value={pageSize}
+ onChange={(e) => handleSizeChange(Number(e.target.value))}
+ className="h-8 px-2 py-1 text-sm border border-input rounded-md bg-background hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 transition-colors"
+ >
+ {pageSizeOptions.map((option) => (
+ <option key={option} value={option}>
+ {option}
+ </option>
+ ))}
+ </select>
+ <span className="text-muted-foreground">{t('pagination.items')}</span>
+ </div>
+ )}
+
+ {/* 快速跳转 */}
+ {showQuickJumper && (
+ <div className="flex items-center gap-2 text-sm whitespace-nowrap">
+ <span className="text-muted-foreground">{t('pagination.jumpTo')}</span>
+ <input
+ type="number"
+ min={1}
+ max={totalPages}
+ className="h-8 w-14 px-2 text-sm text-center border border-input rounded-md bg-background hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 transition-colors"
+ placeholder={t('pagination.page')}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ const page = Number((e.target as HTMLInputElement).value)
+ handlePageChange(page)
+ ;(e.target as HTMLInputElement).value = ''
+ }
+ }}
+ />
+ <span className="text-muted-foreground">{t('pagination.page')}</span>
+ </div>
+ )}
+ </div>
+ )
+}
+
diff --git a/project/web/src/components/ui/radio.tsx b/project/web/src/components/ui/radio.tsx
new file mode 100644
index 00000000..5dade89d
--- /dev/null
+++ b/project/web/src/components/ui/radio.tsx
@@ -0,0 +1,79 @@
+/**
+ * Radio - 单选组件
+ * 用于单选选择
+ */
+
+'use client'
+
+import * as React from 'react'
+import { cn } from '@/lib/utils'
+
+interface RadioProps extends React.InputHTMLAttributes<HTMLInputElement> {
+ /** 值 */
+ value?: string | number
+ /** 是否选中 */
+ checked?: boolean
+ /** 是否禁用 */
+ disabled?: boolean
+ /** 子元素 */
+ children?: React.ReactNode
+}
+
+const RadioComponent = React.forwardRef<HTMLInputElement, RadioProps>(
+ ({ className, value, checked, disabled, children, ...props }, ref) => {
+ return (
+ <label className={cn('flex items-center gap-2 cursor-pointer', disabled && 'opacity-50 cursor-not-allowed', className)}>
+ <input
+ type="radio"
+ ref={ref}
+ value={value}
+ checked={checked}
+ disabled={disabled}
+ className="w-4 h-4 text-primary border-gray-300 focus:ring-primary"
+ {...props}
+ />
+ {children && <span>{children}</span>}
+ </label>
+ )
+ },
+)
+RadioComponent.displayName = 'Radio'
+
+interface RadioGroupProps {
+ /** 选中的值 */
+ value?: string | number
+ /** 值改变回调 */
+ onChange?: (e: { target: { value: string | number } }) => void
+ /** 子元素 */
+ children?: React.ReactNode
+ /** 自定义类名 */
+ className?: string
+}
+
+function RadioGroup({ value, onChange, children, className }: RadioGroupProps) {
+ const handleChange = (newValue: string | number) => {
+ onChange?.({ target: { value: newValue } })
+ }
+
+ return (
+ <div className={cn('flex items-center gap-4', className)}>
+ {React.Children.map(children, (child) => {
+ if (React.isValidElement<RadioProps>(child) && child.type === RadioComponent) {
+ return React.cloneElement(child, {
+ checked: child.props.value === value,
+ onChange: () => handleChange(child.props.value as string | number),
+ })
+ }
+ return child
+ })}
+ </div>
+ )
+}
+
+// 创建带 Group 的 Radio 组件
+const Radio = Object.assign(RadioComponent, {
+ Group: RadioGroup,
+})
+
+export { Radio, RadioGroup }
+
diff --git a/project/web/src/components/ui/spin.tsx b/project/web/src/components/ui/spin.tsx
new file mode 100644
index 00000000..4645d0fe
--- /dev/null
+++ b/project/web/src/components/ui/spin.tsx
@@ -0,0 +1,67 @@
+/**
+ * Spin - 加载中组件
+ * 用于显示加载状态
+ */
+
+'use client'
+
+import { cn } from '@/lib/utils'
+
+interface SpinProps {
+ /** 是否显示加载状态 */
+ spinning?: boolean
+ /** 子元素 */
+ children?: React.ReactNode
+ /** 自定义类名 */
+ className?: string
+ /** 提示文字 */
+ tip?: string
+}
+
+export function Spin({ spinning = false, children, className, tip }: SpinProps) {
+ if (!spinning && !children) {
+ return null
+ }
+
+ const spinner = (
+ <div className="flex flex-col items-center justify-center gap-2">
+ <svg
+ className="animate-spin h-5 w-5 text-foreground"
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ />
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
+ />
+ </svg>
+ {tip && <span className="text-sm text-muted-foreground">{tip}</span>}
+ </div>
+ )
+
+ if (!children) {
+ return <div className={cn('flex items-center justify-center p-4', className)}>{spinner}</div>
+ }
+
+ return (
+ <div className={cn('relative', className)}>
+ {spinning && (
+ <div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50 backdrop-blur-sm rounded">
+ {spinner}
+ </div>
+ )}
+ {children}
+ </div>
+ )
+}
+
diff --git a/project/web/src/components/ui/steps.tsx b/project/web/src/components/ui/steps.tsx
new file mode 100644
index 00000000..f79e52c9
--- /dev/null
+++ b/project/web/src/components/ui/steps.tsx
@@ -0,0 +1,158 @@
+/**
+ * Steps - 步骤条组件
+ * 用于显示步骤进度
+ */
+
+'use client'
+
+import { cn } from '@/lib/utils'
+import { Check, Loader2, X } from 'lucide-react'
+
+export type StepStatus = 'wait' | 'process' | 'finish' | 'error'
+
+export interface StepItem {
+ title: React.ReactNode
+ description?: React.ReactNode
+ status?: StepStatus
+}
+
+interface StepsProps {
+ /** 当前步骤索引 */
+ current?: number
+ /** 步骤项数组 */
+ items: StepItem[]
+ /** 方向,vertical 或 horizontal */
+ direction?: 'vertical' | 'horizontal'
+ /** 自定义类名 */
+ className?: string
+}
+
+export function Steps({ current = 0, items, direction = 'horizontal', className }: StepsProps) {
+ const isVertical = direction === 'vertical'
+
+ const getStepStatus = (index: number, itemStatus?: StepStatus): StepStatus => {
+ if (itemStatus) return itemStatus
+ if (index < current) return 'finish'
+ if (index === current) return 'process'
+ return 'wait'
+ }
+
+ const getStepIcon = (index: number, status: StepStatus) => {
+ if (status === 'finish') {
+ return <Check className="w-5 h-5 text-white" />
+ }
+ if (status === 'process') {
+ return <Loader2 className="w-5 h-5 text-white animate-spin" />
+ }
+ if (status === 'error') {
+ return <X className="w-5 h-5 text-white" />
+ }
+ return <span className="text-sm font-medium">{index + 1}</span>
+ }
+
+ const getStepClassName = (status: StepStatus) => {
+ const base = 'flex items-center justify-center w-8 h-8 rounded-full border-2 transition-colors'
+ switch (status) {
+ case 'finish':
+ return cn(base, 'bg-primary border-primary text-white')
+ case 'process':
+ return cn(base, 'bg-primary border-primary text-white')
+ case 'error':
+ return cn(base, 'bg-destructive border-destructive text-white')
+ default:
+ return cn(base, 'bg-background border-muted-foreground/30 text-muted-foreground')
+ }
+ }
+
+ if (isVertical) {
+ return (
+ <div className={cn('flex flex-col gap-4', className)}>
+ {items.map((item, index) => {
+ const status = getStepStatus(index, item.status)
+ const isLast = index === items.length - 1
+
+ return (
+ <div key={index} className="flex gap-4">
+ {/* 步骤图标和连接线 */}
+ <div className="flex flex-col items-center">
+ <div className={getStepClassName(status)}>
+ {getStepIcon(index, status)}
+ </div>
+ {!isLast && (
+ <div
+ className={cn(
+ 'w-0.5 flex-1 mt-2',
+ status === 'finish' || status === 'process' ? 'bg-primary' : 'bg-muted-foreground/30',
+ )}
+ />
+ )}
+ </div>
+
+ {/* 步骤内容 */}
+ <div className="flex-1 pb-4">
+ <div
+ className={cn(
+ 'font-medium mb-1',
+ status === 'process' ? 'text-primary' : status === 'error' ? 'text-destructive' : 'text-foreground',
+ )}
+ >
+ {item.title}
+ </div>
+ {item.description && (
+ <div className="text-sm text-muted-foreground">{item.description}</div>
+ )}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )
+ }
+
+ // Horizontal layout
+ return (
+ <div className={cn('flex items-center', className)}>
+ {items.map((item, index) => {
+ const status = getStepStatus(index, item.status)
+ const isLast = index === items.length - 1
+
+ return (
+ <div key={index} className="flex items-center flex-1">
+ <div className="flex flex-col items-center flex-1">
+ {/* 步骤图标 */}
+ <div className={getStepClassName(status)}>
+ {getStepIcon(index, status)}
+ </div>
+
+ {/* 步骤内容 */}
+ <div className="mt-2 text-center">
+ <div
+ className={cn(
+ 'font-medium text-sm',
+ status === 'process' ? 'text-primary' : status === 'error' ? 'text-destructive' : 'text-foreground',
+ )}
+ >
+ {item.title}
+ </div>
+ {item.description && (
+ <div className="text-xs text-muted-foreground mt-1">{item.description}</div>
+ )}
+ </div>
+ </div>
+
+ {/* 连接线 */}
+ {!isLast && (
+ <div
+ className={cn(
+ 'h-0.5 flex-1 mx-2',
+ status === 'finish' || status === 'process' ? 'bg-primary' : 'bg-muted-foreground/30',
+ )}
+ />
+ )}
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
diff --git a/project/web/src/components/ui/table.tsx b/project/web/src/components/ui/table.tsx
new file mode 100644
index 00000000..8ded5c62
--- /dev/null
+++ b/project/web/src/components/ui/table.tsx
@@ -0,0 +1,73 @@
+/**
+ * Table - 表格组件
+ * 用于显示表格数据
+ */
+
+'use client'
+
+import { cn } from '@/lib/utils'
+
+interface TableProps extends React.HTMLAttributes<HTMLTableElement> {
+ children?: React.ReactNode
+}
+
+function Table({ className, children, ...props }: TableProps) {
+ return (
+ <div className="w-full overflow-auto">
+ <table
+ className={cn('w-full caption-bottom text-sm', className)}
+ {...props}
+ >
+ {children}
+ </table>
+ </div>
+ )
+}
+
+function TableHeader({ className, ...props }: React.HTMLAttributes<HTMLTableSectionElement>) {
+ return (
+ <thead className={cn('[&_tr]:border-b [&_tr]:border-border/50', className)} {...props} />
+ )
+}
+
+function TableBody({ className, ...props }: React.HTMLAttributes<HTMLTableSectionElement>) {
+ return (
+ <tbody className={cn('[&_tr:last-child]:border-0', className)} {...props} />
+ )
+}
+
+function TableRow({ className, ...props }: React.HTMLAttributes<HTMLTableRowElement>) {
+ return (
+ <tr
+ className={cn(
+ 'border-b border-border/30 transition-colors hover:bg-muted/30 data-[state=selected]:bg-muted',
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TableHead({ className, ...props }: React.HTMLAttributes<HTMLTableCellElement>) {
+ return (
+ <th
+ className={cn(
+ 'h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TableCell({ className, ...props }: React.HTMLAttributes<HTMLTableCellElement>) {
+ return (
+ <td
+ className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)}
+ {...props}
+ />
+ )
+}
+
+export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell }
+
diff --git a/project/web/src/lib/confirm.tsx b/project/web/src/lib/confirm.tsx
index e81144bd..9ec56c2d 100644
--- a/project/web/src/lib/confirm.tsx
+++ b/project/web/src/lib/confirm.tsx
@@ -63,21 +63,43 @@ const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
}) => {
const [loading, setLoading] = React.useState(false)
- const handleOk = async () => {
+ const handleOk = async (e?: React.MouseEvent) => {
+ // 阻止 AlertDialogAction 的默认关闭行为
+ e?.preventDefault()
+ e?.stopPropagation()
+
if (onOk) {
try {
setLoading(true)
await onOk()
+ // onOk 完成后,wrappedOptions.onOk 会处理 destroy 和 resolve
+ // 手动关闭对话框(但此时 destroy 已经执行,所以这个调用可能无效,但不影响)
+ onOpenChange(false)
} finally {
setLoading(false)
}
}
- onOpenChange(false)
+ else {
+ // 如果没有 onOk 回调,直接关闭
+ onOpenChange(false)
+ }
}
- const handleCancel = () => {
- onCancel?.()
- onOpenChange(false)
+ const handleCancel = (e?: React.MouseEvent) => {
+ // 阻止 AlertDialogCancel 的默认关闭行为
+ e?.preventDefault()
+ e?.stopPropagation()
+
+ if (onCancel) {
+ onCancel()
+ // onCancel 完成后,wrappedOptions.onCancel 会处理 destroy 和 resolve
+ // 手动关闭对话框(但此时 destroy 已经执行,所以这个调用可能无效,但不影响)
+ onOpenChange(false)
+ }
+ else {
+ // 如果没有 onCancel 回调,直接关闭
+ onOpenChange(false)
+ }
}
// 如果 cancelText 为 undefined 或 null,则不显示取消按钮
@@ -145,13 +167,17 @@ export function confirm(options: ConfirmOptions): Promise<boolean> {
const root = createRoot(container)
+ let isResolved = false
+
const destroy = () => {
root.unmount()
container.remove()
}
const handleOpenChange = (open: boolean) => {
- if (!open) {
+ if (!open && !isResolved) {
+ // 如果对话框关闭但还没有 resolve,说明是点击外部或按 ESC 关闭
+ isResolved = true
destroy()
resolve(false)
}
@@ -160,12 +186,25 @@ export function confirm(options: ConfirmOptions): Promise<boolean> {
const wrappedOptions: ConfirmOptions = {
...options,
onOk: async () => {
- await options.onOk?.()
+ // 先设置 isResolved,防止 onOpenChange 触发时再次 resolve
+ isResolved = true
+ try {
+ await options.onOk?.()
+ } catch (error) {
+ // 如果 onOk 出错,仍然 resolve true(因为用户已经确认了)
+ console.error('onOk error:', error)
+ }
destroy()
resolve(true)
},
onCancel: () => {
- options.onCancel?.()
+ // 先设置 isResolved,防止 onOpenChange 触发时再次 resolve
+ isResolved = true
+ try {
+ options.onCancel?.()
+ } catch (error) {
+ console.error('onCancel error:', error)
+ }
destroy()
resolve(false)
},