feat: improve error handling and code quality

后端改进:
- 添加统一异常处理系统 (exceptions.py, response.py)
- 实现自定义异常类 (ValidationError, AuthorizationError, ResourceNotFoundError, BusinessLogicError)
- 配置全局异常处理器,统一 API 错误响应格式
- 迁移业务逻辑错误到自定义异常 (users.py, auth.py)
- 添加 SQL LIKE 通配符转义,防止通配符滥用
- 使用 EmailStr 进行邮箱格式验证
- 移除敏感字段暴露 (jwt_sub)

前端改进:
- 配置 ESLint 9 (flat config) 和 Prettier
- 修复所有 ESLint 错误和警告
- 移除未使用的变量和导入
- 为组件添加 PropTypes 默认值
- 统一代码格式和风格
This commit is contained in:
2026-01-03 19:01:15 +08:00
parent 523da50123
commit 5cdc8b2144
57 changed files with 4623 additions and 2754 deletions
+106 -100
View File
@@ -29,16 +29,17 @@
</a-descriptions-item>
<a-descriptions-item label="剩余时间">
<a-tag v-if="tokenStatus.is_valid" :color="tokenStatus.expiring_soon ? 'warning' : 'success'">
<a-tag
v-if="tokenStatus.is_valid"
:color="tokenStatus.expiring_soon ? 'warning' : 'success'"
>
{{ formatRemainTime }}
</a-tag>
<a-tag v-else color="error">已过期</a-tag>
</a-descriptions-item>
<a-descriptions-item label="即将过期">
<a-tag v-if="!tokenStatus.is_valid" color="error">
已过期
</a-tag>
<a-tag v-if="!tokenStatus.is_valid" color="error"> 已过期 </a-tag>
<a-tag v-else :color="tokenStatus.expiring_soon ? 'warning' : 'success'">
{{ tokenStatus.expiring_soon ? '是' : '否' }}
</a-tag>
@@ -78,11 +79,7 @@
:loading="taskStore.loading"
style="width: 100%; max-width: 400px; margin-bottom: 20px"
>
<a-select-option
v-for="task in taskStore.tasks"
:key="task.id"
:value="task.id"
>
<a-select-option v-for="task in taskStore.tasks" :key="task.id" :value="task.id">
<div style="display: flex; justify-content: space-between; align-items: center">
<span>{{ task.name }}</span>
<a-tag size="small" :color="task.is_active ? 'success' : 'default'">
@@ -112,14 +109,24 @@
</a-descriptions-item>
<a-descriptions-item label="状态">
<a-tag
:color="lastCheckIn.status === 'success' ? 'success' :
lastCheckIn.status === 'out_of_time' ? 'default' :
lastCheckIn.status === 'unknown' ? 'warning' : 'error'"
:color="
lastCheckIn.status === 'success'
? 'success'
: lastCheckIn.status === 'out_of_time'
? 'default'
: lastCheckIn.status === 'unknown'
? 'warning'
: 'error'
"
>
{{
lastCheckIn.status === 'success' ? '成功' :
lastCheckIn.status === 'out_of_time' ? '时间范围外' :
lastCheckIn.status === 'unknown' ? '异常' : '失败'
lastCheckIn.status === 'success'
? '成功'
: lastCheckIn.status === 'out_of_time'
? '时间范围外'
: lastCheckIn.status === 'unknown'
? '异常'
: '失败'
}}
</a-tag>
</a-descriptions-item>
@@ -166,161 +173,160 @@
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { CalendarOutlined, KeyOutlined, UserOutlined } from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import { useAuthStore } from '@/stores/auth'
import { useUserStore } from '@/stores/user'
import { useTaskStore } from '@/stores/task'
import { useCheckInStore } from '@/stores/checkIn'
import { formatDateTime } from '@/utils/helpers'
import { usePollStatus } from '@/composables/usePollStatus'
import { ref, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { CalendarOutlined, KeyOutlined, UserOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useAuthStore } from '@/stores/auth';
import { useUserStore } from '@/stores/user';
import { useTaskStore } from '@/stores/task';
import { useCheckInStore } from '@/stores/checkIn';
import { formatDateTime } from '@/utils/helpers';
import { usePollStatus } from '@/composables/usePollStatus';
const authStore = useAuthStore()
const userStore = useUserStore()
const taskStore = useTaskStore()
const checkInStore = useCheckInStore()
const authStore = useAuthStore();
const userStore = useUserStore();
const taskStore = useTaskStore();
const checkInStore = useCheckInStore();
// 使用轮询 composable
const { startPolling } = usePollStatus({
interval: 2000, // 每 2 秒轮询一次
maxRetries: 15, // 最多 15 次 (30 秒)
backoff: false // 不使用指数退避
})
interval: 2000, // 每 2 秒轮询一次
maxRetries: 15, // 最多 15 次 (30 秒)
backoff: false, // 不使用指数退避
});
const tokenStatusLoading = ref(false)
const checkInLoading = ref(false)
const selectedTaskId = ref(null)
const tokenStatusLoading = ref(false);
const checkInLoading = ref(false);
const selectedTaskId = ref(null);
const tokenStatus = computed(() => userStore.tokenStatus)
const tokenStatus = computed(() => userStore.tokenStatus);
const lastCheckIn = computed(() => {
if (checkInStore.myRecords.length > 0) {
return checkInStore.myRecords[0]
return checkInStore.myRecords[0];
}
return null
})
return null;
});
const formatExpireTime = computed(() => {
if (!tokenStatus.value || !tokenStatus.value.expires_at) return '-'
return formatDateTime(tokenStatus.value.expires_at * 1000)
})
if (!tokenStatus.value || !tokenStatus.value.expires_at) return '-';
return formatDateTime(tokenStatus.value.expires_at * 1000);
});
const formatRemainTime = computed(() => {
if (!tokenStatus.value || !tokenStatus.value.expires_at) return '-'
if (!tokenStatus.value || !tokenStatus.value.expires_at) return '-';
const now = Date.now()
const expireTime = tokenStatus.value.expires_at * 1000
const diff = expireTime - now
const now = Date.now();
const expireTime = tokenStatus.value.expires_at * 1000;
const diff = expireTime - now;
if (diff <= 0) return '已过期'
if (diff <= 0) return '已过期';
const days = Math.floor(diff / (1000 * 60 * 60 * 24))
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
if (days > 0) return `${days}${hours} 小时`
if (hours > 0) return `${hours} 小时 ${minutes} 分钟`
return `${minutes} 分钟`
})
if (days > 0) return `${days}${hours} 小时`;
if (hours > 0) return `${hours} 小时 ${minutes} 分钟`;
return `${minutes} 分钟`;
});
// 获取 Token 状态
const fetchTokenStatus = async () => {
tokenStatusLoading.value = true
tokenStatusLoading.value = true;
try {
await userStore.fetchTokenStatus()
await userStore.fetchTokenStatus();
} catch (error) {
message.error(error.message || '获取 Token 状态失败')
message.error(error.message || '获取 Token 状态失败');
} finally {
tokenStatusLoading.value = false
tokenStatusLoading.value = false;
}
}
};
// 手动打卡
const handleCheckIn = async () => {
if (!selectedTaskId.value) {
message.warning('请先选择要打卡的任务')
return
message.warning('请先选择要打卡的任务');
return;
}
checkInLoading.value = true
checkInLoading.value = true;
try {
// 调用异步打卡接口,立即返回 record_id
const result = await taskStore.checkInTask(selectedTaskId.value)
const result = await taskStore.checkInTask(selectedTaskId.value);
// 获取 record_id
const recordId = result.record_id
const recordId = result.record_id;
if (!recordId) {
message.error('打卡请求失败:未获取到记录ID')
checkInLoading.value = false
return
message.error('打卡请求失败:未获取到记录ID');
checkInLoading.value = false;
return;
}
// 如果初始状态就是失败,显示错误并刷新记录
if (result.status === 'failure') {
message.error(result.message || '打卡失败')
checkInLoading.value = false
checkInStore.fetchMyRecords({ limit: 1 })
return
message.error(result.message || '打卡失败');
checkInLoading.value = false;
checkInStore.fetchMyRecords({ limit: 1 });
return;
}
// 显示提示消息
message.info('打卡任务已启动,正在后台处理...')
message.info('打卡任务已启动,正在后台处理...');
// 使用轮询 composable 检查打卡状态
startPolling(
async () => {
const status = await taskStore.getCheckInRecordStatus(recordId)
const status = await taskStore.getCheckInRecordStatus(recordId);
return {
completed: status.status !== 'pending',
success: status.status === 'success',
data: status
}
data: status,
};
},
{
onSuccess: () => {
checkInLoading.value = false
message.success('打卡成功!')
checkInStore.fetchMyRecords({ limit: 1 })
checkInLoading.value = false;
message.success('打卡成功!');
checkInStore.fetchMyRecords({ limit: 1 });
},
onFailure: (statusData) => {
checkInLoading.value = false
const errorMsg = statusData.error_message || statusData.response_text || '打卡失败'
message.error(errorMsg)
checkInStore.fetchMyRecords({ limit: 1 })
onFailure: statusData => {
checkInLoading.value = false;
const errorMsg = statusData.error_message || statusData.response_text || '打卡失败';
message.error(errorMsg);
checkInStore.fetchMyRecords({ limit: 1 });
},
onTimeout: () => {
checkInLoading.value = false
message.warning('打卡处理时间较长,请稍后查看打卡记录')
}
checkInLoading.value = false;
message.warning('打卡处理时间较长,请稍后查看打卡记录');
},
}
)
);
} catch (error) {
console.error('启动打卡失败:', error)
checkInLoading.value = false
message.error(error.message || '启动打卡任务失败')
console.error('启动打卡失败:', error);
checkInLoading.value = false;
message.error(error.message || '启动打卡任务失败');
}
}
};
onMounted(async () => {
fetchTokenStatus()
checkInStore.fetchMyRecords({ limit: 1 })
fetchTokenStatus();
checkInStore.fetchMyRecords({ limit: 1 });
// 加载任务列表
try {
await taskStore.fetchMyTasks()
await taskStore.fetchMyTasks();
// 如果只有一个任务,自动选中(优先选择启用的任务)
if (taskStore.activeTasks.length === 1) {
selectedTaskId.value = taskStore.activeTasks[0].id
selectedTaskId.value = taskStore.activeTasks[0].id;
} else if (taskStore.tasks.length === 1) {
selectedTaskId.value = taskStore.tasks[0].id
selectedTaskId.value = taskStore.tasks[0].id;
}
} catch (error) {
message.error(error.message || '加载任务列表失败')
message.error(error.message || '加载任务列表失败');
}
})
});
</script>
<style scoped>
+75 -75
View File
@@ -6,7 +6,9 @@
<template #title>
<div class="card-header">
<h2>接龙自动打卡系统</h2>
<p class="subtitle">{{ loginMode === 'qrcode' ? 'QQ 扫码登录/注册' : '用户名密码登录' }}</p>
<p class="subtitle">
{{ loginMode === 'qrcode' ? 'QQ 扫码登录/注册' : '用户名密码登录' }}
</p>
</div>
</template>
@@ -18,9 +20,9 @@
<!-- QR码登录表单 -->
<a-form
v-if="loginMode === 'qrcode'"
ref="qrcodeFormRef"
:model="qrcodeForm"
:rules="qrcodeRules"
ref="qrcodeFormRef"
layout="vertical"
@submit.prevent="handleQRCodeLogin"
>
@@ -54,9 +56,9 @@
<!-- 别名+密码登录表单 -->
<a-form
v-else
ref="passwordFormRef"
:model="passwordForm"
:rules="passwordRules"
ref="passwordFormRef"
layout="vertical"
>
<a-form-item name="alias">
@@ -98,9 +100,7 @@
</a-form-item>
<div class="tips-link">
<a @click="loginMode = 'qrcode'" class="link-text">
没有密码使用扫码登录
</a>
<a class="link-text" @click="loginMode = 'qrcode'"> 没有密码使用扫码登录 </a>
</div>
</a-form>
@@ -142,59 +142,59 @@
</template>
<script setup>
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, KeyOutlined } from '@ant-design/icons-vue'
import { authAPI } from '@/api'
import { useAuthStore } from '@/stores/auth'
import QRCodeModal from '@/components/QRCodeModal.vue'
import { ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { UserOutlined, KeyOutlined } from '@ant-design/icons-vue';
import { authAPI } from '@/api';
import { useAuthStore } from '@/stores/auth';
import QRCodeModal from '@/components/QRCodeModal.vue';
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const qrcodeFormRef = ref(null)
const passwordFormRef = ref(null)
const loading = ref(false)
const qrcodeVisible = ref(false)
const qrcodeFormRef = ref(null);
const passwordFormRef = ref(null);
const loading = ref(false);
const qrcodeVisible = ref(false);
// 登录模式
const loginMode = ref('qrcode')
const loginMode = ref('qrcode');
const loginModeOptions = [
{ label: '扫码登录', value: 'qrcode' },
{ label: '密码登录', value: 'password' }
]
{ label: '密码登录', value: 'password' },
];
// 监听登录模式切换,同步用户名
watch(loginMode, () => {
// 从密码登录切换到扫码登录
if (loginMode.value === 'qrcode' && passwordForm.value.alias) {
qrcodeForm.value.alias = passwordForm.value.alias
qrcodeForm.value.alias = passwordForm.value.alias;
}
// 从扫码登录切换到密码登录
else if (loginMode.value === 'password' && qrcodeForm.value.alias) {
passwordForm.value.alias = qrcodeForm.value.alias
passwordForm.value.alias = qrcodeForm.value.alias;
}
})
});
// QR码登录表单
const qrcodeForm = ref({
alias: '',
})
});
const qrcodeRules = {
alias: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
],
}
};
// 密码登录表单
const passwordForm = ref({
alias: '',
password: '',
})
});
const passwordRules = {
alias: [
@@ -205,34 +205,34 @@ const passwordRules = {
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, message: '密码至少6个字符', trigger: 'blur' },
],
}
};
// QR码登录
const handleQRCodeLogin = async () => {
if (!qrcodeFormRef.value) return
if (!qrcodeFormRef.value) return;
try {
await qrcodeFormRef.value.validate()
await qrcodeFormRef.value.validate();
// 显示 QR 码弹窗
qrcodeVisible.value = true
} catch (error) {
qrcodeVisible.value = true;
} catch {
// 表单验证失败,不需要打印错误(由 Ant Design 自动显示错误提示)
}
}
};
// 密码登录
const handlePasswordLogin = async () => {
if (!passwordFormRef.value) return
if (!passwordFormRef.value) return;
try {
await passwordFormRef.value.validate()
await passwordFormRef.value.validate();
loading.value = true
loading.value = true;
const response = await authAPI.aliasLogin(
passwordForm.value.alias,
passwordForm.value.password
)
);
if (response.success) {
// 使用 authStore 保存认证信息
@@ -241,18 +241,18 @@ const handlePasswordLogin = async () => {
alias: response.alias,
role: response.role || 'user',
is_approved: response.is_approved !== false,
}
};
// 如果没有 authorization(测试账号),使用 user_id 作为认证凭据
const authToken = response.authorization || `user_id:${response.user_id}`
authStore.setAuth(authToken, user)
const authToken = response.authorization || `user_id:${response.user_id}`;
authStore.setAuth(authToken, user);
// 只有当有真实 authorization 时才获取完整用户信息
if (response.authorization) {
try {
await authStore.fetchCurrentUser()
await authStore.fetchCurrentUser();
} catch (err) {
console.warn('获取完整用户信息失败,使用基本信息:', err)
console.warn('获取完整用户信息失败,使用基本信息:', err);
// 即使失败也继续登录流程
}
} else {
@@ -260,7 +260,7 @@ const handlePasswordLogin = async () => {
message.info({
content: '您正在使用密码登录模式。如需使用打卡功能,请先扫码绑定 QQ。',
duration: 5,
})
});
}
// 如果有 Token 警告,显示提示
@@ -268,71 +268,71 @@ const handlePasswordLogin = async () => {
message.warning({
content: response.warning_message,
duration: 5,
})
});
} else if (response.authorization) {
// 只有有 token 的用户才显示"欢迎回来"
message.success(`欢迎回来,${response.alias}`)
message.success(`欢迎回来,${response.alias}`);
} else {
// 测试账号登录成功提示
message.success(`登录成功,${response.alias}`)
message.success(`登录成功,${response.alias}`);
}
// 跳转到重定向页面或仪表盘
const redirect = route.query.redirect || '/dashboard'
router.push(redirect)
const redirect = route.query.redirect || '/dashboard';
router.push(redirect);
} else {
// 根据不同错误类型提供友好提示
handlePasswordLoginError(response.message)
handlePasswordLoginError(response.message);
}
} catch (error) {
console.error('密码登录失败:', error)
const errorMsg = error.response?.data?.detail || error.message || '登录失败,请稍后重试'
handlePasswordLoginError(errorMsg)
console.error('密码登录失败:', error);
const errorMsg = error.response?.data?.detail || error.message || '登录失败,请稍后重试';
handlePasswordLoginError(errorMsg);
} finally {
loading.value = false
loading.value = false;
}
}
};
// 处理密码登录错误
const handlePasswordLoginError = (msg) => {
const handlePasswordLoginError = msg => {
if (!msg) {
message.error('登录失败,请稍后重试')
return
message.error('登录失败,请稍后重试');
return;
}
// 用户不存在或密码错误
if (msg.includes('用户名或密码错误')) {
message.error('用户名或密码错误')
return
message.error('用户名或密码错误');
return;
}
// 未设置密码
if (msg.includes('未设置密码')) {
message.warning('该账户未设置密码,请使用扫码登录')
return
message.warning('该账户未设置密码,请使用扫码登录');
return;
}
// 用户不存在
if (msg.includes('用户不存在')) {
message.error('用户不存在,请检查用户名或使用扫码登录注册')
return
message.error('用户不存在,请检查用户名或使用扫码登录注册');
return;
}
// 其他错误
message.error(msg || '登录失败,请稍后重试')
}
message.error(msg || '登录失败,请稍后重试');
};
const handleLoginSuccess = (user) => {
message.success(`欢迎回来,${user.alias}`)
const handleLoginSuccess = user => {
message.success(`欢迎回来,${user.alias}`);
// 跳转到重定向页面或仪表盘
const redirect = route.query.redirect || '/dashboard'
router.push(redirect)
}
const redirect = route.query.redirect || '/dashboard';
router.push(redirect);
};
const handleLoginError = (error) => {
message.error(error.message || '登录失败')
}
const handleLoginError = error => {
message.error(error.message || '登录失败');
};
</script>
<style scoped>
+4 -4
View File
@@ -9,13 +9,13 @@
</template>
<script setup>
import { useRouter } from 'vue-router'
import { useRouter } from 'vue-router';
const router = useRouter()
const router = useRouter();
const goHome = () => {
router.push('/')
}
router.push('/');
};
</script>
<style scoped>
+73 -83
View File
@@ -44,13 +44,7 @@
</a-descriptions-item>
</a-descriptions>
<a-alert
message="⚠️ 审批说明"
type="info"
:closable="false"
show-icon
class="mb-6"
>
<a-alert message="⚠️ 审批说明" type="info" :closable="false" show-icon class="mb-6">
<template #description>
<ul class="tips-list">
<li>管理员将在 <strong>24 小时内</strong> 审核您的注册申请</li>
@@ -84,17 +78,13 @@
v-model:open="showProfileModal"
title="完善个人信息"
:confirm-loading="profileLoading"
width="500px"
@ok="handleUpdateProfile"
@cancel="resetProfileForm"
width="500px"
>
<a-form :model="profileForm" layout="vertical">
<a-form-item label="邮箱地址(可选)" name="email">
<a-input
v-model:value="profileForm.email"
placeholder="用于接收审批通知"
type="email"
/>
<a-input v-model:value="profileForm.email" placeholder="用于接收审批通知" type="email" />
<div class="form-hint">建议设置邮箱方便接收审批结果通知</div>
</a-form-item>
@@ -110,11 +100,7 @@
/>
</a-form-item>
<a-form-item
v-if="profileForm.new_password"
label="确认密码"
name="confirm_password"
>
<a-form-item v-if="profileForm.new_password" label="确认密码" name="confirm_password">
<a-input-password
v-model:value="profileForm.confirm_password"
placeholder="再次输入新密码"
@@ -139,118 +125,122 @@
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { ReloadOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons-vue'
import { userAPI } from '@/api'
import { useAuthStore } from '@/stores/auth'
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { ReloadOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons-vue';
import { userAPI } from '@/api';
import { useAuthStore } from '@/stores/auth';
const router = useRouter()
const authStore = useAuthStore()
const user = ref(null)
const showProfileModal = ref(false)
const profileLoading = ref(false)
const router = useRouter();
const authStore = useAuthStore();
const user = ref(null);
const showProfileModal = ref(false);
const profileLoading = ref(false);
const profileForm = ref({
email: '',
new_password: '',
confirm_password: '',
current_password: '',
})
});
const checkStatus = async () => {
try {
const response = await userAPI.getUserStatus()
user.value = response
const response = await userAPI.getUserStatus();
user.value = response;
if (response.is_approved) {
message.success('恭喜!您的账户已通过审批')
router.push('/dashboard')
message.success('恭喜!您的账户已通过审批');
router.push('/dashboard');
} else {
message.info('仍在等待审批中')
message.info('仍在等待审批中');
}
} catch (error) {
console.error('获取状态失败:', error)
message.error('获取状态失败:' + (error.message || '未知错误'))
console.error('获取状态失败:', error);
message.error('获取状态失败:' + (error.message || '未知错误'));
}
}
};
const loadUserInfo = async () => {
try {
const response = await userAPI.getCurrentUser()
user.value = response
const response = await userAPI.getCurrentUser();
user.value = response;
// 初始化表单
profileForm.value.email = response.email || ''
profileForm.value.email = response.email || '';
} catch (error) {
console.error('加载用户信息失败:', error)
console.error('加载用户信息失败:', error);
}
}
};
const handleUpdateProfile = async () => {
// 验证
if (profileForm.value.new_password && profileForm.value.new_password.length < 6) {
message.error('密码至少需要 6 位字符')
return
message.error('密码至少需要 6 位字符');
return;
}
if (profileForm.value.new_password !== profileForm.value.confirm_password) {
message.error('两次输入的密码不一致')
return
message.error('两次输入的密码不一致');
return;
}
if (user.value?.has_password && profileForm.value.new_password && !profileForm.value.current_password) {
message.error('修改密码时需要提供当前密码')
return
if (
user.value?.has_password &&
profileForm.value.new_password &&
!profileForm.value.current_password
) {
message.error('修改密码时需要提供当前密码');
return;
}
profileLoading.value = true
profileLoading.value = true;
try {
const updateData = {}
const updateData = {};
// 只提交有变化的字段
if (profileForm.value.email !== (user.value?.email || '')) {
updateData.email = profileForm.value.email || null
updateData.email = profileForm.value.email || null;
}
if (profileForm.value.new_password) {
updateData.new_password = profileForm.value.new_password
updateData.new_password = profileForm.value.new_password;
if (user.value?.has_password) {
updateData.current_password = profileForm.value.current_password
updateData.current_password = profileForm.value.current_password;
}
}
// 如果没有要更新的字段
if (Object.keys(updateData).length === 0) {
message.info('没有需要更新的信息')
showProfileModal.value = false
return
message.info('没有需要更新的信息');
showProfileModal.value = false;
return;
}
await userAPI.updateProfile(updateData)
message.success('个人信息更新成功')
showProfileModal.value = false
resetProfileForm()
await userAPI.updateProfile(updateData);
message.success('个人信息更新成功');
showProfileModal.value = false;
resetProfileForm();
// 重新加载用户信息
await loadUserInfo()
await loadUserInfo();
// 如果设置了密码,更新本地存储的用户信息
if (updateData.new_password) {
const currentUser = authStore.user
const currentUser = authStore.user;
if (currentUser) {
currentUser.has_password = true
localStorage.setItem('user', JSON.stringify(currentUser))
currentUser.has_password = true;
localStorage.setItem('user', JSON.stringify(currentUser));
}
}
} catch (error) {
console.error('更新个人信息失败:', error)
message.error(error.message || '更新失败,请重试')
console.error('更新个人信息失败:', error);
message.error(error.message || '更新失败,请重试');
} finally {
profileLoading.value = false
profileLoading.value = false;
}
}
};
const resetProfileForm = () => {
profileForm.value = {
@@ -258,24 +248,24 @@ const resetProfileForm = () => {
new_password: '',
confirm_password: '',
current_password: '',
}
}
};
};
const logout = () => {
authStore.logout()
router.push('/login')
}
authStore.logout();
router.push('/login');
};
const formatDate = (dateStr) => {
if (!dateStr) return '未知'
const date = new Date(dateStr)
return date.toLocaleString('zh-CN')
}
const formatDate = dateStr => {
if (!dateStr) return '未知';
const date = new Date(dateStr);
return date.toLocaleString('zh-CN');
};
onMounted(() => {
loadUserInfo()
checkStatus()
})
loadUserInfo();
checkStatus();
});
</script>
<style scoped>
+34 -30
View File
@@ -44,7 +44,7 @@
<!-- 桌面端表格 -->
<a-table
v-if="!isMobile"
:dataSource="checkInStore.myRecords"
:data-source="checkInStore.myRecords"
:columns="columns"
:loading="checkInStore.loading"
:pagination="false"
@@ -58,7 +58,9 @@
</template>
<template v-else-if="column.key === 'status'">
<a-tag v-if="record.status === 'success'" color="success">✅ 打卡成功</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default">🕐 时间范围外</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default"
>🕐 时间范围外</a-tag
>
<a-tag v-else-if="record.status === 'unknown'" color="warning">❗ 打卡异常</a-tag>
<a-tag v-else color="error">❌ 打卡失败</a-tag>
</template>
@@ -86,7 +88,9 @@
</a-descriptions-item>
<a-descriptions-item label="状态">
<a-tag v-if="record.status === 'success'" color="success">✅ 打卡成功</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default">🕐 时间范围外</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default"
>🕐 时间范围外</a-tag
>
<a-tag v-else-if="record.status === 'unknown'" color="warning">❗ 打卡异常</a-tag>
<a-tag v-else color="error">❌ 打卡失败</a-tag>
</a-descriptions-item>
@@ -107,14 +111,14 @@
<div class="pagination-container">
<a-pagination
v-model:current="checkInStore.currentPage"
v-model:pageSize="checkInStore.pageSize"
v-model:page-size="checkInStore.pageSize"
:total="total"
:pageSizeOptions="['10', '20', '50', '100']"
:page-size-options="['10', '20', '50', '100']"
show-size-changer
show-quick-jumper
:show-total="total => `${total} 条记录`"
@change="handlePageChange"
@showSizeChange="handleSizeChange"
@show-size-change="handleSizeChange"
/>
</div>
</a-card>
@@ -123,22 +127,22 @@
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UnorderedListOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import { useBreakpoint } from '@/composables/useBreakpoint'
import { useCheckInStore } from '@/stores/checkIn'
import { formatDateTime } from '@/utils/helpers'
import { computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { UnorderedListOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useBreakpoint } from '@/composables/useBreakpoint';
import { useCheckInStore } from '@/stores/checkIn';
import { formatDateTime } from '@/utils/helpers';
const checkInStore = useCheckInStore()
const { isMobile } = useBreakpoint()
const checkInStore = useCheckInStore();
const { isMobile } = useBreakpoint();
const total = computed(() => checkInStore.total)
const total = computed(() => checkInStore.total);
const successCount = computed(() => {
return checkInStore.myRecords.filter((r) => r.status === 'success').length
})
return checkInStore.myRecords.filter(r => r.status === 'success').length;
});
// 表格列配置
const columns = [
@@ -172,32 +176,32 @@ const columns = [
key: 'response_text',
ellipsis: true,
},
]
];
// 刷新数据
const handleRefresh = async () => {
try {
await checkInStore.fetchMyRecords()
message.success('刷新成功')
await checkInStore.fetchMyRecords();
message.success('刷新成功');
} catch (error) {
message.error(error.message || '刷新失败')
message.error(error.message || '刷新失败');
}
}
};
// 页码改变
const handlePageChange = () => {
checkInStore.fetchMyRecords()
}
checkInStore.fetchMyRecords();
};
// 每页数量改变
const handleSizeChange = () => {
checkInStore.currentPage = 1
checkInStore.fetchMyRecords()
}
checkInStore.currentPage = 1;
checkInStore.fetchMyRecords();
};
onMounted(() => {
checkInStore.fetchMyRecords()
})
checkInStore.fetchMyRecords();
});
</script>
<style scoped>
+68 -89
View File
@@ -37,12 +37,7 @@
修改个人信息
</h2>
<a-form
:model="profileForm"
:rules="profileRules"
ref="profileFormRef"
layout="vertical"
>
<a-form ref="profileFormRef" :model="profileForm" :rules="profileRules" layout="vertical">
<a-form-item label="邮箱" name="email">
<a-input
v-model:value="profileForm.email"
@@ -62,11 +57,7 @@
<a-form-item style="margin-top: 8px">
<a-space>
<a-button
type="primary"
:loading="profileLoading"
@click="handleUpdateProfile"
>
<a-button type="primary" :loading="profileLoading" @click="handleUpdateProfile">
保存
</a-button>
<a-button @click="resetProfileForm">重置</a-button>
@@ -92,14 +83,8 @@
:closable="false"
/>
<a-form
:model="passwordForm"
layout="vertical"
>
<a-form-item
v-if="hasPassword"
label="当前密码"
>
<a-form :model="passwordForm" layout="vertical">
<a-form-item v-if="hasPassword" label="当前密码">
<a-input-password
v-model:value="passwordForm.currentPassword"
placeholder="请输入当前密码"
@@ -125,11 +110,7 @@
<a-form-item style="margin-top: 8px">
<a-space>
<a-button
type="primary"
:loading="passwordLoading"
@click="handleUpdatePassword"
>
<a-button type="primary" :loading="passwordLoading" @click="handleUpdatePassword">
{{ hasPassword ? '修改密码' : '设置密码' }}
</a-button>
<a-button @click="resetPasswordForm">重置</a-button>
@@ -143,130 +124,128 @@
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UserOutlined, EditOutlined, KeyOutlined } from '@ant-design/icons-vue'
import { userAPI } from '@/api'
import Layout from '@/components/Layout.vue'
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { UserOutlined, EditOutlined, KeyOutlined } from '@ant-design/icons-vue';
import { userAPI } from '@/api';
import Layout from '@/components/Layout.vue';
const profileFormRef = ref(null)
const profileLoading = ref(false)
const passwordLoading = ref(false)
const profileFormRef = ref(null);
const profileLoading = ref(false);
const passwordLoading = ref(false);
const user = ref(null)
const hasPassword = ref(false)
const user = ref(null);
const hasPassword = ref(false);
// 个人信息表单
const profileForm = ref({
email: '',
})
});
const profileRules = {
email: [
{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
],
}
email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
};
// 密码表单
const passwordForm = ref({
currentPassword: '',
newPassword: '',
confirmPassword: '',
})
});
// 加载用户信息
const loadUserInfo = async () => {
try {
user.value = await userAPI.getCurrentUser()
profileForm.value.email = user.value.email || ''
user.value = await userAPI.getCurrentUser();
profileForm.value.email = user.value.email || '';
// 从后端返回的数据中获取密码状态
hasPassword.value = user.value.has_password || false
hasPassword.value = user.value.has_password || false;
} catch (error) {
message.error(error.message || '加载用户信息失败')
message.error(error.message || '加载用户信息失败');
}
}
};
// 更新个人信息
const handleUpdateProfile = async () => {
if (!profileFormRef.value) return
if (!profileFormRef.value) return;
try {
await profileFormRef.value.validate()
profileLoading.value = true
await profileFormRef.value.validate();
profileLoading.value = true;
await userAPI.updateProfile({
email: profileForm.value.email || null,
})
});
message.success('个人信息修改成功')
await loadUserInfo()
message.success('个人信息修改成功');
await loadUserInfo();
} catch (error) {
if (error.errorFields) return // 验证错误
const errorMsg = error.response?.data?.detail || error.message || '修改失败'
message.error(errorMsg)
if (error.errorFields) return; // 验证错误
const errorMsg = error.response?.data?.detail || error.message || '修改失败';
message.error(errorMsg);
} finally {
profileLoading.value = false
profileLoading.value = false;
}
}
};
// 重置个人信息表单
const resetProfileForm = () => {
profileForm.value.email = user.value?.email || ''
profileFormRef.value?.clearValidate()
}
profileForm.value.email = user.value?.email || '';
profileFormRef.value?.clearValidate();
};
// 更新密码
const handleUpdatePassword = async () => {
try {
// 手动验证
if (hasPassword.value && !passwordForm.value.currentPassword) {
message.error('请输入当前密码')
return
message.error('请输入当前密码');
return;
}
if (!passwordForm.value.newPassword) {
message.error('请输入新密码')
return
message.error('请输入新密码');
return;
}
if (passwordForm.value.newPassword.length < 6) {
message.error('密码至少需要6个字符')
return
message.error('密码至少需要6个字符');
return;
}
if (!passwordForm.value.confirmPassword) {
message.error('请再次输入新密码')
return
message.error('请再次输入新密码');
return;
}
if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
message.error('两次输入的密码不一致')
return
message.error('两次输入的密码不一致');
return;
}
passwordLoading.value = true
passwordLoading.value = true;
const updateData = {
new_password: passwordForm.value.newPassword,
}
};
if (hasPassword.value) {
updateData.current_password = passwordForm.value.currentPassword
updateData.current_password = passwordForm.value.currentPassword;
}
await userAPI.updateProfile(updateData)
await userAPI.updateProfile(updateData);
message.success(hasPassword.value ? '密码修改成功' : '密码设置成功')
hasPassword.value = true
resetPasswordForm()
message.success(hasPassword.value ? '密码修改成功' : '密码设置成功');
hasPassword.value = true;
resetPasswordForm();
} catch (error) {
const errorMsg = error.response?.data?.detail || error.message || '操作失败'
message.error(errorMsg)
const errorMsg = error.response?.data?.detail || error.message || '操作失败';
message.error(errorMsg);
} finally {
passwordLoading.value = false
passwordLoading.value = false;
}
}
};
// 重置密码表单
const resetPasswordForm = () => {
@@ -274,25 +253,25 @@ const resetPasswordForm = () => {
currentPassword: '',
newPassword: '',
confirmPassword: '',
}
}
};
};
// 格式化日期
const formatDate = (dateString) => {
if (!dateString) return '-'
const date = new Date(dateString)
const formatDate = dateString => {
if (!dateString) return '-';
const date = new Date(dateString);
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
});
};
onMounted(() => {
loadUserInfo()
})
loadUserInfo();
});
</script>
<style scoped>
+125 -131
View File
@@ -4,11 +4,7 @@
<div class="max-w-7xl mx-auto">
<!-- Header -->
<div class="mb-8">
<a-button
@click="router.back()"
type="link"
class="mb-4 flex items-center"
>
<a-button type="link" class="mb-4 flex items-center" @click="router.back()">
<template #icon><LeftOutlined /></template>
返回任务列表
</a-button>
@@ -16,7 +12,9 @@
<a-card v-if="currentTask" class="md3-card">
<div class="flex items-start justify-between">
<div class="flex-1">
<h1 class="text-3xl font-bold text-gradient mb-2">{{ currentTask.name || '未命名任务' }}</h1>
<h1 class="text-3xl font-bold text-gradient mb-2">
{{ currentTask.name || '未命名任务' }}
</h1>
<div class="flex items-center gap-4 text-sm text-on-surface-variant">
<span class="flex items-center">
<NumberOutlined class="mr-1" />
@@ -27,11 +25,7 @@
</a-tag>
</div>
</div>
<a-button
type="primary"
:loading="checkInLoading"
@click="handleManualCheckIn"
>
<a-button type="primary" :loading="checkInLoading" @click="handleManualCheckIn">
{{ checkInLoading ? '打卡中...' : '立即打卡' }}
</a-button>
</div>
@@ -49,31 +43,41 @@
<a-col :xs="12" :sm="8" :md="4">
<a-card class="md3-card animate-slide-up" style="animation-delay: 0.05s">
<p class="text-sm text-on-surface-variant mb-1">成功次数</p>
<p class="text-2xl font-bold text-green-600 dark:text-green-400">{{ recordStats.success }}</p>
<p class="text-2xl font-bold text-green-600 dark:text-green-400">
{{ recordStats.success }}
</p>
</a-card>
</a-col>
<a-col :xs="12" :sm="8" :md="4">
<a-card class="md3-card animate-slide-up" style="animation-delay: 0.1s">
<p class="text-sm text-on-surface-variant mb-1">时间范围外</p>
<p class="text-2xl font-bold text-blue-600 dark:text-blue-400">{{ recordStats.outOfTime }}</p>
<p class="text-2xl font-bold text-blue-600 dark:text-blue-400">
{{ recordStats.outOfTime }}
</p>
</a-card>
</a-col>
<a-col :xs="12" :sm="8" :md="4">
<a-card class="md3-card animate-slide-up" style="animation-delay: 0.15s">
<p class="text-sm text-on-surface-variant mb-1">失败次数</p>
<p class="text-2xl font-bold text-red-600 dark:text-red-400">{{ recordStats.failure }}</p>
<p class="text-2xl font-bold text-red-600 dark:text-red-400">
{{ recordStats.failure }}
</p>
</a-card>
</a-col>
<a-col :xs="12" :sm="8" :md="4">
<a-card class="md3-card animate-slide-up" style="animation-delay: 0.2s">
<p class="text-sm text-on-surface-variant mb-1">异常次数</p>
<p class="text-2xl font-bold text-orange-600 dark:text-orange-400">{{ recordStats.unknown }}</p>
<p class="text-2xl font-bold text-orange-600 dark:text-orange-400">
{{ recordStats.unknown }}
</p>
</a-card>
</a-col>
<a-col :xs="12" :sm="8" :md="4">
<a-card class="md3-card animate-slide-up" style="animation-delay: 0.25s">
<p class="text-sm text-on-surface-variant mb-1">成功率</p>
<p class="text-2xl font-bold text-purple-600 dark:text-purple-400">{{ recordStats.successRate }}%</p>
<p class="text-2xl font-bold text-purple-600 dark:text-purple-400">
{{ recordStats.successRate }}%
</p>
</a-card>
</a-col>
</a-row>
@@ -83,7 +87,12 @@
<a-space wrap :size="[16, 16]">
<div class="flex items-center gap-2">
<span class="text-sm font-medium text-on-surface">状态筛选:</span>
<a-radio-group v-model:value="filterStatus" button-style="solid" size="small" @change="handleFilterChange">
<a-radio-group
v-model:value="filterStatus"
button-style="solid"
size="small"
@change="handleFilterChange"
>
<a-radio-button value="">全部</a-radio-button>
<a-radio-button value="success">成功</a-radio-button>
<a-radio-button value="out_of_time">时间范围外</a-radio-button>
@@ -94,7 +103,12 @@
<div class="flex items-center gap-2">
<span class="text-sm font-medium text-on-surface">触发方式:</span>
<a-radio-group v-model:value="filterTrigger" button-style="solid" size="small" @change="handleFilterChange">
<a-radio-group
v-model:value="filterTrigger"
button-style="solid"
size="small"
@change="handleFilterChange"
>
<a-radio-button value="">全部</a-radio-button>
<a-radio-button value="scheduler">自动</a-radio-button>
<a-radio-button value="manual">手动</a-radio-button>
@@ -115,7 +129,11 @@
</a-card>
</div>
<a-card v-else-if="records.length === 0" class="md3-card text-center" style="padding: 48px 20px;">
<a-card
v-else-if="records.length === 0"
class="md3-card text-center"
style="padding: 48px 20px"
>
<FileTextOutlined class="text-8xl text-on-surface-variant opacity-30 mb-4" />
<h3 class="text-xl font-semibold text-on-surface mb-2">暂无打卡记录</h3>
<p class="text-on-surface-variant">当前筛选条件下没有找到任何打卡记录</p>
@@ -130,25 +148,13 @@
<div class="flex items-start justify-between mb-4">
<div class="flex-1">
<div class="flex items-center gap-3 mb-2 flex-wrap">
<h3 class="text-lg font-semibold text-on-surface">
打卡记录 #{{ record.id }}
</h3>
<a-tag
v-if="record.status === 'success'"
color="success"
> 打卡成功</a-tag>
<a-tag
v-else-if="record.status === 'out_of_time'"
color="default"
>🕐 时间范围外</a-tag>
<a-tag
v-else-if="record.status === 'unknown'"
color="warning"
> 打卡异常</a-tag>
<a-tag
v-else
color="error"
> 打卡失败</a-tag>
<h3 class="text-lg font-semibold text-on-surface">打卡记录 #{{ record.id }}</h3>
<a-tag v-if="record.status === 'success'" color="success"> 打卡成功</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default"
>🕐 时间范围外</a-tag
>
<a-tag v-else-if="record.status === 'unknown'" color="warning"> 打卡异常</a-tag>
<a-tag v-else color="error"> 打卡失败</a-tag>
<a-tag :color="record.trigger_type === 'scheduled' ? 'blue' : 'orange'">
{{ record.trigger_type === 'scheduled' ? '自动触发' : '手动触发' }}
</a-tag>
@@ -161,7 +167,9 @@
</div>
<!-- Record Details -->
<div class="bg-surface-container-high dark:bg-surface-container rounded-lg p-4 space-y-2">
<div
class="bg-surface-container-high dark:bg-surface-container rounded-lg p-4 space-y-2"
>
<div v-if="record.response_text" class="flex items-start">
<span class="text-sm font-medium text-on-surface-variant w-20">响应:</span>
<span class="text-sm text-on-surface flex-1">{{ record.response_text }}</span>
@@ -179,14 +187,14 @@
<div v-if="!loading && records.length > 0" class="mt-6 flex justify-center">
<a-pagination
v-model:current="currentPage"
v-model:pageSize="pageSize"
v-model:page-size="pageSize"
:total="total"
:pageSizeOptions="['10', '20', '50', '100']"
:page-size-options="['10', '20', '50', '100']"
show-size-changer
show-quick-jumper
:show-total="total => `${total} 条记录`"
@change="handlePageChange"
@showSizeChange="handleSizeChange"
@show-size-change="handleSizeChange"
/>
</div>
</div>
@@ -195,47 +203,47 @@
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import {
LeftOutlined,
NumberOutlined,
FileTextOutlined,
ClockCircleOutlined,
ReloadOutlined,
} from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import { useTaskStore } from '@/stores/task'
import { formatDateTime } from '@/utils/helpers'
} from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useTaskStore } from '@/stores/task';
import { formatDateTime } from '@/utils/helpers';
const route = useRoute()
const router = useRouter()
const taskStore = useTaskStore()
const route = useRoute();
const router = useRouter();
const taskStore = useTaskStore();
const taskId = computed(() => parseInt(route.params.taskId))
const currentTask = ref(null)
const records = ref([])
const loading = ref(false)
const checkInLoading = ref(false)
const taskId = computed(() => parseInt(route.params.taskId));
const currentTask = ref(null);
const records = ref([]);
const loading = ref(false);
const checkInLoading = ref(false);
// Pagination
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
// Filters
const filterStatus = ref('')
const filterTrigger = ref('')
const filterStatus = ref('');
const filterTrigger = ref('');
// Stats
const recordStats = computed(() => {
const success = records.value.filter(r => r.status === 'success').length
const outOfTime = records.value.filter(r => r.status === 'out_of_time').length
const failure = records.value.filter(r => r.status === 'failure').length
const unknown = records.value.filter(r => r.status === 'unknown').length
const totalRecords = records.value.length
const successRate = totalRecords > 0 ? Math.round((success / totalRecords) * 100) : 0
const success = records.value.filter(r => r.status === 'success').length;
const outOfTime = records.value.filter(r => r.status === 'out_of_time').length;
const failure = records.value.filter(r => r.status === 'failure').length;
const unknown = records.value.filter(r => r.status === 'unknown').length;
const totalRecords = records.value.length;
const successRate = totalRecords > 0 ? Math.round((success / totalRecords) * 100) : 0;
return {
total: totalRecords,
@@ -244,129 +252,115 @@ const recordStats = computed(() => {
failure,
unknown,
successRate,
}
})
};
});
// 从 payload_config 中提取 ThreadId
const getThreadId = (task) => {
if (!task || !task.payload_config) return '未知'
const getThreadId = task => {
if (!task || !task.payload_config) return '未知';
try {
const payload = JSON.parse(task.payload_config)
return payload.ThreadId || '未知'
const payload = JSON.parse(task.payload_config);
return payload.ThreadId || '未知';
} catch (e) {
console.error('解析 payload_config 失败:', e)
return '未知'
console.error('解析 payload_config 失败:', e);
return '未知';
}
}
};
// 获取任务详情
const fetchTaskDetail = async () => {
try {
currentTask.value = await taskStore.fetchTask(taskId.value)
currentTask.value = await taskStore.fetchTask(taskId.value);
} catch (error) {
message.error(error.message || '获取任务详情失败')
router.push('/tasks')
message.error(error.message || '获取任务详情失败');
router.push('/tasks');
}
}
};
// 获取打卡记录
const fetchRecords = async () => {
loading.value = true
loading.value = true;
try {
const params = {
skip: (currentPage.value - 1) * pageSize.value,
limit: pageSize.value,
}
};
if (filterStatus.value) {
params.status = filterStatus.value
params.status = filterStatus.value;
}
if (filterTrigger.value) {
params.trigger_type = filterTrigger.value
params.trigger_type = filterTrigger.value;
}
const response = await taskStore.fetchTaskRecords(taskId.value, params)
const response = await taskStore.fetchTaskRecords(taskId.value, params);
// API 可能返回数组或对象
if (Array.isArray(response)) {
records.value = response
total.value = response.length
records.value = response;
total.value = response.length;
} else if (response.items) {
records.value = response.items
total.value = response.total || response.items.length
records.value = response.items;
total.value = response.total || response.items.length;
} else {
records.value = []
total.value = 0
records.value = [];
total.value = 0;
}
} catch (error) {
message.error(error.message || '获取打卡记录失败')
message.error(error.message || '获取打卡记录失败');
} finally {
loading.value = false
loading.value = false;
}
}
};
// 手动打卡
const handleManualCheckIn = async () => {
checkInLoading.value = true
checkInLoading.value = true;
// 显示持久化通知
const hide = message.loading('正在打卡中,请稍候... 您可以继续浏览其他页面', 0)
const hide = message.loading('正在打卡中,请稍候... 您可以继续浏览其他页面', 0);
try {
const result = await taskStore.checkInTask(taskId.value)
hide()
const result = await taskStore.checkInTask(taskId.value);
hide();
if (result.success) {
message.success('打卡成功')
message.success('打卡成功');
// 刷新记录列表
await fetchRecords()
await fetchRecords();
} else {
message.warning(result.message || '打卡失败')
message.warning(result.message || '打卡失败');
}
} catch (error) {
hide()
message.error(error.message || '打卡失败')
hide();
message.error(error.message || '打卡失败');
} finally {
checkInLoading.value = false
checkInLoading.value = false;
}
}
};
// 筛选变化
const handleFilterChange = () => {
currentPage.value = 1
fetchRecords()
}
currentPage.value = 1;
fetchRecords();
};
// 分页变化
const handlePageChange = () => {
fetchRecords()
}
fetchRecords();
};
const handleSizeChange = () => {
currentPage.value = 1
fetchRecords()
}
// 格式化响应数据
const formatResponse = (data) => {
if (!data) return '-'
if (typeof data === 'string') {
try {
const parsed = JSON.parse(data)
return JSON.stringify(parsed, null, 2).substring(0, 200) + (data.length > 200 ? '...' : '')
} catch {
return data.substring(0, 200) + (data.length > 200 ? '...' : '')
}
}
return JSON.stringify(data, null, 2).substring(0, 200)
}
currentPage.value = 1;
fetchRecords();
};
onMounted(async () => {
await fetchTaskDetail()
await fetchRecords()
})
await fetchTaskDetail();
await fetchRecords();
});
</script>
<style scoped>
+276 -259
View File
@@ -12,8 +12,8 @@
<a-button
type="primary"
size="large"
@click="showCreateDialog = true"
class="shadow-md3-3"
@click="showCreateDialog = true"
>
<template #icon>
<PlusOutlined />
@@ -31,7 +31,9 @@
<p class="text-sm text-on-surface-variant mb-1">总任务数</p>
<p class="text-3xl font-bold text-primary">{{ taskStore.taskStats.total }}</p>
</div>
<div class="w-12 h-12 bg-primary-100 dark:bg-primary-900/30 rounded-md3 flex items-center justify-center">
<div
class="w-12 h-12 bg-primary-100 dark:bg-primary-900/30 rounded-md3 flex items-center justify-center"
>
<FileTextOutlined class="text-2xl text-primary" />
</div>
</div>
@@ -43,9 +45,13 @@
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-on-surface-variant mb-1">启用中</p>
<p class="text-3xl font-bold text-green-600 dark:text-green-400">{{ taskStore.taskStats.active }}</p>
<p class="text-3xl font-bold text-green-600 dark:text-green-400">
{{ taskStore.taskStats.active }}
</p>
</div>
<div class="w-12 h-12 bg-green-100 dark:bg-green-900/30 rounded-md3 flex items-center justify-center">
<div
class="w-12 h-12 bg-green-100 dark:bg-green-900/30 rounded-md3 flex items-center justify-center"
>
<CheckCircleOutlined class="text-2xl text-green-600 dark:text-green-400" />
</div>
</div>
@@ -57,9 +63,13 @@
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-on-surface-variant mb-1">已禁用</p>
<p class="text-3xl font-bold text-on-surface-variant">{{ taskStore.taskStats.inactive }}</p>
<p class="text-3xl font-bold text-on-surface-variant">
{{ taskStore.taskStats.inactive }}
</p>
</div>
<div class="w-12 h-12 bg-surface-container-high rounded-md3 flex items-center justify-center">
<div
class="w-12 h-12 bg-surface-container-high rounded-md3 flex items-center justify-center"
>
<StopOutlined class="text-2xl text-on-surface-variant" />
</div>
</div>
@@ -71,7 +81,7 @@
<!-- Tasks List -->
<div v-if="loading">
<a-row :gutter="[16, 16]">
<a-col :xs="24" :sm="12" :lg="8" v-for="i in 6" :key="i">
<a-col v-for="i in 6" :key="i" :xs="24" :sm="12" :lg="8">
<a-card>
<a-skeleton :active="true" :paragraph="{ rows: 4 }" />
</a-card>
@@ -79,21 +89,21 @@
</a-row>
</div>
<a-card v-else-if="taskStore.tasks.length === 0" class="md3-card text-center" style="padding: 48px 20px;">
<a-card
v-else-if="taskStore.tasks.length === 0"
class="md3-card text-center"
style="padding: 48px 20px"
>
<FileTextOutlined class="text-8xl text-on-surface-variant opacity-30 mb-4" />
<h3 class="text-xl font-semibold text-on-surface mb-2">暂无任务</h3>
<p class="text-on-surface-variant mb-6">点击右上角的"创建任务"按钮开始添加您的第一个打卡任务</p>
<a-button type="primary" @click="showCreateDialog = true">
创建第一个任务
</a-button>
<p class="text-on-surface-variant mb-6">
点击右上角的"创建任务"按钮开始添加您的第一个打卡任务
</p>
<a-button type="primary" @click="showCreateDialog = true"> 创建第一个任务 </a-button>
</a-card>
<a-row v-else :gutter="[16, 16]">
<a-col
:xs="24" :sm="12" :lg="8"
v-for="task in taskStore.tasks"
:key="task.id"
>
<a-col v-for="task in taskStore.tasks" :key="task.id" :xs="24" :sm="12" :lg="8">
<a-card
class="md3-card hover:scale-105 transform transition-all cursor-pointer animate-slide-up"
@click="viewTask(task)"
@@ -101,8 +111,10 @@
<!-- Task Header -->
<div class="flex items-start justify-between mb-4">
<div class="flex-1">
<h3 class="text-lg font-semibold text-on-surface mb-1">{{ task.name || '未命名任务' }}</h3>
<a-divider style="margin: 8px 0;" />
<h3 class="text-lg font-semibold text-on-surface mb-1">
{{ task.name || '未命名任务' }}
</h3>
<a-divider style="margin: 8px 0" />
<p class="text-sm text-on-surface-variant">任务 ID: {{ task.id }}</p>
</div>
<a-tag :color="task.is_active ? 'success' : 'default'">
@@ -118,21 +130,32 @@
</div>
<div class="flex items-center text-sm text-on-surface-variant">
<ClockCircleOutlined class="mr-2" />
最后打卡: {{ task.last_check_in_time ? formatDateTime(task.last_check_in_time) : '未打卡' }}
最后打卡:
{{ task.last_check_in_time ? formatDateTime(task.last_check_in_time) : '未打卡' }}
</div>
<div class="flex items-center text-sm">
<CheckCircleOutlined class="mr-2 text-on-surface-variant" />
<span v-if="task.last_check_in_status" :class="{
'text-green-600 dark:text-green-400 font-medium': task.last_check_in_status === 'success',
'text-blue-600 dark:text-blue-400 font-medium': task.last_check_in_status === 'out_of_time',
'text-red-600 dark:text-red-400 font-medium': task.last_check_in_status === 'failure',
'text-yellow-600 dark:text-yellow-400 font-medium': task.last_check_in_status === 'unknown'
}">
<span
v-if="task.last_check_in_status"
:class="{
'text-green-600 dark:text-green-400 font-medium':
task.last_check_in_status === 'success',
'text-blue-600 dark:text-blue-400 font-medium':
task.last_check_in_status === 'out_of_time',
'text-red-600 dark:text-red-400 font-medium':
task.last_check_in_status === 'failure',
'text-yellow-600 dark:text-yellow-400 font-medium':
task.last_check_in_status === 'unknown',
}"
>
{{
task.last_check_in_status === 'success' ? '✅ 打卡成功' :
task.last_check_in_status === 'out_of_time' ? '🕐 时间范围外' :
task.last_check_in_status === 'failure' ? '❌ 打卡失败' :
'❗ 打卡异常'
task.last_check_in_status === 'success'
? '✅ 打卡成功'
: task.last_check_in_status === 'out_of_time'
? '🕐 时间范围外'
: task.last_check_in_status === 'failure'
? '❌ 打卡失败'
: '❗ 打卡异常'
}}
</span>
<span v-else class="text-on-surface-variant">暂无打卡记录</span>
@@ -145,33 +168,24 @@
type="primary"
size="small"
:loading="checkInLoading[task.id]"
@click.stop="handleCheckIn(task.id)"
class="flex-1"
@click.stop="handleCheckIn(task.id)"
>
{{ checkInLoading[task.id] ? '打卡中...' : '立即打卡' }}
</a-button>
<a-button
size="small"
@click.stop="toggleTaskStatus(task)"
class="flex-1"
>
<a-button size="small" class="flex-1" @click.stop="toggleTaskStatus(task)">
{{ task.is_active ? '禁用' : '启用' }}
</a-button>
<a-button
type="primary"
size="small"
ghost
@click.stop="editTask(task)"
class="icon-button"
@click.stop="editTask(task)"
>
<template #icon><EditOutlined /></template>
</a-button>
<a-button
danger
size="small"
@click.stop="deleteTask(task)"
class="icon-button"
>
<a-button danger size="small" class="icon-button" @click.stop="deleteTask(task)">
<template #icon><DeleteOutlined /></template>
</a-button>
</div>
@@ -187,7 +201,7 @@
:title="editingTask ? '编辑任务' : '从模板创建任务'"
:width="isMobile ? '100%' : 700"
:style="isMobile ? { top: 0, maxWidth: '100vw' } : {}"
:maskClosable="false"
:mask-closable="false"
>
<!-- 只显示从模板创建 -->
<div v-if="!editingTask">
@@ -203,32 +217,46 @@
<div v-else>
<!-- Template Selection -->
<a-form-item label="选择模板" v-if="!selectedTemplate">
<a-form-item v-if="!selectedTemplate" label="选择模板">
<div class="grid grid-cols-1 gap-3">
<div
v-for="template in activeTemplates"
:key="template.id"
@click="selectTemplate(template)"
class="border border-outline-variant rounded-lg p-4 cursor-pointer hover:border-primary hover:bg-primary-container/10 transition-all"
@click="selectTemplate(template)"
>
<h4 class="font-semibold text-on-surface mb-1">{{ template.name }}</h4>
<p class="text-sm text-on-surface-variant">{{ template.description || '无描述' }}</p>
<p class="text-sm text-on-surface-variant">
{{ template.description || '无描述' }}
</p>
</div>
</div>
</a-form-item>
<!-- Template Form -->
<a-form v-if="selectedTemplate" :model="templateTaskForm" ref="templateFormRef" layout="vertical">
<a-form
v-if="selectedTemplate"
ref="templateFormRef"
:model="templateTaskForm"
layout="vertical"
>
<div class="mb-4 p-3 bg-blue-50 rounded-lg flex items-center justify-between">
<div class="flex items-center">
<FileTextOutlined class="text-blue-600 mr-2" />
<span class="text-sm font-medium text-blue-900">使用模板{{ selectedTemplate.name }}</span>
<span class="text-sm font-medium text-blue-900"
>使用模板{{ selectedTemplate.name }}</span
>
</div>
<a-button size="small" type="link" @click="selectedTemplate = null">更换模板</a-button>
<a-button size="small" type="link" @click="selectedTemplate = null"
>更换模板</a-button
>
</div>
<a-form-item label="任务名称" name="task_name">
<a-input v-model:value="templateTaskForm.task_name" placeholder="可选,留空则自动生成" />
<a-input
v-model:value="templateTaskForm.task_name"
placeholder="可选,留空则自动生成"
/>
</a-form-item>
<a-form-item label="接龙 ID" name="thread_id" required>
@@ -239,10 +267,7 @@
<!-- Dynamic Fields -->
<div v-for="(fieldConfig, key) in visibleFields" :key="key">
<a-form-item
:label="fieldConfig.display_name"
:required="fieldConfig.required"
>
<a-form-item :label="fieldConfig.display_name" :required="fieldConfig.required">
<!-- Text Input -->
<a-input
v-if="fieldConfig.field_type === 'text'"
@@ -292,7 +317,13 @@
</div>
<!-- Edit Mode Form - 简化版只显示任务名称和启用状态 -->
<a-form v-if="editingTask" :model="taskForm" :rules="taskRules" ref="taskFormRef" layout="vertical">
<a-form
v-if="editingTask"
ref="taskFormRef"
:model="taskForm"
:rules="taskRules"
layout="vertical"
>
<a-form-item label="任务名称" name="name">
<a-input v-model:value="taskForm.name" placeholder="请输入任务名称(例如:公司打卡)" />
</a-form-item>
@@ -314,12 +345,7 @@
<div class="mb-4">
<div class="flex items-center justify-between mb-2">
<span class="text-sm text-on-surface-variant">完整的打卡请求配置</span>
<a-button
size="small"
type="primary"
ghost
@click="copyPayload"
>
<a-button size="small" type="primary" ghost @click="copyPayload">
<template #icon><CopyOutlined /></template>
复制
</a-button>
@@ -329,7 +355,7 @@
:rows="12"
readonly
class="font-mono text-xs"
style="resize: vertical; min-height: 200px; max-height: 400px;"
style="resize: vertical; min-height: 200px; max-height: 400px"
/>
<p class="text-xs text-on-surface-variant mt-1">
💡 此配置由模板自动生成如需修改请删除任务后从模板重新创建
@@ -341,7 +367,7 @@
<div class="flex gap-3 justify-end">
<a-button @click="showCreateDialog = false">取消</a-button>
<a-button type="primary" :loading="submitting" @click="handleSubmit">
{{ submitting ? '提交中...' : (editingTask ? '保存修改' : '创建任务') }}
{{ submitting ? '提交中...' : editingTask ? '保存修改' : '创建任务' }}
</a-button>
</div>
</template>
@@ -350,9 +376,9 @@
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import {
PlusOutlined,
FileTextOutlined,
@@ -363,41 +389,41 @@ import {
EditOutlined,
DeleteOutlined,
CopyOutlined,
} from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import CrontabEditor from '@/components/CrontabEditor.vue'
import { useBreakpoint } from '@/composables/useBreakpoint'
import { useTaskStore } from '@/stores/task'
import { useTemplateStore } from '@/stores/template'
import { copyToClipboard, formatDateTime } from '@/utils/helpers'
import { usePollStatus } from '@/composables/usePollStatus'
} from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import CrontabEditor from '@/components/CrontabEditor.vue';
import { useBreakpoint } from '@/composables/useBreakpoint';
import { useTaskStore } from '@/stores/task';
import { useTemplateStore } from '@/stores/template';
import { copyToClipboard, formatDateTime } from '@/utils/helpers';
import { usePollStatus } from '@/composables/usePollStatus';
const router = useRouter()
const taskStore = useTaskStore()
const templateStore = useTemplateStore()
const { isMobile } = useBreakpoint()
const router = useRouter();
const taskStore = useTaskStore();
const templateStore = useTemplateStore();
const { isMobile } = useBreakpoint();
// 使用轮询 composable
const { startPolling } = usePollStatus({
interval: 2000,
maxRetries: 15,
backoff: false
})
backoff: false,
});
const loading = ref(false)
const showCreateDialog = ref(false)
const submitting = ref(false)
const editingTask = ref(null)
const taskFormRef = ref(null)
const templateFormRef = ref(null)
const checkInLoading = ref({})
const loading = ref(false);
const showCreateDialog = ref(false);
const submitting = ref(false);
const editingTask = ref(null);
const taskFormRef = ref(null);
const templateFormRef = ref(null);
const checkInLoading = ref({});
// Template mode
const createMode = ref('template') // 'template' or 'manual'
const loadingTemplates = ref(false)
const activeTemplates = ref([])
const selectedTemplate = ref(null)
const templatePreview = ref(null) // 存储从 preview 接口获取的合并后配置
const createMode = ref('template'); // 'template' or 'manual'
const loadingTemplates = ref(false);
const activeTemplates = ref([]);
const selectedTemplate = ref(null);
const templatePreview = ref(null); // 存储从 preview 接口获取的合并后配置
// Manual create form
const taskForm = reactive({
@@ -406,214 +432,206 @@ const taskForm = reactive({
is_active: true,
payload_config: '',
cron_expression: '0 20 * * *', // 新增:Crontab 表达式,默认每天 20:00
})
});
// Template create form
const templateTaskForm = reactive({
task_name: '',
thread_id: '',
field_values: {}
})
field_values: {},
});
const taskRules = {
name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
thread_id: [{ required: true, message: '请输入接龙 ID', trigger: 'blur' }],
}
};
// Compute visible fields from selected template (using merged config)
const visibleFields = computed(() => {
if (!templatePreview.value) return {}
if (!templatePreview.value) return {};
// 使用合并后的完整字段配置(包含从父模板继承的字段)
const fieldConfig = templatePreview.value.field_config
const visible = {}
const fieldConfig = templatePreview.value.field_config;
const visible = {};
// 递归函数:提取所有可见的普通字段
const extractVisibleFields = (config, parentPath = '') => {
for (const [key, value] of Object.entries(config)) {
const currentPath = parentPath ? `${parentPath}.${key}` : key
const currentPath = parentPath ? `${parentPath}.${key}` : key;
// 判断是否为字段配置对象(包含 display_name
if (value && typeof value === 'object' && 'display_name' in value) {
// 这是一个普通字段配置
if (!value.hidden) {
visible[currentPath] = value
visible[currentPath] = value;
}
}
// 判断是否为数组字段
else if (Array.isArray(value)) {
// 数组字段:遍历每个元素
if (value.length > 0) {
const firstElement = value[0]
const firstElement = value[0];
// 如果数组元素是字段配置对象,直接提取
if (firstElement && typeof firstElement === 'object' && 'display_name' in firstElement) {
if (!firstElement.hidden) {
visible[`${currentPath}[0]`] = firstElement
visible[`${currentPath}[0]`] = firstElement;
}
}
// 如果数组元素是对象(但不是字段配置),递归处理
else if (firstElement && typeof firstElement === 'object') {
extractVisibleFields(firstElement, `${currentPath}[0]`)
extractVisibleFields(firstElement, `${currentPath}[0]`);
}
}
}
// 判断是否为对象字段(不包含 display_name 的对象)
else if (value && typeof value === 'object' && !('display_name' in value)) {
// 递归处理对象字段
extractVisibleFields(value, currentPath)
extractVisibleFields(value, currentPath);
}
}
}
};
extractVisibleFields(fieldConfig)
extractVisibleFields(fieldConfig);
return visible
})
return visible;
});
// Formatted payload for display in edit mode
const formattedPayload = computed(() => {
if (!taskForm.payload_config) return '{}'
if (!taskForm.payload_config) return '{}';
try {
const payload = JSON.parse(taskForm.payload_config)
return JSON.stringify(payload, null, 2)
} catch (e) {
return taskForm.payload_config
const payload = JSON.parse(taskForm.payload_config);
return JSON.stringify(payload, null, 2);
} catch {
return taskForm.payload_config;
}
})
});
// Copy payload to clipboard
const copyPayload = async () => {
const success = await copyToClipboard(formattedPayload.value)
const success = await copyToClipboard(formattedPayload.value);
if (success) {
message.success('Payload 已复制到剪贴板')
message.success('Payload 已复制到剪贴板');
} else {
message.error('复制失败')
message.error('复制失败');
}
}
};
// Initialize field values with defaults when template is selected
watch(selectedTemplate, async (newTemplate) => {
watch(selectedTemplate, async newTemplate => {
if (!newTemplate) {
templatePreview.value = null
return
templatePreview.value = null;
return;
}
// 获取模板的合并后配置(包含父模板的字段)
try {
templatePreview.value = await templateStore.previewTemplate(newTemplate.id)
} catch (error) {
message.error('获取模板配置失败')
templatePreview.value = null
return
templatePreview.value = await templateStore.previewTemplate(newTemplate.id);
} catch {
message.error('获取模板配置失败');
templatePreview.value = null;
return;
}
const fieldConfig = templatePreview.value.field_config
const fieldValues = {}
const fieldConfig = templatePreview.value.field_config;
const fieldValues = {};
// 递归函数:提取所有字段的默认值
const extractDefaultValues = (config, parentPath = '') => {
for (const [key, value] of Object.entries(config)) {
const currentPath = parentPath ? `${parentPath}.${key}` : key
const currentPath = parentPath ? `${parentPath}.${key}` : key;
// 判断是否为字段配置对象(包含 display_name
if (value && typeof value === 'object' && 'display_name' in value) {
fieldValues[currentPath] = value.default_value || ''
fieldValues[currentPath] = value.default_value || '';
}
// 判断是否为数组字段
else if (Array.isArray(value)) {
// 数组字段:处理第一个元素的默认值
if (value.length > 0) {
const firstElement = value[0]
const firstElement = value[0];
// 如果数组元素是字段配置对象,直接提取默认值
if (firstElement && typeof firstElement === 'object' && 'display_name' in firstElement) {
fieldValues[`${currentPath}[0]`] = firstElement.default_value || ''
fieldValues[`${currentPath}[0]`] = firstElement.default_value || '';
}
// 如果数组元素是对象(但不是字段配置),递归处理
else if (firstElement && typeof firstElement === 'object') {
extractDefaultValues(firstElement, `${currentPath}[0]`)
extractDefaultValues(firstElement, `${currentPath}[0]`);
}
}
}
// 判断是否为对象字段(不包含 display_name 的对象)
else if (value && typeof value === 'object' && !('display_name' in value)) {
// 递归处理对象字段
extractDefaultValues(value, currentPath)
extractDefaultValues(value, currentPath);
}
}
}
};
extractDefaultValues(fieldConfig)
extractDefaultValues(fieldConfig);
templateTaskForm.field_values = fieldValues
})
templateTaskForm.field_values = fieldValues;
});
// Load templates
const loadTemplates = async () => {
loadingTemplates.value = true
loadingTemplates.value = true;
try {
activeTemplates.value = await templateStore.fetchActiveTemplates()
activeTemplates.value = await templateStore.fetchActiveTemplates();
} catch (error) {
message.error(error.message || '加载模板失败')
message.error(error.message || '加载模板失败');
} finally {
loadingTemplates.value = false
loadingTemplates.value = false;
}
}
};
// Select template
const selectTemplate = (template) => {
selectedTemplate.value = template
}
// Handle mode change
const handleModeChange = (mode) => {
selectedTemplate.value = null
templateTaskForm.task_name = ''
templateTaskForm.thread_id = ''
templateTaskForm.field_values = {}
}
const selectTemplate = template => {
selectedTemplate.value = template;
};
// 从 payload_config 中提取 ThreadId
const getThreadId = (task) => {
if (!task.payload_config) return '未知'
const getThreadId = task => {
if (!task.payload_config) return '未知';
try {
const payload = JSON.parse(task.payload_config)
return payload.ThreadId || '未知'
const payload = JSON.parse(task.payload_config);
return payload.ThreadId || '未知';
} catch (e) {
console.error('解析 payload_config 失败:', e)
return '未知'
console.error('解析 payload_config 失败:', e);
return '未知';
}
}
};
// 加载任务列表
const fetchTasks = async () => {
loading.value = true
loading.value = true;
try {
await taskStore.fetchMyTasks()
await taskStore.fetchMyTasks();
} catch (error) {
message.error(error.message || '加载任务列表失败')
message.error(error.message || '加载任务列表失败');
} finally {
loading.value = false
loading.value = false;
}
}
};
// 查看任务详情
const viewTask = (task) => {
router.push(`/tasks/${task.id}/records`)
}
const viewTask = task => {
router.push(`/tasks/${task.id}/records`);
};
// 编辑任务
const editTask = (task) => {
editingTask.value = task
const editTask = task => {
editingTask.value = task;
// 从 payload_config 中提取 thread_id
let threadId = ''
let threadId = '';
try {
const payload = JSON.parse(task.payload_config || '{}')
threadId = payload.ThreadId || ''
const payload = JSON.parse(task.payload_config || '{}');
threadId = payload.ThreadId || '';
} catch (e) {
console.error('解析 payload_config 失败:', e)
console.error('解析 payload_config 失败:', e);
}
Object.assign(taskForm, {
@@ -622,12 +640,12 @@ const editTask = (task) => {
is_active: task.is_active,
payload_config: task.payload_config || '{}',
cron_expression: task.cron_expression || '0 20 * * *',
})
showCreateDialog.value = true
}
});
showCreateDialog.value = true;
};
// 删除任务
const deleteTask = (task) => {
const deleteTask = task => {
Modal.confirm({
title: '删除确认',
content: `确定要删除任务"${task.name || task.id}"吗?此操作不可恢复。`,
@@ -636,112 +654,111 @@ const deleteTask = (task) => {
okType: 'danger',
onOk: async () => {
try {
await taskStore.deleteTask(task.id)
message.success('任务删除成功')
await fetchTasks()
await taskStore.deleteTask(task.id);
message.success('任务删除成功');
await fetchTasks();
} catch (error) {
message.error(error.message || '删除任务失败')
message.error(error.message || '删除任务失败');
}
},
})
}
});
};
// 切换任务状态
const toggleTaskStatus = async (task) => {
const toggleTaskStatus = async task => {
try {
await taskStore.toggleTask(task.id)
message.success(task.is_active ? '任务已禁用' : '任务已启用')
await taskStore.toggleTask(task.id);
message.success(task.is_active ? '任务已禁用' : '任务已启用');
} catch (error) {
message.error(error.message || '切换任务状态失败')
message.error(error.message || '切换任务状态失败');
}
}
};
// 手动打卡 (异步轮询方式)
const handleCheckIn = async (taskId) => {
checkInLoading.value[taskId] = true
const handleCheckIn = async taskId => {
checkInLoading.value[taskId] = true;
try {
// 调用异步打卡接口,立即返回 record_id
const result = await taskStore.checkInTask(taskId)
const result = await taskStore.checkInTask(taskId);
// 获取 record_id
const recordId = result.record_id
const recordId = result.record_id;
if (!recordId) {
message.error('打卡请求失败:未获取到记录ID')
checkInLoading.value[taskId] = false
return
message.error('打卡请求失败:未获取到记录ID');
checkInLoading.value[taskId] = false;
return;
}
// 如果初始状态就是失败,显示错误并刷新任务列表
if (result.status === 'failure') {
message.error(result.message || '打卡失败')
checkInLoading.value[taskId] = false
await fetchTasks()
return
message.error(result.message || '打卡失败');
checkInLoading.value[taskId] = false;
await fetchTasks();
return;
}
// 显示提示消息
message.info('打卡任务已启动,正在后台处理...')
message.info('打卡任务已启动,正在后台处理...');
// 使用轮询 composable 检查打卡状态
startPolling(
async () => {
const status = await taskStore.getCheckInRecordStatus(recordId)
const status = await taskStore.getCheckInRecordStatus(recordId);
return {
completed: status.status !== 'pending',
success: status.status === 'success',
data: status
}
data: status,
};
},
{
onSuccess: async () => {
checkInLoading.value[taskId] = false
message.success('打卡成功!')
await fetchTasks()
checkInLoading.value[taskId] = false;
message.success('打卡成功!');
await fetchTasks();
},
onFailure: async (statusData) => {
checkInLoading.value[taskId] = false
const errorMsg = statusData.error_message || statusData.response_text || '打卡失败'
message.error(errorMsg)
await fetchTasks()
onFailure: async statusData => {
checkInLoading.value[taskId] = false;
const errorMsg = statusData.error_message || statusData.response_text || '打卡失败';
message.error(errorMsg);
await fetchTasks();
},
onTimeout: () => {
checkInLoading.value[taskId] = false
message.warning('打卡处理时间较长,请稍后查看打卡记录')
}
checkInLoading.value[taskId] = false;
message.warning('打卡处理时间较长,请稍后查看打卡记录');
},
}
)
);
} catch (error) {
console.error('启动打卡失败:', error)
checkInLoading.value[taskId] = false
message.error(error.message || '启动打卡任务失败')
console.error('启动打卡失败:', error);
checkInLoading.value[taskId] = false;
message.error(error.message || '启动打卡任务失败');
}
}
};
// 提交表单
const handleSubmit = async () => {
submitting.value = true
submitting.value = true;
try {
// Edit mode
if (editingTask.value) {
if (!taskFormRef.value) return
await taskFormRef.value.validate()
if (!taskFormRef.value) return;
await taskFormRef.value.validate();
await taskStore.updateTask(editingTask.value.id, taskForm)
message.success('任务更新成功')
await taskStore.updateTask(editingTask.value.id, taskForm);
message.success('任务更新成功');
}
// Create from template
else if (createMode.value === 'template') {
if (!selectedTemplate.value) {
message.warning('请选择一个模板')
return
message.warning('请选择一个模板');
return;
}
if (!templateTaskForm.thread_id) {
message.warning('请输入接龙 ID')
return
message.warning('请输入接龙 ID');
return;
}
await templateStore.createTaskFromTemplate(
@@ -749,59 +766,59 @@ const handleSubmit = async () => {
templateTaskForm.thread_id,
templateTaskForm.field_values,
templateTaskForm.task_name || null
)
);
message.success('任务创建成功')
message.success('任务创建成功');
}
// Create manually
else {
if (!taskFormRef.value) return
await taskFormRef.value.validate()
if (!taskFormRef.value) return;
await taskFormRef.value.validate();
await taskStore.createTask(taskForm)
message.success('任务创建成功')
await taskStore.createTask(taskForm);
message.success('任务创建成功');
}
showCreateDialog.value = false
resetForm()
await fetchTasks()
showCreateDialog.value = false;
resetForm();
await fetchTasks();
} catch (error) {
message.error(error.message || '操作失败')
message.error(error.message || '操作失败');
} finally {
submitting.value = false
submitting.value = false;
}
}
};
// 重置表单
const resetForm = () => {
editingTask.value = null
selectedTemplate.value = null
createMode.value = 'template'
editingTask.value = null;
selectedTemplate.value = null;
createMode.value = 'template';
Object.assign(taskForm, {
name: '',
thread_id: '',
is_active: true,
payload_config: '',
})
});
templateTaskForm.task_name = ''
templateTaskForm.thread_id = ''
templateTaskForm.field_values = {}
templateTaskForm.task_name = '';
templateTaskForm.thread_id = '';
templateTaskForm.field_values = {};
taskFormRef.value?.resetFields()
}
taskFormRef.value?.resetFields();
};
// Watch dialog open to load templates
watch(showCreateDialog, (isOpen) => {
watch(showCreateDialog, isOpen => {
if (isOpen && !editingTask.value) {
loadTemplates()
loadTemplates();
}
})
});
onMounted(() => {
fetchTasks()
})
fetchTasks();
});
</script>
<style scoped>
+23 -22
View File
@@ -48,43 +48,44 @@
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { FileTextOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import { useAdminStore } from '@/stores/admin'
import { formatDateTime } from '@/utils/helpers'
import { ref, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { FileTextOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useAdminStore } from '@/stores/admin';
import { formatDateTime } from '@/utils/helpers';
const adminStore = useAdminStore()
const adminStore = useAdminStore();
const logContent = ref('')
const lastUpdate = ref('')
const logContent = ref('');
const lastUpdate = ref('');
const logLines = computed(() => {
if (!logContent.value) return 0
const content = typeof logContent.value === 'string' ? logContent.value : String(logContent.value)
return content.split('\n').length
})
if (!logContent.value) return 0;
const content =
typeof logContent.value === 'string' ? logContent.value : String(logContent.value);
return content.split('\n').length;
});
const handleRefresh = async () => {
try {
const data = await adminStore.fetchLogs({ lines: 200 })
const data = await adminStore.fetchLogs({ lines: 200 });
if (data.logs) {
// 确保是字符串
logContent.value = typeof data.logs === 'string' ? data.logs : String(data.logs)
lastUpdate.value = formatDateTime(new Date())
message.success('刷新成功')
logContent.value = typeof data.logs === 'string' ? data.logs : String(data.logs);
lastUpdate.value = formatDateTime(new Date());
message.success('刷新成功');
} else {
logContent.value = '无日志内容'
logContent.value = '无日志内容';
}
} catch (error) {
message.error(error.message || '刷新失败')
message.error(error.message || '刷新失败');
}
}
};
onMounted(() => {
handleRefresh()
})
handleRefresh();
});
</script>
<style scoped>
+57 -35
View File
@@ -18,7 +18,7 @@
<!-- Desktop table -->
<a-table
v-if="!isMobile"
:dataSource="checkInStore.allRecords"
:data-source="checkInStore.allRecords"
:columns="columns"
:loading="checkInStore.loading"
:pagination="false"
@@ -32,7 +32,9 @@
</template>
<template v-else-if="column.key === 'status'">
<a-tag v-if="record.status === 'success'" color="success">✅ 打卡成功</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default">🕐 时间范围外</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default"
>🕐 时间范围外</a-tag
>
<a-tag v-else-if="record.status === 'unknown'" color="warning">❗ 打卡异常</a-tag>
<a-tag v-else color="error">❌ 打卡失败</a-tag>
</template>
@@ -47,17 +49,32 @@
<!-- Mobile card view -->
<a-space v-else direction="vertical" :size="16" style="width: 100%">
<a-card v-for="record in checkInStore.allRecords" :key="record.id" size="small" :loading="checkInStore.loading">
<a-card
v-for="record in checkInStore.allRecords"
:key="record.id"
size="small"
:loading="checkInStore.loading"
>
<a-descriptions :column="1" size="small" bordered>
<a-descriptions-item label="ID">{{ record.id }}</a-descriptions-item>
<a-descriptions-item label="用户ID">{{ record.user_id }}</a-descriptions-item>
<a-descriptions-item label="用户邮箱">{{ record.user_email || '-' }}</a-descriptions-item>
<a-descriptions-item label="任务名称">{{ record.task_name || '-' }}</a-descriptions-item>
<a-descriptions-item label="接龙ID">{{ record.thread_id || '-' }}</a-descriptions-item>
<a-descriptions-item label="打卡时间">{{ formatDateTime(record.check_in_time) }}</a-descriptions-item>
<a-descriptions-item label="用户邮箱">{{
record.user_email || '-'
}}</a-descriptions-item>
<a-descriptions-item label="任务名称">{{
record.task_name || '-'
}}</a-descriptions-item>
<a-descriptions-item label="接龙ID">{{
record.thread_id || '-'
}}</a-descriptions-item>
<a-descriptions-item label="打卡时间">{{
formatDateTime(record.check_in_time)
}}</a-descriptions-item>
<a-descriptions-item label="状态">
<a-tag v-if="record.status === 'success'" color="success">✅ 打卡成功</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default">🕐 时间范围外</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default"
>🕐 时间范围外</a-tag
>
<a-tag v-else-if="record.status === 'unknown'" color="warning">❗ 打卡异常</a-tag>
<a-tag v-else color="error">❌ 打卡失败</a-tag>
</a-descriptions-item>
@@ -67,26 +84,31 @@
<a-tag v-else-if="record.trigger_type === 'admin'" color="orange">管理员</a-tag>
<a-tag v-else>{{ record.trigger_type }}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="消息">{{ record.response_text || '-' }}</a-descriptions-item>
<a-descriptions-item label="消息">{{
record.response_text || '-'
}}</a-descriptions-item>
</a-descriptions>
</a-card>
</a-space>
<!-- Empty state -->
<a-empty v-if="!checkInStore.loading && checkInStore.allRecords.length === 0" description="暂无打卡记录" />
<a-empty
v-if="!checkInStore.loading && checkInStore.allRecords.length === 0"
description="暂无打卡记录"
/>
<!-- Pagination -->
<div class="pagination-container" v-if="checkInStore.total > 0">
<div v-if="checkInStore.total > 0" class="pagination-container">
<a-pagination
v-model:current="checkInStore.currentPage"
v-model:pageSize="checkInStore.pageSize"
v-model:page-size="checkInStore.pageSize"
:total="checkInStore.total"
:pageSizeOptions="['10', '20', '50', '100']"
:page-size-options="['10', '20', '50', '100']"
show-size-changer
show-quick-jumper
:show-total="total => `${total} 条记录`"
@change="handlePageChange"
@showSizeChange="handleSizeChange"
@show-size-change="handleSizeChange"
/>
</div>
</a-card>
@@ -95,16 +117,16 @@
</template>
<script setup>
import { onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UnorderedListOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import { useCheckInStore } from '@/stores/checkIn'
import { useBreakpoint } from '@/composables/useBreakpoint'
import { formatDateTime } from '@/utils/helpers'
import { onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { UnorderedListOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useCheckInStore } from '@/stores/checkIn';
import { useBreakpoint } from '@/composables/useBreakpoint';
import { formatDateTime } from '@/utils/helpers';
const checkInStore = useCheckInStore()
const { isMobile } = useBreakpoint()
const checkInStore = useCheckInStore();
const { isMobile } = useBreakpoint();
// Table columns configuration
const columns = [
@@ -117,29 +139,29 @@ const columns = [
{ title: '状态', dataIndex: 'status', key: 'status', width: 120 },
{ title: '触发方式', dataIndex: 'trigger_type', key: 'trigger_type', width: 120 },
{ title: '消息', dataIndex: 'response_text', key: 'response_text', ellipsis: true },
]
];
const handleRefresh = async () => {
try {
await checkInStore.fetchAllRecords()
message.success('刷新成功')
await checkInStore.fetchAllRecords();
message.success('刷新成功');
} catch (error) {
message.error(error.message || '刷新失败')
message.error(error.message || '刷新失败');
}
}
};
const handlePageChange = () => {
checkInStore.fetchAllRecords()
}
checkInStore.fetchAllRecords();
};
const handleSizeChange = () => {
checkInStore.currentPage = 1
checkInStore.fetchAllRecords()
}
checkInStore.currentPage = 1;
checkInStore.fetchAllRecords();
};
onMounted(() => {
checkInStore.fetchAllRecords()
})
checkInStore.fetchAllRecords();
});
</script>
<style scoped>
+38 -36
View File
@@ -22,10 +22,7 @@
<div v-else-if="adminStore.stats" class="stats-content">
<a-row :gutter="[20, 20]">
<a-col :xs="24" :sm="12" :md="6">
<a-statistic
title="总用户数"
:value="adminStore.totalUsers"
>
<a-statistic title="总用户数" :value="adminStore.totalUsers">
<template #prefix>
<UserOutlined />
</template>
@@ -43,10 +40,7 @@
</a-statistic>
</a-col>
<a-col :xs="24" :sm="12" :md="6">
<a-statistic
title="总打卡次数"
:value="adminStore.totalRecords"
>
<a-statistic title="总打卡次数" :value="adminStore.totalRecords">
<template #prefix>
<UnorderedListOutlined />
</template>
@@ -75,16 +69,24 @@
{{ adminStore.stats?.users?.regular || 0 }}
</a-descriptions-item>
<a-descriptions-item label="今日成功打卡">
<a-tag color="success">{{ adminStore.stats?.check_in_records?.today_success || 0 }}</a-tag>
<a-tag color="success">{{
adminStore.stats?.check_in_records?.today_success || 0
}}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="今日失败打卡">
<a-tag color="error">{{ adminStore.stats?.check_in_records?.today_failure || 0 }}</a-tag>
<a-tag color="error">{{
adminStore.stats?.check_in_records?.today_failure || 0
}}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="今日时间范围外">
<a-tag color="default">{{ adminStore.stats?.check_in_records?.today_out_of_time || 0 }}</a-tag>
<a-tag color="default">{{
adminStore.stats?.check_in_records?.today_out_of_time || 0
}}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="今日异常打卡">
<a-tag color="warning">{{ adminStore.stats?.check_in_records?.today_unknown || 0 }}</a-tag>
<a-tag color="warning">{{
adminStore.stats?.check_in_records?.today_unknown || 0
}}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="总成功率" :span="2">
<a-progress
@@ -102,8 +104,8 @@
</template>
<script setup>
import { onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
BarChartOutlined,
ReloadOutlined,
@@ -111,45 +113,45 @@ import {
CheckOutlined,
UnorderedListOutlined,
CalendarOutlined,
} from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import { useAdminStore } from '@/stores/admin'
} from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useAdminStore } from '@/stores/admin';
const adminStore = useAdminStore()
const adminStore = useAdminStore();
const getProgressColor = (percentage) => {
if (percentage >= 90) return '#52c41a'
if (percentage >= 70) return '#faad14'
return '#ff4d4f'
}
const getProgressColor = percentage => {
if (percentage >= 90) return '#52c41a';
if (percentage >= 70) return '#faad14';
return '#ff4d4f';
};
const calculateSuccessRate = () => {
const total = adminStore.stats?.check_in_records?.total || 0
const todaySuccess = adminStore.stats?.check_in_records?.today_success || 0
const total = adminStore.stats?.check_in_records?.total || 0;
const todaySuccess = adminStore.stats?.check_in_records?.today_success || 0;
if (total === 0) return 0
if (total === 0) return 0;
// Calculate success rate based on all records (not just today)
// We need to get success count from backend or calculate differently
// For now, use today's success rate as approximation
const todayTotal = adminStore.stats?.check_in_records?.today || 0
if (todayTotal === 0) return 0
const todayTotal = adminStore.stats?.check_in_records?.today || 0;
if (todayTotal === 0) return 0;
return Math.round((todaySuccess / todayTotal) * 100)
}
return Math.round((todaySuccess / todayTotal) * 100);
};
const handleRefresh = async () => {
try {
await adminStore.fetchStats()
message.success('刷新成功')
await adminStore.fetchStats();
message.success('刷新成功');
} catch (error) {
message.error(error.message || '刷新失败')
message.error(error.message || '刷新失败');
}
}
};
onMounted(() => {
adminStore.fetchStats()
})
adminStore.fetchStats();
});
</script>
<style scoped>
+341 -220
View File
@@ -9,9 +9,14 @@
<h1 class="text-3xl font-bold text-gradient mb-2">任务模板管理</h1>
<p class="text-on-surface-variant">JSON 映射架构 - 配置即结构</p>
</div>
<button @click="showCreateDialog" class="md3-button-filled">
<button class="md3-button-filled" @click="showCreateDialog">
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 4v16m8-8H4"
/>
</svg>
新建模板
</button>
@@ -25,13 +30,27 @@
</a-card>
</div>
<a-card v-else-if="templates.length === 0" class="md3-card text-center" style="padding: 48px 20px;">
<svg class="w-20 h-20 mx-auto text-on-surface-variant opacity-30 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
<a-card
v-else-if="templates.length === 0"
class="md3-card text-center"
style="padding: 48px 20px"
>
<svg
class="w-20 h-20 mx-auto text-on-surface-variant opacity-30 mb-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
<h3 class="text-xl font-semibold text-on-surface mb-2">暂无模板</h3>
<p class="text-on-surface-variant mb-4">创建第一个模板让用户更轻松地创建打卡任务</p>
<button @click="showCreateDialog" class="md3-button-filled">新建模板</button>
<button class="md3-button-filled" @click="showCreateDialog">新建模板</button>
</a-card>
<div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
@@ -43,8 +62,10 @@
<div class="flex items-start justify-between mb-3">
<div class="flex-1">
<h3 class="text-lg font-semibold text-on-surface mb-2">{{ template.name }}</h3>
<a-divider style="margin: 8px 0;" />
<p class="text-sm text-on-surface-variant mb-2">{{ template.description || '无描述' }}</p>
<a-divider style="margin: 8px 0" />
<p class="text-sm text-on-surface-variant mb-2">
{{ template.description || '无描述' }}
</p>
<span :class="template.is_active ? 'md3-badge-success' : 'md3-badge-info'">
{{ template.is_active ? '已启用' : '已禁用' }}
</span>
@@ -55,19 +76,50 @@
<!-- 第一行预览在左半部分居中编辑在右半部分居中 -->
<div class="grid grid-cols-2 gap-2">
<div class="flex justify-center">
<button @click="previewTemplate(template)" class="md3-button-outlined text-sm flex-shrink-0">
<svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
<button
class="md3-button-outlined text-sm flex-shrink-0"
@click="previewTemplate(template)"
>
<svg
class="w-4 h-4 mr-1.5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
/>
</svg>
预览
</button>
</div>
<div class="flex justify-center">
<button @click="editTemplate(template)" class="md3-button-outlined text-sm flex-shrink-0">
<svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
<button
class="md3-button-outlined text-sm flex-shrink-0"
@click="editTemplate(template)"
>
<svg
class="w-4 h-4 mr-1.5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
/>
</svg>
编辑
</button>
@@ -78,9 +130,22 @@
<div class="grid grid-cols-2 gap-2">
<div></div>
<div class="flex justify-center">
<button @click="deleteTemplate(template)" class="md3-button-outlined text-sm !text-red-600 dark:!text-red-500 !border-red-600 dark:!border-red-500 hover:!bg-red-50 dark:hover:!bg-red-900/20 flex-shrink-0">
<svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
<button
class="md3-button-outlined text-sm !text-red-600 dark:!text-red-500 !border-red-600 dark:!border-red-500 hover:!bg-red-50 dark:hover:!bg-red-900/20 flex-shrink-0"
@click="deleteTemplate(template)"
>
<svg
class="w-4 h-4 mr-1.5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
删除
</button>
@@ -96,16 +161,25 @@
:title="dialogMode === 'create' ? '新建模板' : '编辑模板'"
:width="dialogWidth"
:style="isMobile ? { top: 0, maxWidth: '100vw' } : {}"
:maskClosable="false"
:mask-closable="false"
class="template-editor-modal"
>
<a-form :model="formData" layout="vertical" ref="formRef">
<a-form ref="formRef" :model="formData" layout="vertical">
<a-form-item label="模板名称" required>
<a-input v-model:value="formData.name" placeholder="请输入模板名称" :maxlength="100" show-count />
<a-input
v-model:value="formData.name"
placeholder="请输入模板名称"
:maxlength="100"
show-count
/>
</a-form-item>
<a-form-item label="模板描述">
<a-textarea v-model:value="formData.description" :rows="2" placeholder="请输入模板描述" />
<a-textarea
v-model:value="formData.description"
:rows="2"
placeholder="请输入模板描述"
/>
</a-form-item>
<a-form-item label="父模板">
@@ -145,12 +219,8 @@
<p class="text-sm mb-2">
<strong>配置即结构</strong>模板配置完全映射到生成的 Payload 结构
</p>
<p class="text-sm mb-2">
<strong>字段名保持原样</strong>不进行任何大小写转换
</p>
<p class="text-sm">
<strong>ThreadId</strong> 由用户填写无需在模板中配置
</p>
<p class="text-sm mb-2"><strong>字段名保持原样</strong>不进行任何大小写转换</p>
<p class="text-sm"><strong>ThreadId</strong> 由用户填写无需在模板中配置</p>
</template>
</a-alert>
@@ -166,20 +236,50 @@
<template #overlay>
<a-menu @click="handleAddField">
<a-menu-item key="field">
<svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
<svg
class="w-4 h-4 inline mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"
/>
</svg>
普通字段
</a-menu-item>
<a-menu-item key="array">
<svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16" />
<svg
class="w-4 h-4 inline mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 6h16M4 10h16M4 14h16M4 18h16"
/>
</svg>
数组字段
</a-menu-item>
<a-menu-item key="object">
<svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
<svg
class="w-4 h-4 inline mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
对象字段
</a-menu-item>
@@ -189,9 +289,22 @@
</div>
<!-- 递归渲染字段树 -->
<div v-if="Object.keys(formData.field_config).length === 0" class="text-center py-12 border-2 border-dashed border-outline-variant rounded-lg bg-surface-container">
<svg class="w-16 h-16 mx-auto text-on-surface-variant opacity-40 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
<div
v-if="Object.keys(formData.field_config).length === 0"
class="text-center py-12 border-2 border-dashed border-outline-variant rounded-lg bg-surface-container"
>
<svg
class="w-16 h-16 mx-auto text-on-surface-variant opacity-40 mb-3"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
<h3 class="text-lg font-semibold text-on-surface mb-2">暂无字段配置</h3>
<p class="text-sm text-on-surface-variant">点击上方"添加字段"开始配置模板</p>
@@ -204,9 +317,9 @@
:field-key="key"
:field-config="config"
:path="[key]"
@update="(event) => updateField(event.path, event.value)"
@delete="(path) => deleteField(path)"
@move="(event) => moveField(event.path, event.direction)"
@update="event => updateField(event.path, event.value)"
@delete="path => deleteField(path)"
@move="event => moveField(event.path, event.direction)"
/>
</div>
</div>
@@ -216,14 +329,16 @@
<span class="text-lg font-bold">JSON 预览</span>
</a-divider>
<div class="bg-surface-container text-green-400 p-4 rounded-lg font-mono text-sm overflow-auto max-h-96">
<div
class="bg-surface-container text-green-400 p-4 rounded-lg font-mono text-sm overflow-auto max-h-96"
>
<pre>{{ JSON.stringify(formData.field_config, null, 2) }}</pre>
</div>
</a-form>
<template #footer>
<a-button @click="dialogVisible = false">取消</a-button>
<a-button type="primary" @click="handleSubmit" :loading="submitting">
<a-button type="primary" :loading="submitting" @click="handleSubmit">
{{ dialogMode === 'create' ? '创建' : '更新' }}
</a-button>
</template>
@@ -265,12 +380,18 @@
<div v-if="previewData" class="space-y-4">
<div class="bg-surface-container rounded p-4">
<h4 class="font-semibold mb-2 text-on-surface">生成的 Payload使用默认值</h4>
<pre class="text-xs bg-surface text-on-surface p-3 rounded border border-outline-variant overflow-auto max-h-96">{{ JSON.stringify(previewData.preview_payload, null, 2) }}</pre>
<pre
class="text-xs bg-surface text-on-surface p-3 rounded border border-outline-variant overflow-auto max-h-96"
>{{ JSON.stringify(previewData.preview_payload, null, 2) }}</pre
>
</div>
<div class="bg-surface-container rounded p-4">
<h4 class="font-semibold mb-2 text-on-surface">字段配置</h4>
<pre class="text-xs bg-surface text-on-surface p-3 rounded border border-outline-variant overflow-auto max-h-96">{{ JSON.stringify(previewData.field_config, null, 2) }}</pre>
<pre
class="text-xs bg-surface text-on-surface p-3 rounded border border-outline-variant overflow-auto max-h-96"
>{{ JSON.stringify(previewData.field_config, null, 2) }}</pre
>
</div>
</div>
@@ -284,68 +405,68 @@
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { DownOutlined } from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import FieldTreeNode from '@/components/FieldTreeNode.vue'
import { useTemplateStore } from '@/stores/template'
import { useBreakpoint } from '@/composables/useBreakpoint'
import { ref, onMounted, computed } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { DownOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import FieldTreeNode from '@/components/FieldTreeNode.vue';
import { useTemplateStore } from '@/stores/template';
import { useBreakpoint } from '@/composables/useBreakpoint';
const templateStore = useTemplateStore()
const { isMobile, isTablet } = useBreakpoint()
const templateStore = useTemplateStore();
const { isMobile, isTablet } = useBreakpoint();
// 计算对话框宽度 - 响应式设计
const dialogWidth = computed(() => {
if (isMobile.value) return '100%'
if (isTablet.value) return 900
return 1200
})
if (isMobile.value) return '100%';
if (isTablet.value) return 900;
return 1200;
});
const previewDialogWidth = computed(() => {
if (isMobile.value) return '100%'
if (isTablet.value) return 800
return 1000
})
if (isMobile.value) return '100%';
if (isTablet.value) return 800;
return 1000;
});
const templates = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref('create')
const currentTemplateId = ref(null)
const submitting = ref(false)
const templates = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogMode = ref('create');
const currentTemplateId = ref(null);
const submitting = ref(false);
const previewDialogVisible = ref(false)
const previewData = ref(null)
const previewDialogVisible = ref(false);
const previewData = ref(null);
const addFieldDialogVisible = ref(false)
const newFieldName = ref('')
const newFieldType = ref('field')
const fieldConfigVersion = ref(0) // 用于强制刷新字段列表
const addFieldDialogVisible = ref(false);
const newFieldName = ref('');
const newFieldType = ref('field');
const fieldConfigVersion = ref(0); // 用于强制刷新字段列表
const formData = ref({
name: '',
description: '',
parent_id: null,
is_active: true,
field_config: {}
})
field_config: {},
});
const availableParentTemplates = computed(() => {
if (dialogMode.value === 'create') {
return templates.value
return templates.value;
}
return templates.value.filter(t => t.id !== currentTemplateId.value)
})
return templates.value.filter(t => t.id !== currentTemplateId.value);
});
const fieldTypeLabel = computed(() => {
const labels = {
field: '普通字段',
array: '数组字段',
object: '对象字段'
}
return labels[newFieldType.value] || '字段'
})
object: '对象字段',
};
return labels[newFieldType.value] || '字段';
});
function createDefaultFieldConfig() {
return {
@@ -356,85 +477,85 @@ function createDefaultFieldConfig() {
hidden: false,
placeholder: '',
value_type: 'string',
options: []
}
options: [],
};
}
const fetchTemplates = async () => {
loading.value = true
loading.value = true;
try {
templates.value = await templateStore.fetchTemplates()
templates.value = await templateStore.fetchTemplates();
} catch (error) {
message.error(error.message || '获取模板列表失败')
message.error(error.message || '获取模板列表失败');
} finally {
loading.value = false
loading.value = false;
}
}
};
const showCreateDialog = () => {
dialogMode.value = 'create'
currentTemplateId.value = null
dialogMode.value = 'create';
currentTemplateId.value = null;
formData.value = {
name: '',
description: '',
parent_id: null,
is_active: true,
field_config: {}
}
dialogVisible.value = true
}
field_config: {},
};
dialogVisible.value = true;
};
const editTemplate = (template) => {
dialogMode.value = 'edit'
currentTemplateId.value = template.id
const editTemplate = template => {
dialogMode.value = 'edit';
currentTemplateId.value = template.id;
const fieldConfig = JSON.parse(template.field_config)
const fieldConfig = JSON.parse(template.field_config);
formData.value = {
name: template.name,
description: template.description || '',
parent_id: template.parent_id || null,
is_active: template.is_active,
field_config: fieldConfig
}
field_config: fieldConfig,
};
dialogVisible.value = true
}
dialogVisible.value = true;
};
const handleSubmit = async () => {
if (!formData.value.name) {
message.warning('请输入模板名称')
return
message.warning('请输入模板名称');
return;
}
submitting.value = true
submitting.value = true;
try {
const templateData = {
name: formData.value.name,
description: formData.value.description,
parent_id: formData.value.parent_id,
is_active: formData.value.is_active,
field_config: JSON.stringify(formData.value.field_config)
}
field_config: JSON.stringify(formData.value.field_config),
};
if (dialogMode.value === 'create') {
await templateStore.createTemplate(templateData)
message.success('模板创建成功')
await templateStore.createTemplate(templateData);
message.success('模板创建成功');
} else {
await templateStore.updateTemplate(currentTemplateId.value, templateData)
message.success('模板更新成功')
await templateStore.updateTemplate(currentTemplateId.value, templateData);
message.success('模板更新成功');
}
dialogVisible.value = false
await fetchTemplates()
dialogVisible.value = false;
await fetchTemplates();
} catch (error) {
message.error(error.message || '操作失败')
message.error(error.message || '操作失败');
} finally {
submitting.value = false
submitting.value = false;
}
}
};
const deleteTemplate = (template) => {
const deleteTemplate = template => {
Modal.confirm({
title: '确认删除',
content: `确定要删除模板"${template.name}"吗?此操作不可撤销。`,
@@ -443,224 +564,224 @@ const deleteTemplate = (template) => {
okType: 'danger',
onOk: async () => {
try {
await templateStore.deleteTemplate(template.id)
message.success('模板删除成功')
await fetchTemplates()
await templateStore.deleteTemplate(template.id);
message.success('模板删除成功');
await fetchTemplates();
} catch (error) {
message.error(error.message || '删除失败')
message.error(error.message || '删除失败');
}
},
})
}
});
};
const previewTemplate = async (template) => {
const previewTemplate = async template => {
try {
previewData.value = await templateStore.previewTemplate(template.id)
previewDialogVisible.value = true
previewData.value = await templateStore.previewTemplate(template.id);
previewDialogVisible.value = true;
} catch (error) {
message.error(error.message || '预览失败')
message.error(error.message || '预览失败');
}
}
};
const handleAddField = ({ key }) => {
newFieldType.value = key
newFieldName.value = ''
addFieldDialogVisible.value = true
}
newFieldType.value = key;
newFieldName.value = '';
addFieldDialogVisible.value = true;
};
const confirmAddField = () => {
if (!newFieldName.value) {
message.warning('请输入字段名')
return
message.warning('请输入字段名');
return;
}
if (formData.value.field_config[newFieldName.value]) {
message.warning('该字段已存在')
return
message.warning('该字段已存在');
return;
}
// 创建一个新对象,确保新字段被添加到末尾
const newConfig = { ...formData.value.field_config }
const newConfig = { ...formData.value.field_config };
// 创建对应类型的字段
if (newFieldType.value === 'field') {
newConfig[newFieldName.value] = createDefaultFieldConfig()
newConfig[newFieldName.value] = createDefaultFieldConfig();
} else if (newFieldType.value === 'array') {
newConfig[newFieldName.value] = []
newConfig[newFieldName.value] = [];
} else if (newFieldType.value === 'object') {
newConfig[newFieldName.value] = {}
newConfig[newFieldName.value] = {};
}
// 替换整个 field_config 以确保顺序和响应性
formData.value.field_config = newConfig
fieldConfigVersion.value++ // 强制刷新
formData.value.field_config = newConfig;
fieldConfigVersion.value++; // 强制刷新
addFieldDialogVisible.value = false
message.success('字段添加成功')
}
addFieldDialogVisible.value = false;
message.success('字段添加成功');
};
const updateField = (path, newValue) => {
// 通过路径更新嵌套字段
let target = formData.value.field_config
let target = formData.value.field_config;
for (let i = 0; i < path.length - 1; i++) {
target = target[path[i]]
target = target[path[i]];
}
target[path[path.length - 1]] = newValue
}
target[path[path.length - 1]] = newValue;
};
const deleteField = (path) => {
const deleteField = path => {
// 通过路径删除嵌套字段
if (!path || path.length === 0) return
if (!path || path.length === 0) return;
// 创建一个新的 field_config 副本以触发响应性
const newConfig = JSON.parse(JSON.stringify(formData.value.field_config))
let target = newConfig
const newConfig = JSON.parse(JSON.stringify(formData.value.field_config));
let target = newConfig;
// 导航到父对象/数组
for (let i = 0; i < path.length - 1; i++) {
if (!target || typeof target !== 'object') {
console.error('❌ 删除失败:路径无效', path, 'at index', i)
return
console.error('❌ 删除失败:路径无效', path, 'at index', i);
return;
}
target = target[path[i]]
target = target[path[i]];
}
if (!target || typeof target !== 'object') {
console.error('❌ 删除失败:父对象不存在', path)
return
console.error('❌ 删除失败:父对象不存在', path);
return;
}
const lastKey = path[path.length - 1]
const lastKey = path[path.length - 1];
// 如果父容器是数组,使用 splice;如果是对象,使用 delete
if (Array.isArray(target)) {
target.splice(lastKey, 1)
target.splice(lastKey, 1);
} else {
delete target[lastKey]
delete target[lastKey];
}
// 替换整个 field_config 以触发 Vue 响应性
formData.value.field_config = newConfig
fieldConfigVersion.value++ // 强制刷新
}
formData.value.field_config = newConfig;
fieldConfigVersion.value++; // 强制刷新
};
const moveField = (path, direction) => {
// 通过路径移动字段
if (!path || path.length === 0) return
if (!path || path.length === 0) return;
// 如果是根级别字段,直接重建整个 field_config
if (path.length === 1) {
const fieldKey = path[0]
const keys = Object.keys(formData.value.field_config)
const currentIndex = keys.indexOf(fieldKey)
const fieldKey = path[0];
const keys = Object.keys(formData.value.field_config);
const currentIndex = keys.indexOf(fieldKey);
if (currentIndex === -1) {
console.error('❌ 字段不存在:', fieldKey)
return
console.error('❌ 字段不存在:', fieldKey);
return;
}
let targetIndex = currentIndex
let targetIndex = currentIndex;
if (direction === 'up' && currentIndex > 0) {
targetIndex = currentIndex - 1
targetIndex = currentIndex - 1;
} else if (direction === 'down' && currentIndex < keys.length - 1) {
targetIndex = currentIndex + 1
targetIndex = currentIndex + 1;
} else {
return
return;
}
// 交换键的位置
const temp = keys[currentIndex]
keys[currentIndex] = keys[targetIndex]
keys[targetIndex] = temp
const temp = keys[currentIndex];
keys[currentIndex] = keys[targetIndex];
keys[targetIndex] = temp;
// 重建整个 field_config - 使用深拷贝确保完全新的对象
const newConfig = {}
const newConfig = {};
keys.forEach(key => {
// 深拷贝每个字段配置
newConfig[key] = JSON.parse(JSON.stringify(formData.value.field_config[key]))
})
newConfig[key] = JSON.parse(JSON.stringify(formData.value.field_config[key]));
});
// 替换整个 formData,而不只是 field_config
formData.value = {
...formData.value,
field_config: newConfig
}
fieldConfigVersion.value++
return
field_config: newConfig,
};
fieldConfigVersion.value++;
return;
}
// 嵌套字段的情况(保留原有逻辑)
const newConfig = JSON.parse(JSON.stringify(formData.value.field_config))
const newConfig = JSON.parse(JSON.stringify(formData.value.field_config));
// 导航到目标的父容器
let parent = newConfig
let parent = newConfig;
for (let i = 0; i < path.length - 1; i++) {
parent = parent[path[i]]
parent = parent[path[i]];
if (!parent) {
console.error('❌ 路径无效:', path)
return
console.error('❌ 路径无效:', path);
return;
}
}
const fieldKey = path[path.length - 1]
const fieldKey = path[path.length - 1];
if (Array.isArray(parent)) {
// 数组情况:直接交换元素
const index = Number(fieldKey)
const index = Number(fieldKey);
if (direction === 'up' && index > 0) {
const temp = parent[index]
parent[index] = parent[index - 1]
parent[index - 1] = temp
const temp = parent[index];
parent[index] = parent[index - 1];
parent[index - 1] = temp;
} else if (direction === 'down' && index < parent.length - 1) {
const temp = parent[index]
parent[index] = parent[index + 1]
parent[index + 1] = temp
const temp = parent[index];
parent[index] = parent[index + 1];
parent[index + 1] = temp;
} else {
return
return;
}
} else {
// 对象情况:重建对象以改变键顺序
const keys = Object.keys(parent)
const currentIndex = keys.indexOf(fieldKey)
const keys = Object.keys(parent);
const currentIndex = keys.indexOf(fieldKey);
if (currentIndex === -1) {
console.error('❌ 字段不存在:', fieldKey)
return
console.error('❌ 字段不存在:', fieldKey);
return;
}
let targetIndex = currentIndex
let targetIndex = currentIndex;
if (direction === 'up' && currentIndex > 0) {
targetIndex = currentIndex - 1
targetIndex = currentIndex - 1;
} else if (direction === 'down' && currentIndex < keys.length - 1) {
targetIndex = currentIndex + 1
targetIndex = currentIndex + 1;
} else {
return
return;
}
// 交换键数组中的位置
const temp = keys[currentIndex]
keys[currentIndex] = keys[targetIndex]
keys[targetIndex] = temp
const temp = keys[currentIndex];
keys[currentIndex] = keys[targetIndex];
keys[targetIndex] = temp;
// 重建父对象
const reorderedParent = {}
const reorderedParent = {};
keys.forEach(key => {
reorderedParent[key] = parent[key]
})
reorderedParent[key] = parent[key];
});
// 替换父容器的所有属性
Object.keys(parent).forEach(key => delete parent[key])
Object.assign(parent, reorderedParent)
Object.keys(parent).forEach(key => delete parent[key]);
Object.assign(parent, reorderedParent);
}
// 强制触发响应性更新
formData.value.field_config = newConfig
fieldConfigVersion.value++
}
formData.value.field_config = newConfig;
fieldConfigVersion.value++;
};
onMounted(() => {
fetchTemplates()
})
fetchTemplates();
});
</script>
<style scoped>
+158 -156
View File
@@ -22,13 +22,13 @@
</template>
<!-- Tab 切换 -->
<a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
<a-tabs v-model:active-key="activeTab" @change="handleTabChange">
<!-- 待审批用户 Tab -->
<a-tab-pane key="pending" tab="待审批用户">
<!-- 桌面端表格 -->
<a-table
v-if="!isMobile"
:dataSource="pendingUsers"
:data-source="pendingUsers"
:columns="pendingColumns"
:loading="loading"
:row-key="record => record.id"
@@ -44,9 +44,7 @@
<a-button type="primary" size="small" @click="handleApprove(record)">
通过
</a-button>
<a-button danger size="small" @click="handleReject(record)">
拒绝
</a-button>
<a-button danger size="small" @click="handleReject(record)"> 拒绝 </a-button>
</a-space>
</template>
</template>
@@ -59,10 +57,14 @@
<a-descriptions-item label="ID">{{ user.id }}</a-descriptions-item>
<a-descriptions-item label="用户名">{{ user.alias }}</a-descriptions-item>
<a-descriptions-item label="邮箱">{{ user.email || '-' }}</a-descriptions-item>
<a-descriptions-item label="注册时间">{{ formatDateTime(user.created_at) }}</a-descriptions-item>
<a-descriptions-item label="注册时间">{{
formatDateTime(user.created_at)
}}</a-descriptions-item>
</a-descriptions>
<a-space class="mt-3" style="width: 100%">
<a-button type="primary" size="small" block @click="handleApprove(user)">通过</a-button>
<a-button type="primary" size="small" block @click="handleApprove(user)"
>通过</a-button
>
<a-button danger size="small" block @click="handleReject(user)">拒绝</a-button>
</a-space>
</a-card>
@@ -75,7 +77,7 @@
<!-- 桌面端表格 -->
<a-table
v-if="!isMobile"
:dataSource="userStore.users"
:data-source="userStore.users"
:columns="allColumns"
:loading="loading"
:row-key="record => record.id"
@@ -95,7 +97,11 @@
</a-tag>
</template>
<template v-else-if="column.key === 'jwt_exp'">
{{ record.jwt_exp && record.jwt_exp !== '0' ? formatDateTime(parseInt(record.jwt_exp) * 1000) : '-' }}
{{
record.jwt_exp && record.jwt_exp !== '0'
? formatDateTime(parseInt(record.jwt_exp) * 1000)
: '-'
}}
</template>
<template v-else-if="column.key === 'created_at'">
{{ formatDateTime(record.created_at) }}
@@ -105,9 +111,7 @@
<a-button type="primary" size="small" @click="handleEdit(record)">
编辑
</a-button>
<a-button danger size="small" @click="handleDelete(record)">
删除
</a-button>
<a-button danger size="small" @click="handleDelete(record)"> 删除 </a-button>
</a-space>
</template>
</template>
@@ -115,7 +119,12 @@
<!-- 移动端卡片视图 -->
<a-space v-else direction="vertical" :size="16" style="width: 100%">
<a-card v-for="user in userStore.users" :key="user.id" size="small" :loading="loading">
<a-card
v-for="user in userStore.users"
:key="user.id"
size="small"
:loading="loading"
>
<a-descriptions :column="1" size="small" bordered>
<a-descriptions-item label="ID">{{ user.id }}</a-descriptions-item>
<a-descriptions-item label="用户名">{{ user.alias }}</a-descriptions-item>
@@ -131,32 +140,38 @@
</a-tag>
</a-descriptions-item>
<a-descriptions-item label="Token过期">
{{ user.jwt_exp && user.jwt_exp !== '0' ? formatDateTime(parseInt(user.jwt_exp) * 1000) : '-' }}
{{
user.jwt_exp && user.jwt_exp !== '0'
? formatDateTime(parseInt(user.jwt_exp) * 1000)
: '-'
}}
</a-descriptions-item>
<a-descriptions-item label="创建时间">{{ formatDateTime(user.created_at) }}</a-descriptions-item>
<a-descriptions-item label="创建时间">{{
formatDateTime(user.created_at)
}}</a-descriptions-item>
</a-descriptions>
<a-space class="mt-3" style="width: 100%">
<a-button type="primary" size="small" block @click="handleEdit(user)">编辑</a-button>
<a-button type="primary" size="small" block @click="handleEdit(user)"
>编辑</a-button
>
<a-button danger size="small" block @click="handleDelete(user)">删除</a-button>
</a-space>
</a-card>
</a-space>
<!-- 批量操作 -->
<div class="batch-actions" v-if="selectedUsers.length > 0">
<div v-if="selectedUsers.length > 0" class="batch-actions">
<a-alert
:message="`已选择 ${selectedUsers.length} 个用户`"
type="info"
:closable="false"
>
<template #description>
<a-space style="margin-top: 10px;">
<a-space style="margin-top: 10px">
<a-button type="primary" size="small" @click="handleBatchApprove">
批量审批
</a-button>
<a-button danger size="small" @click="handleBatchDelete">
批量删除
</a-button>
<a-button danger size="small" @click="handleBatchDelete"> 批量删除 </a-button>
</a-space>
</template>
</a-alert>
@@ -167,17 +182,12 @@
<!-- 创建/编辑用户对话框 -->
<a-modal
:title="dialogMode === 'create' ? '创建用户' : '编辑用户'"
v-model:open="dialogVisible"
:title="dialogMode === 'create' ? '创建用户' : '编辑用户'"
:width="isMobile ? '100%' : 600"
:style="isMobile ? { top: 0, maxWidth: '100vw' } : {}"
>
<a-form
ref="formRef"
:model="formData"
:rules="formRules"
layout="vertical"
>
<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
<a-form-item label="用户名" name="alias">
<a-input v-model:value="formData.alias" placeholder="请输入用户名" />
</a-form-item>
@@ -203,14 +213,12 @@
v-model:value="formData.password"
:placeholder="dialogMode === 'create' ? '请输入密码' : '留空则不修改密码'"
/>
<span class="form-hint" v-if="dialogMode === 'edit'">
留空则不修改密码
</span>
<span v-if="dialogMode === 'edit'" class="form-hint"> 留空则不修改密码 </span>
</a-form-item>
<a-form-item label="重置密码" v-if="dialogMode === 'edit'">
<a-form-item v-if="dialogMode === 'edit'" label="重置密码">
<a-switch v-model:checked="formData.reset_password" />
<span class="form-hint-danger" v-if="formData.reset_password">
<span v-if="formData.reset_password" class="form-hint-danger">
⚠️ 将重置为默认密码
</span>
</a-form-item>
@@ -218,9 +226,7 @@
<template #footer>
<a-button @click="dialogVisible = false">取消</a-button>
<a-button type="primary" @click="handleSubmit" :loading="submitting">
确定
</a-button>
<a-button type="primary" :loading="submitting" @click="handleSubmit"> 确定 </a-button>
</template>
</a-modal>
</div>
@@ -228,31 +234,29 @@
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { UserOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import Layout from '@/components/Layout.vue'
import { useBreakpoint } from '@/composables/useBreakpoint'
import { useUserStore } from '@/stores/user'
import { useAdminStore } from '@/stores/admin'
import { adminAPI } from '@/api/index'
import { ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { UserOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useBreakpoint } from '@/composables/useBreakpoint';
import { useUserStore } from '@/stores/user';
import { adminAPI } from '@/api/index';
const userStore = useUserStore()
const adminStore = useAdminStore()
const { isMobile } = useBreakpoint()
const userStore = useUserStore();
const { isMobile } = useBreakpoint();
// 状态
const loading = ref(false)
const activeTab = ref('all') // 默认展示所有用户
const pendingUsers = ref([])
const selectedUsers = ref([])
const selectedRowKeys = ref([])
const dialogVisible = ref(false)
const dialogMode = ref('create')
const submitting = ref(false)
const loading = ref(false);
const activeTab = ref('all'); // 默认展示所有用户
const pendingUsers = ref([]);
const selectedUsers = ref([]);
const selectedRowKeys = ref([]);
const dialogVisible = ref(false);
const dialogMode = ref('create');
const submitting = ref(false);
// 表单
const formRef = ref(null)
const formRef = ref(null);
const formData = ref({
alias: '',
role: 'user',
@@ -260,7 +264,7 @@ const formData = ref({
email: '',
password: '',
reset_password: false,
})
});
// 表单验证规则
const formRules = {
@@ -269,15 +273,13 @@ const formRules = {
{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
],
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
email: [
{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
],
}
email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
};
// 时间格式化
const formatDateTime = (timestamp) => {
if (!timestamp) return '-'
const date = new Date(timestamp)
const formatDateTime = timestamp => {
if (!timestamp) return '-';
const date = new Date(timestamp);
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
@@ -285,8 +287,8 @@ const formatDateTime = (timestamp) => {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
}
});
};
// 待审批用户表格列
const pendingColumns = [
@@ -295,7 +297,7 @@ const pendingColumns = [
{ title: '邮箱', dataIndex: 'email', key: 'email', ellipsis: true },
{ title: '注册时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'actions', width: 200, fixed: 'right' },
]
];
// 所有用户表格列
const allColumns = [
@@ -307,40 +309,40 @@ const allColumns = [
{ title: 'Token 过期时间', dataIndex: 'jwt_exp', key: 'jwt_exp', width: 180 },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'actions', width: 200, fixed: 'right' },
]
];
// 行选择配置
const rowSelection = {
selectedRowKeys: selectedRowKeys,
onChange: (keys, rows) => {
selectedRowKeys.value = keys
selectedUsers.value = rows
selectedRowKeys.value = keys;
selectedUsers.value = rows;
},
}
};
// 获取待审批用户
const fetchPendingUsers = async () => {
loading.value = true
loading.value = true;
try {
pendingUsers.value = await adminAPI.getPendingUsers()
pendingUsers.value = await adminAPI.getPendingUsers();
} catch (error) {
message.error(error.message || '获取待审批用户失败')
message.error(error.message || '获取待审批用户失败');
} finally {
loading.value = false
loading.value = false;
}
}
};
// Tab 切换
const handleTabChange = (tab) => {
const handleTabChange = tab => {
if (tab === 'pending') {
fetchPendingUsers()
fetchPendingUsers();
} else {
handleRefresh()
handleRefresh();
}
}
};
// 审批通过用户
const handleApprove = async (user) => {
const handleApprove = async user => {
Modal.confirm({
title: '审批确认',
content: `确认通过用户 "${user.alias}" 的审批吗?`,
@@ -348,18 +350,18 @@ const handleApprove = async (user) => {
cancelText: '取消',
onOk: async () => {
try {
await adminAPI.approveUser(user.id)
message.success('审批成功')
fetchPendingUsers()
await adminAPI.approveUser(user.id);
message.success('审批成功');
fetchPendingUsers();
} catch (error) {
message.error(error.message || '审批失败')
message.error(error.message || '审批失败');
}
},
})
}
});
};
// 拒绝用户
const handleReject = async (user) => {
const handleReject = async user => {
Modal.confirm({
title: '拒绝确认',
content: `确认拒绝用户 "${user.alias}" 的申请吗?拒绝后将删除该用户。`,
@@ -368,36 +370,36 @@ const handleReject = async (user) => {
okType: 'danger',
onOk: async () => {
try {
await adminAPI.rejectUser(user.id)
message.success('已拒绝并删除用户')
fetchPendingUsers()
await adminAPI.rejectUser(user.id);
message.success('已拒绝并删除用户');
fetchPendingUsers();
} catch (error) {
message.error(error.message || '操作失败')
message.error(error.message || '操作失败');
}
},
})
}
});
};
// 刷新数据
const handleRefresh = async () => {
if (activeTab.value === 'pending') {
await fetchPendingUsers()
await fetchPendingUsers();
} else {
loading.value = true
loading.value = true;
try {
await userStore.fetchUsers()
message.success('刷新成功')
await userStore.fetchUsers();
message.success('刷新成功');
} catch (error) {
message.error(error.message || '刷新失败')
message.error(error.message || '刷新失败');
} finally {
loading.value = false
loading.value = false;
}
}
}
};
// 创建用户
const handleCreate = () => {
dialogMode.value = 'create'
dialogMode.value = 'create';
formData.value = {
alias: '',
role: 'user',
@@ -405,13 +407,13 @@ const handleCreate = () => {
email: '',
password: '',
reset_password: false,
}
dialogVisible.value = true
}
};
dialogVisible.value = true;
};
// 编辑用户
const handleEdit = (user) => {
dialogMode.value = 'edit'
const handleEdit = user => {
dialogMode.value = 'edit';
formData.value = {
id: user.id,
alias: user.alias,
@@ -420,44 +422,44 @@ const handleEdit = (user) => {
email: user.email || '',
password: '',
reset_password: false,
}
dialogVisible.value = true
}
};
dialogVisible.value = true;
};
// 提交表单
const handleSubmit = async () => {
if (!formRef.value) return
if (!formRef.value) return;
try {
await formRef.value.validate()
submitting.value = true
await formRef.value.validate();
submitting.value = true;
// 检查密码设置冲突
if (dialogMode.value === 'edit' && formData.value.password && formData.value.reset_password) {
message.warning('不能同时设置新密码和重置密码,请选择其一')
submitting.value = false
return
message.warning('不能同时设置新密码和重置密码,请选择其一');
submitting.value = false;
return;
}
if (dialogMode.value === 'create') {
await userStore.createUser(formData.value)
message.success('创建成功')
await userStore.createUser(formData.value);
message.success('创建成功');
} else {
await userStore.updateUser(formData.value.id, formData.value)
message.success('更新成功')
await userStore.updateUser(formData.value.id, formData.value);
message.success('更新成功');
}
dialogVisible.value = false
await handleRefresh()
dialogVisible.value = false;
await handleRefresh();
} catch (error) {
message.error(error.message || '操作失败')
message.error(error.message || '操作失败');
} finally {
submitting.value = false
submitting.value = false;
}
}
};
// 删除用户
const handleDelete = (user) => {
const handleDelete = user => {
Modal.confirm({
title: '警告',
content: `确定要删除用户 "${user.alias}" `,
@@ -466,15 +468,15 @@ const handleDelete = (user) => {
okType: 'danger',
onOk: async () => {
try {
await userStore.deleteUser(user.id)
message.success('删除成功')
await handleRefresh()
await userStore.deleteUser(user.id);
message.success('删除成功');
await handleRefresh();
} catch (error) {
message.error(error.message || '删除失败')
message.error(error.message || '删除失败');
}
},
})
}
});
};
// 批量审批
const handleBatchApprove = () => {
@@ -484,24 +486,24 @@ const handleBatchApprove = () => {
okText: '确认',
cancelText: '取消',
onOk: async () => {
const userIds = selectedUsers.value.map((u) => u.id)
let successCount = 0
let failureCount = 0
const userIds = selectedUsers.value.map(u => u.id);
let successCount = 0;
let failureCount = 0;
for (const userId of userIds) {
try {
await adminAPI.approveUser(userId)
successCount++
} catch (error) {
failureCount++
await adminAPI.approveUser(userId);
successCount++;
} catch {
failureCount++;
}
}
message.success(`批量审批完成成功 ${successCount}失败 ${failureCount}`)
await handleRefresh()
message.success(`批量审批完成成功 ${successCount}失败 ${failureCount}`);
await handleRefresh();
},
})
}
});
};
// 批量删除
const handleBatchDelete = () => {
@@ -512,29 +514,29 @@ const handleBatchDelete = () => {
cancelText: '取消',
okType: 'danger',
onOk: async () => {
const userIds = selectedUsers.value.map((u) => u.id)
let successCount = 0
let failureCount = 0
const userIds = selectedUsers.value.map(u => u.id);
let successCount = 0;
let failureCount = 0;
for (const userId of userIds) {
try {
await userStore.deleteUser(userId)
successCount++
} catch (error) {
failureCount++
await userStore.deleteUser(userId);
successCount++;
} catch {
failureCount++;
}
}
message.success(`批量删除完成成功 ${successCount}失败 ${failureCount}`)
await handleRefresh()
message.success(`批量删除完成成功 ${successCount}失败 ${failureCount}`);
await handleRefresh();
},
})
}
});
};
onMounted(() => {
// 默认加载所有用户
handleRefresh()
})
handleRefresh();
});
</script>
<style scoped>