Initial commit: 网络验证平台

This commit is contained in:
Admin
2026-04-27 17:22:56 +08:00
commit afe67d704e
780 changed files with 88960 additions and 0 deletions
@@ -0,0 +1,273 @@
<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'
import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
interface Application {
id: number
name: string
}
const loading = ref(true)
const saving = ref(false)
const applications = ref<Application[]>([])
const form = ref({
id: '',
app_id: '',
key: '',
value: '',
var_type: 'string',
description: '',
status: 'active',
})
async function fetchApplications() {
try {
const data = await api.get<{ applications: Application[] }>('/dev/applications')
applications.value = Array.isArray(data?.applications) ? data.applications : []
}
catch (error) {
console.error('获取应用列表失败:', error)
}
}
async function fetchConstant() {
loading.value = true
try {
const constId = route.params.id
const data = await api.get<{ id: number, app_id: number, key: string, value: string, var_type: string, description: string, status: string }>(`/dev/cloud-constants/${constId}`)
const constant = data
if (constant) {
form.value = {
id: String(constant.id),
app_id: String(constant.app_id || ''),
key: constant.key,
value: constant.value,
var_type: constant.var_type || 'string',
description: constant.description || '',
status: constant.status || 'active',
}
}
else {
toast.error(t('developer.cloudConstants.create.failed'))
router.push('/developer/cloud-constants')
}
}
catch (error) {
console.error('获取云端常量失败:', error)
toast.error(t('developer.cloudConstants.create.failed'))
router.push('/developer/cloud-constants')
}
finally {
loading.value = false
}
}
const selectedApplication = computed(() => {
if (form.value.app_id) {
return applications.value.find(app => String(app.id) === form.value.app_id)
}
return null
})
async function handleSave() {
if (!form.value.key) {
toast.error(t('developer.cloudConstants.create.keyRequired'))
return
}
if (!form.value.value) {
toast.error(t('developer.cloudConstants.create.valueRequired'))
return
}
saving.value = true
try {
await api.put(`/dev/cloud-constants/${form.value.id}`, {
key: form.value.key,
value: form.value.value,
var_type: form.value.var_type,
description: form.value.description,
status: form.value.status,
})
toast.success(t('developer.cloudConstants.create.success'))
router.push('/developer/cloud-constants')
}
catch (error: any) {
console.error('更新云端常量失败:', error)
toast.error(error.message || t('developer.cloudConstants.create.failed'))
}
finally {
saving.value = false
}
}
onMounted(async () => {
await fetchApplications()
fetchConstant()
})
</script>
<template>
<BasicPage
:title="t('developer.cloudConstants.edit')"
:description="t('developer.cloudConstants.editDescription')"
:breadcrumbs="[
{ title: t('developer.cloudConstants.title'), href: '/developer/cloud-constants' },
{ title: t('developer.cloudConstants.edit') },
]"
sticky
>
<div v-if="loading" class="flex items-center justify-center py-12">
<Icon icon="lucide:loader-2" class="size-8 animate-spin text-muted-foreground" />
</div>
<div v-else class="space-y-6">
<div class="grid gap-6 lg:grid-cols-3">
<div class="lg:col-span-2 space-y-6">
<UiCard>
<UiCardHeader>
<UiCardTitle class="flex items-center gap-2">
<Icon icon="lucide:settings-2" class="size-5" />
{{ t('developer.cloudConstants.create.config') }}
</UiCardTitle>
<UiCardDescription>{{ t('developer.cloudConstants.create.configDesc') }}</UiCardDescription>
</UiCardHeader>
<UiCardContent class="space-y-6">
<div class="space-y-2">
<UiLabel>{{ t('developer.cloudConstants.create.application') }}</UiLabel>
<div class="flex items-center gap-2 p-2.5 rounded-md border bg-muted/50">
<Icon icon="lucide:layout-grid" class="size-4 text-muted-foreground" />
<span>{{ selectedApplication?.name || '-' }}</span>
</div>
</div>
<div class="space-y-2">
<UiLabel for="varType">
{{ t('developer.cloudConstants.create.type') }}
</UiLabel>
<UiSelect id="varType" v-model="form.var_type">
<UiSelectTrigger>
<UiSelectValue :placeholder="t('developer.cloudConstants.create.selectType')" />
</UiSelectTrigger>
<UiSelectContent>
<UiSelectItem value="integer">
{{ t('developer.cloudConstants.types.integer') }}
</UiSelectItem>
<UiSelectItem value="decimal">
{{ t('developer.cloudConstants.types.decimal') }}
</UiSelectItem>
<UiSelectItem value="string">
{{ t('developer.cloudConstants.types.string') }}
</UiSelectItem>
</UiSelectContent>
</UiSelect>
</div>
<div class="space-y-2">
<UiLabel for="key">
{{ t('developer.cloudConstants.create.key') }}
</UiLabel>
<UiInput id="key" v-model="form.key" :placeholder="t('developer.cloudConstants.create.keyPlaceholder')" />
<p class="text-xs text-muted-foreground">
{{ t('developer.cloudConstants.create.keyHint') }}
</p>
</div>
<div class="space-y-2">
<UiLabel for="value">
{{ t('developer.cloudConstants.create.value') }}
</UiLabel>
<UiTextarea id="value" v-model="form.value" :placeholder="t('developer.cloudConstants.create.valuePlaceholder')" rows="3" />
</div>
<div class="space-y-2">
<UiLabel for="description">
{{ t('developer.cloudConstants.create.description') }}
</UiLabel>
<UiInput id="description" v-model="form.description" :placeholder="t('developer.cloudConstants.create.descriptionPlaceholder')" />
</div>
</UiCardContent>
</UiCard>
</div>
<div class="space-y-6">
<UiCard>
<UiCardHeader>
<UiCardTitle class="flex items-center gap-2">
<Icon icon="lucide:eye" class="size-5" />
{{ t('developer.cloudConstants.create.preview') }}
</UiCardTitle>
</UiCardHeader>
<UiCardContent class="space-y-4">
<div class="space-y-3">
<div class="flex justify-between text-sm">
<span class="text-muted-foreground">{{ t('developer.cloudConstants.create.application') }}</span>
<span>{{ selectedApplication?.name || '-' }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-muted-foreground">{{ t('developer.cloudConstants.create.type') }}</span>
<span>{{ t(`developer.cloudConstants.types.${form.var_type}`) }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-muted-foreground">{{ t('developer.cloudConstants.create.key') }}</span>
<span>{{ form.key || '-' }}</span>
</div>
<div class="flex justify-between text-sm items-center">
<span class="text-muted-foreground">{{ t('developer.cloudConstants.create.status') }}</span>
<UiSwitch
:checked="form.status === 'active'"
@update:checked="form.status = $event ? 'active' : 'inactive'"
/>
</div>
<div class="border-t pt-3 mt-3">
<div class="text-sm">
<div class="text-muted-foreground mb-2">
{{ t('developer.cloudConstants.create.value') }}
</div>
<div class="bg-muted p-2 rounded max-h-[100px] overflow-y-auto text-xs">
{{ form.value || '-' }}
</div>
</div>
</div>
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardContent class="pt-6">
<div class="flex flex-col gap-3">
<UiButton
class="w-full"
size="lg"
:disabled="saving || !form.key || !form.value"
@click="handleSave"
>
<Icon v-if="saving" icon="lucide:loader-2" class="mr-2 h-4 w-4 animate-spin" />
<Icon v-else icon="lucide:check" class="mr-2 h-4 w-4" />
{{ t('developer.cloudConstants.create.submit') }}
</UiButton>
<UiButton
variant="outline"
class="w-full"
@click="router.back()"
>
{{ t('developer.cloudConstants.create.cancel') }}
</UiButton>
</div>
</UiCardContent>
</UiCard>
</div>
</div>
</div>
</BasicPage>
</template>
@@ -0,0 +1,185 @@
import type { ColumnDef } from '@tanstack/vue-table'
import type { Composer } from 'vue-i18n'
import { Download, File, MoreHorizontal, Pencil, Power, PowerOff, Trash2 } from 'lucide-vue-next'
import { h } from 'vue'
import type { CloudConstant } from '@/pages/developer/cloud-constants/data/schema'
import { Copy } from '@/components/sva-ui/copy'
import Badge from '@/components/ui/badge/Badge.vue'
import Button from '@/components/ui/button/Button.vue'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
export function getColumns(actions: {
onEdit: (row: CloudConstant) => void
onDelete: (row: CloudConstant) => void
onToggleStatus: (row: CloudConstant) => void
onDownload: (row: CloudConstant) => void
}, t: Composer['t']): ColumnDef<CloudConstant>[] {
return [
{
accessorKey: 'key',
header: () => t('developer.cloudConstants.columns.key'),
cell: ({ row }) => {
const key = row.getValue('key') as string
if (!key)
return '-'
return h('div', { class: 'flex items-center space-x-2' }, [
h('code', { class: 'text-xs bg-muted px-2 py-1 rounded font-mono' }, key),
h(Copy, { class: 'h-4 w-4', size: 'sm', content: key }),
])
},
},
{
accessorKey: 'value',
header: () => t('developer.cloudConstants.columns.value'),
cell: ({ row }) => {
const value = row.getValue('value') as string
const varType = row.original.var_type
if (!value)
return '-'
if (varType === 'binary') {
const originalName = row.original.original_name || value
return h('div', { class: 'flex items-center gap-2' }, [
h(File, { class: 'h-4 w-4 text-muted-foreground' }),
h('span', { class: 'max-w-xs truncate', title: originalName }, originalName),
])
}
return h('div', { class: 'max-w-xs truncate', title: value }, value)
},
},
{
accessorKey: 'var_type',
header: () => t('developer.cloudConstants.columns.type'),
cell: ({ row }) => {
const type = row.getValue('var_type') as string
const typeMap: Record<string, string> = {
integer: t('developer.cloudConstants.types.integer'),
decimal: t('developer.cloudConstants.types.decimal'),
string: t('developer.cloudConstants.types.string'),
binary: t('developer.cloudConstants.types.binary'),
}
return h(Badge, { variant: 'secondary' }, () => typeMap[type || 'string'] || type || 'string')
},
},
{
accessorKey: 'description',
header: () => t('developer.cloudConstants.columns.description'),
cell: ({ row }) => {
const description = row.getValue('description') as string
if (!description)
return '-'
return h('div', { class: 'max-w-xs truncate', title: description }, description)
},
},
{
accessorKey: 'application_name',
header: () => t('developer.cloudConstants.columns.application'),
cell: ({ row }) => {
const appName = row.getValue('application_name') as string
const appId = row.original.app_id
if (!appId)
return h(Badge, { variant: 'outline' }, () => t('developer.cloudConstants.notLinked'))
if (!appName)
return '-'
return h(Badge, { variant: 'outline' }, () => appName)
},
},
{
accessorKey: 'status',
header: () => t('developer.cloudConstants.columns.status'),
cell: ({ row }) => {
const status = row.getValue('status') as string
const isActive = status === 'active'
return h(Badge, { variant: isActive ? 'default' : 'destructive' }, () => isActive ? t('developer.cloudConstants.statusActive') : t('developer.cloudConstants.statusInactive'))
},
},
{
accessorKey: 'created_at',
header: () => t('developer.cloudConstants.columns.createdAt'),
cell: ({ row }) => {
const createdAt = row.getValue('created_at')
if (!createdAt)
return '-'
try {
const date = new Date(createdAt as string)
if (Number.isNaN(date.getTime()))
return '-'
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
catch {
return '-'
}
},
},
{
id: 'actions',
header: () => h('span', { class: 'sr-only' }, t('common.actions')),
cell: ({ row }) => {
const constant = row.original
return h(
DropdownMenu,
{},
{
default: () => [
h(DropdownMenuTrigger, { asChild: true }, () =>
h(Button, { variant: 'ghost', class: 'h-8 w-8 p-0' }, () => [
h(MoreHorizontal, { class: 'h-4 w-4' }),
h('span', { class: 'sr-only' }, t('common.openMenu')),
])),
h(
DropdownMenuContent,
{ align: 'end' },
() => {
const items = [
h(DropdownMenuItem, { onClick: () => actions.onEdit(constant) }, () => [
h(Pencil, { class: 'mr-2 h-4 w-4' }),
t('developer.cloudConstants.edit'),
]),
]
if (constant.var_type === 'binary') {
items.push(
h(DropdownMenuItem, { onClick: () => actions.onDownload(constant) }, () => [
h(Download, { class: 'mr-2 h-4 w-4' }),
'下载文件',
]),
)
}
items.push(
h(DropdownMenuItem, { onClick: () => actions.onToggleStatus(constant) }, () => [
constant.status === 'active' ? h(PowerOff, { class: 'mr-2 h-4 w-4' }) : h(Power, { class: 'mr-2 h-4 w-4' }),
constant.status === 'active' ? t('developer.cloudConstants.disable') : t('developer.cloudConstants.enable'),
]),
h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onDelete(constant) }, () => [
h(Trash2, { class: 'mr-2 h-4 w-4' }),
t('developer.cloudConstants.delete'),
]),
)
return items
},
),
],
},
)
},
enableSorting: false,
enableHiding: false,
},
]
}
@@ -0,0 +1,44 @@
<script setup lang="ts">
import type { Row } from '@tanstack/vue-table'
import { Ellipsis, Pencil, Trash2 } from 'lucide-vue-next'
import type { CloudConstant } from '../data/schema'
interface DataTableRowActionsProps {
row: Row<CloudConstant>
}
const props = defineProps<DataTableRowActionsProps>()
const emit = defineEmits<{
edit: [constant: CloudConstant]
delete: [constant: CloudConstant]
}>()
const constant = props.row.original
</script>
<template>
<UiDropdownMenu>
<UiDropdownMenuTrigger as-child>
<UiButton
variant="ghost"
class="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
>
<Ellipsis class="size-4" />
<span class="sr-only">打开菜单</span>
</UiButton>
</UiDropdownMenuTrigger>
<UiDropdownMenuContent align="end" class="w-[160px]">
<UiDropdownMenuItem @click="emit('edit', constant)">
<Pencil class="mr-2 h-4 w-4" />
编辑
</UiDropdownMenuItem>
<UiDropdownMenuSeparator />
<UiDropdownMenuItem class="text-destructive" @click="emit('delete', constant)">
<Trash2 class="mr-2 h-4 w-4" />
删除
</UiDropdownMenuItem>
</UiDropdownMenuContent>
</UiDropdownMenu>
</template>
@@ -0,0 +1,43 @@
<script setup lang="ts">
import type { Table } from '@tanstack/vue-table'
import { X } from 'lucide-vue-next'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { CloudConstant } from '@/pages/developer/cloud-constants/data/schema'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
const props = defineProps<DataTableToolbarProps>()
const { t } = useI18n()
interface DataTableToolbarProps {
table: Table<CloudConstant>
}
const isFiltered = computed(() => props.table.getState().columnFilters.length > 0)
</script>
<template>
<div class="flex items-center flex-1 space-x-2">
<Input
:placeholder="t('developer.cloudConstants.searchPlaceholder')"
:model-value="(table.getColumn('key')?.getFilterValue() as string) ?? ''"
class="h-8 w-[150px] lg:w-[250px]"
@input="table.getColumn('key')?.setFilterValue($event.target.value)"
/>
<Button
v-if="isFiltered"
variant="ghost"
class="h-8 px-2 lg:px-3"
@click="table.resetColumnFilters()"
>
{{ t('common.reset') }}
<X class="size-4 ml-2" />
</Button>
</div>
</template>
@@ -0,0 +1,98 @@
<script setup lang="ts">
import type { ColumnDef } from '@tanstack/vue-table'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { DataTableProps } from '@/components/data-table/types'
import type { CloudConstant } from '@/pages/developer/cloud-constants/data/schema'
import BulkActions from '@/components/data-table/bulk-actions.vue'
import DataTable from '@/components/data-table/data-table.vue'
import { SelectColumn } from '@/components/data-table/table-columns'
import { generateVueTable } from '@/components/data-table/use-generate-vue-table'
import DataTableViewOptions from '@/components/data-table/view-options.vue'
import { getColumns } from '@/pages/developer/cloud-constants/components/columns'
import DataTableToolbar from '@/pages/developer/cloud-constants/components/data-table-toolbar.vue'
const props = defineProps<Omit<DataTableProps<CloudConstant>, 'columns'> & {
onEdit: (row: CloudConstant) => void
onDelete: (row: CloudConstant) => void
onToggleStatus: (row: CloudConstant) => void
onDownload: (row: CloudConstant) => void
}>()
const emit = defineEmits<{
refresh: []
batchAction: [action: 'enable' | 'disable' | 'delete', rows: CloudConstant[]]
}>()
const { t } = useI18n()
const columns = computed(() => [
SelectColumn as ColumnDef<CloudConstant>,
...getColumns({
onEdit: props.onEdit,
onDelete: props.onDelete,
onToggleStatus: props.onToggleStatus,
onDownload: props.onDownload,
}, t),
])
const table = generateVueTable<CloudConstant>({
get data() { return props.data },
get loading() { return props.loading },
columns: columns.value,
}, columns.value)
const columnLabels: Record<string, string> = {
select: 'developer.cloudConstants.select',
key: 'developer.cloudConstants.columns.key',
value: 'developer.cloudConstants.columns.value',
var_type: 'developer.cloudConstants.columns.type',
description: 'developer.cloudConstants.columns.description',
application_name: 'developer.cloudConstants.columns.application',
status: 'developer.cloudConstants.columns.status',
created_at: 'developer.cloudConstants.columns.createdAt',
}
defineExpose({
table,
})
function handleBatchAction(action: 'enable' | 'disable' | 'delete') {
const selectedRows = table.getSelectedRowModel().rows.map(row => row.original)
emit('batchAction', action, selectedRows)
table.resetRowSelection()
}
</script>
<template>
<DataTable :columns="columns" :data :loading :table @refresh="emit('refresh')">
<template #toolbar>
<div class="space-y-3">
<div class="flex items-center justify-end">
<slot name="actions" />
</div>
<BulkActions :table="table" entity-name="constants">
<UiButton variant="outline" size="sm" @click="handleBatchAction('enable')">
{{ t('developer.cloudConstants.batchEnableBtn') }}
</UiButton>
<UiButton variant="outline" size="sm" @click="handleBatchAction('disable')">
{{ t('developer.cloudConstants.batchDisableBtn') }}
</UiButton>
<UiButton variant="destructive" size="sm" @click="handleBatchAction('delete')">
{{ t('developer.cloudConstants.batchDeleteBtn') }}
</UiButton>
</BulkActions>
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="flex flex-wrap items-center gap-2">
<DataTableToolbar :table />
<slot name="filters" />
</div>
<DataTableViewOptions :table="table" :column-labels="columnLabels" />
</div>
</div>
</template>
</DataTable>
</template>
@@ -0,0 +1,354 @@
<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'
import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'
const router = useRouter()
const { t } = useI18n()
interface Application {
id: number
name: string
}
const saving = ref(false)
const applications = ref<Application[]>([])
const fileInput = ref<HTMLInputElement | null>(null)
const selectedFile = ref<File | null>(null)
const uploading = ref(false)
const form = ref({
app_id: '',
key: '',
value: '',
var_type: 'string',
description: '',
status: 'active',
})
async function fetchApplications() {
try {
const data = await api.get<{ applications: Application[] }>('/dev/applications')
applications.value = Array.isArray(data?.applications) ? data.applications : []
}
catch (error) {
console.error('获取应用列表失败:', error)
}
}
const selectedApplication = computed(() => {
if (form.value.app_id) {
return applications.value.find(app => String(app.id) === form.value.app_id)
}
return null
})
function handleFileSelect(event: Event) {
const target = event.target as HTMLInputElement
if (target.files && target.files[0]) {
selectedFile.value = target.files[0]
if (!form.value.key) {
form.value.key = selectedFile.value.name.replace(/\.[^/.]+$/, '')
}
}
}
function clearFile() {
selectedFile.value = null
if (fileInput.value) {
fileInput.value.value = ''
}
}
async function handleSave() {
if (!form.value.key) {
toast.error(t('developer.cloudConstants.create.keyRequired'))
return
}
if (!form.value.app_id) {
toast.error(t('developer.cloudConstants.create.appRequired'))
return
}
if (form.value.var_type === 'binary') {
if (!selectedFile.value) {
toast.error('请选择要上传的文件')
return
}
await uploadFile()
return
}
if (!form.value.value) {
toast.error(t('developer.cloudConstants.create.valueRequired'))
return
}
saving.value = true
try {
await api.post('/dev/cloud-constants', {
app_id: Number(form.value.app_id),
key: form.value.key,
value: form.value.value,
var_type: form.value.var_type,
description: form.value.description,
status: form.value.status,
})
toast.success(t('developer.cloudConstants.create.success'))
router.push('/developer/cloud-constants')
}
catch (error: any) {
console.error('创建云端常量失败:', error)
toast.error(error.message || t('developer.cloudConstants.create.failed'))
}
finally {
saving.value = false
}
}
async function uploadFile() {
if (!selectedFile.value || !form.value.app_id || !form.value.key)
return
uploading.value = true
try {
const formData = new FormData()
formData.append('file', selectedFile.value)
formData.append('app_id', form.value.app_id)
formData.append('key', form.value.key)
formData.append('description', form.value.description)
formData.append('status', form.value.status)
await api.postFormData('/dev/cloud-constants/upload', formData)
toast.success(t('developer.cloudConstants.create.success'))
router.push('/developer/cloud-constants')
}
catch (error: any) {
console.error('上传文件失败:', error)
toast.error(error.message || '上传文件失败')
}
finally {
uploading.value = false
}
}
function formatFileSize(bytes: number): string {
if (bytes === 0)
return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
}
onMounted(() => {
fetchApplications()
})
</script>
<template>
<BasicPage
:title="t('developer.cloudConstants.addConstant')"
:description="t('developer.cloudConstants.createDescription')"
:breadcrumbs="[
{ title: t('developer.cloudConstants.title'), href: '/developer/cloud-constants' },
{ title: t('developer.cloudConstants.addConstant') },
]"
sticky
>
<div class="space-y-6">
<div class="grid gap-6 lg:grid-cols-3">
<div class="lg:col-span-2 space-y-6">
<UiCard>
<UiCardHeader>
<UiCardTitle class="flex items-center gap-2">
<Icon icon="lucide:settings-2" class="size-5" />
{{ t('developer.cloudConstants.create.config') }}
</UiCardTitle>
<UiCardDescription>{{ t('developer.cloudConstants.create.configDesc') }}</UiCardDescription>
</UiCardHeader>
<UiCardContent class="space-y-6">
<div class="space-y-2">
<UiLabel for="application">
{{ t('developer.cloudConstants.create.application') }}
</UiLabel>
<UiSelect v-model="form.app_id">
<UiSelectTrigger>
<UiSelectValue :placeholder="t('developer.cloudConstants.create.selectApp')" />
</UiSelectTrigger>
<UiSelectContent>
<UiSelectItem v-for="app in applications" :key="app.id" :value="String(app.id)">
{{ app.name }}
</UiSelectItem>
</UiSelectContent>
</UiSelect>
</div>
<div class="space-y-2">
<UiLabel for="varType">
{{ t('developer.cloudConstants.create.type') }}
</UiLabel>
<UiSelect id="varType" v-model="form.var_type">
<UiSelectTrigger>
<UiSelectValue :placeholder="t('developer.cloudConstants.create.selectType')" />
</UiSelectTrigger>
<UiSelectContent>
<UiSelectItem value="integer">
{{ t('developer.cloudConstants.types.integer') }}
</UiSelectItem>
<UiSelectItem value="decimal">
{{ t('developer.cloudConstants.types.decimal') }}
</UiSelectItem>
<UiSelectItem value="string">
{{ t('developer.cloudConstants.types.string') }}
</UiSelectItem>
<UiSelectItem value="binary">
二进制
</UiSelectItem>
</UiSelectContent>
</UiSelect>
</div>
<div class="space-y-2">
<UiLabel for="key">
{{ t('developer.cloudConstants.create.key') }}
</UiLabel>
<UiInput id="key" v-model="form.key" :placeholder="t('developer.cloudConstants.create.keyPlaceholder')" />
<p class="text-xs text-muted-foreground">
{{ t('developer.cloudConstants.create.keyHint') }}
</p>
</div>
<div v-if="form.var_type === 'binary'" class="space-y-2">
<UiLabel>选择文件</UiLabel>
<div v-if="!selectedFile" class="border-2 border-dashed rounded-lg p-6 text-center">
<input
ref="fileInput"
type="file"
class="hidden"
@change="handleFileSelect"
>
<Icon icon="lucide:upload" class="mx-auto h-12 w-12 text-muted-foreground mb-4" />
<p class="text-sm text-muted-foreground mb-2">
拖拽文件到此处或点击选择
</p>
<UiButton variant="outline" @click="fileInput?.click()">
选择文件
</UiButton>
</div>
<div v-else class="border rounded-lg p-4">
<div class="flex items-center justify-between">
<div class="flex items-center gap-3">
<Icon icon="lucide:file" class="h-8 w-8 text-muted-foreground" />
<div>
<p class="font-medium">
{{ selectedFile.name }}
</p>
<p class="text-sm text-muted-foreground">
{{ formatFileSize(selectedFile.size) }}
</p>
</div>
</div>
<UiButton variant="ghost" size="icon" @click="clearFile">
<Icon icon="lucide:x" class="h-4 w-4" />
</UiButton>
</div>
</div>
</div>
<div v-else class="space-y-2">
<UiLabel for="value">
{{ t('developer.cloudConstants.create.value') }}
</UiLabel>
<UiTextarea id="value" v-model="form.value" :placeholder="t('developer.cloudConstants.create.valuePlaceholder')" rows="3" />
</div>
<div class="space-y-2">
<UiLabel for="description">
{{ t('developer.cloudConstants.create.description') }}
</UiLabel>
<UiInput id="description" v-model="form.description" :placeholder="t('developer.cloudConstants.create.descriptionPlaceholder')" />
</div>
</UiCardContent>
</UiCard>
</div>
<div class="space-y-6">
<UiCard>
<UiCardHeader>
<UiCardTitle class="flex items-center gap-2">
<Icon icon="lucide:eye" class="size-5" />
{{ t('developer.cloudConstants.create.preview') }}
</UiCardTitle>
</UiCardHeader>
<UiCardContent class="space-y-4">
<div class="space-y-3">
<div class="flex justify-between text-sm">
<span class="text-muted-foreground">{{ t('developer.cloudConstants.create.application') }}</span>
<span>{{ selectedApplication?.name || '-' }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-muted-foreground">{{ t('developer.cloudConstants.create.type') }}</span>
<span>{{ t(`developer.cloudConstants.types.${form.var_type}`) }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-muted-foreground">{{ t('developer.cloudConstants.create.key') }}</span>
<span>{{ form.key || '-' }}</span>
</div>
<div class="flex justify-between text-sm items-center">
<span class="text-muted-foreground">{{ t('developer.cloudConstants.create.status') }}</span>
<UiSwitch
:checked="form.status === 'active'"
@update:checked="form.status = $event ? 'active' : 'inactive'"
/>
</div>
<div class="border-t pt-3 mt-3">
<div class="text-sm">
<div class="text-muted-foreground mb-2">
{{ t('developer.cloudConstants.create.value') }}
</div>
<div v-if="form.var_type === 'binary'" class="bg-muted p-2 rounded text-xs">
{{ selectedFile ? `${selectedFile.name} (${formatFileSize(selectedFile.size)})` : '未选择文件' }}
</div>
<div v-else class="bg-muted p-2 rounded max-h-[100px] overflow-y-auto text-xs">
{{ form.value || '-' }}
</div>
</div>
</div>
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardContent class="pt-6">
<div class="flex flex-col gap-3">
<UiButton
class="w-full"
size="lg"
:disabled="(saving || uploading) || !form.app_id || !form.key || (form.var_type !== 'binary' && !form.value) || (form.var_type === 'binary' && !selectedFile)"
@click="handleSave"
>
<Icon v-if="saving || uploading" icon="lucide:loader-2" class="mr-2 h-4 w-4 animate-spin" />
<Icon v-else icon="lucide:check" class="mr-2 h-4 w-4" />
{{ uploading ? '上传中...' : t('developer.cloudConstants.create.submit') }}
</UiButton>
<UiButton
variant="outline"
class="w-full"
@click="router.back()"
>
{{ t('developer.cloudConstants.create.cancel') }}
</UiButton>
</div>
</UiCardContent>
</UiCard>
</div>
</div>
</div>
</BasicPage>
</template>
@@ -0,0 +1,9 @@
import type { CloudConstant } from './schema'
export const constantAppOptions: { label: string, value: string }[] = []
export function filterConstantsByApp(constants: CloudConstant[], appId: string): CloudConstant[] {
if (!appId || appId === 'all')
return constants
return constants.filter(c => String(c.app_id) === appId)
}
@@ -0,0 +1,21 @@
import { z } from 'zod'
export const cloudConstantSchema = z.object({
id: z.union([z.string(), z.number()]),
user_id: z.union([z.string(), z.number()]),
app_id: z.union([z.string(), z.number()]).nullable().optional(),
application_name: z.string().optional().nullable(),
key: z.string(),
value: z.string(),
var_type: z.string().optional().nullable(),
file_path: z.string().optional().nullable(),
file_size: z.union([z.string(), z.number()]).optional().nullable(),
mime_type: z.string().optional().nullable(),
original_name: z.string().optional().nullable(),
description: z.string().optional().nullable(),
status: z.string().optional().nullable(),
created_at: z.string(),
updated_at: z.string().optional().nullable(),
})
export type CloudConstant = z.infer<typeof cloudConstantSchema>
@@ -0,0 +1,337 @@
<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'
import ConfirmDialog from '@/components/confirm-dialog.vue'
import DateRangeFilter from '@/components/data-table/date-range-filter.vue'
import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'
import type { CloudConstant } from './data/schema'
import DataTable from './components/data-table.vue'
const { t } = useI18n()
const router = useRouter()
interface Application {
id: number
name: string
app_key: string
}
const loading = ref(true)
const constants = ref<CloudConstant[]>([])
const applications = ref<Application[]>([])
const appFilter = ref<string>('')
const startDate = ref<string>('')
const endDate = ref<string>('')
const deleteDialogOpen = ref(false)
const deleteTarget = ref<CloudConstant | null>(null)
const batchDialogOpen = ref(false)
const batchAction = ref<'enable' | 'disable' | 'delete' | null>(null)
const selectedRows = ref<CloudConstant[]>([])
const filteredConstants = computed(() => {
let result = [...constants.value]
if (appFilter.value) {
result = result.filter(c => String(c.app_id) === appFilter.value)
}
if (startDate.value) {
const fromDateTime = startDate.value.includes('T')
? startDate.value.replace('T', ' ')
: `${startDate.value} 00:00`
result = result.filter(c => c.created_at >= fromDateTime)
}
if (endDate.value) {
const toDateTime = endDate.value.includes('T')
? endDate.value.replace('T', ' ')
: `${endDate.value} 23:59`
result = result.filter(c => c.created_at <= toDateTime)
}
return result
})
const linkedCount = computed(() => constants.value.filter(c => c.app_id).length)
const unlinkedCount = computed(() => constants.value.filter(c => !c.app_id).length)
const applicationOptions = computed(() => {
return applications.value.map(app => ({
label: app.name,
value: String(app.id),
}))
})
async function fetchApplications() {
try {
const data = await api.get<{ applications: Application[] }>('/dev/applications')
applications.value = data?.applications || []
}
catch (error) {
console.error('获取应用列表失败:', error)
}
}
async function fetchConstants() {
loading.value = true
try {
const data = await api.get<{ constants: CloudConstant[] }>('/dev/cloud-constants')
const consts = data?.constants || []
constants.value = consts.map((c: any) => ({
...c,
application_name: applications.value.find(app => app.id === c.app_id)?.name || '',
}))
}
catch (error) {
console.error('获取云端常量失败:', error)
constants.value = []
}
finally {
loading.value = false
}
}
function openCreatePage() {
router.push('/developer/cloud-constants/create')
}
function openEditPage(constant: CloudConstant) {
router.push(`/developer/cloud-constants/${constant.id}`)
}
function confirmDelete(constant: CloudConstant) {
deleteTarget.value = constant
deleteDialogOpen.value = true
}
async function handleDelete() {
if (!deleteTarget.value)
return
try {
await api.delete(`/dev/cloud-constants/${deleteTarget.value.id}`)
toast.success(t('developer.cloudConstants.deleteSuccess'))
fetchConstants()
}
catch (error: any) {
console.error('删除云端常量失败:', error)
toast.error(error.message || t('developer.cloudConstants.deleteFailed'))
}
finally {
deleteTarget.value = null
}
}
async function handleToggleStatus(constant: CloudConstant) {
const newStatus = constant.status === 'active' ? 'inactive' : 'active'
try {
await api.put(`/dev/cloud-constants/${constant.id}`, {
key: constant.key,
value: constant.value,
var_type: constant.var_type,
description: constant.description,
status: newStatus,
})
toast.success(newStatus === 'active' ? t('developer.cloudConstants.enableSuccess') : t('developer.cloudConstants.disableSuccess'))
fetchConstants()
}
catch (error: any) {
console.error('更新状态失败:', error)
toast.error(error.message || t('developer.cloudConstants.updateFailed'))
}
}
function handleDownload(constant: CloudConstant) {
if (constant.var_type !== 'binary')
return
const token = localStorage.getItem('token')
const url = `/api/v1/dev/cloud-constants/${constant.id}/download?token=${token}`
window.open(url, '_blank')
}
function openBatchDialog(action: 'enable' | 'disable' | 'delete', rows: CloudConstant[]) {
batchAction.value = action
selectedRows.value = rows
batchDialogOpen.value = true
}
async function handleBatchAction() {
if (!batchAction.value || selectedRows.value.length === 0)
return
const ids = selectedRows.value.map(c => c.id)
try {
if (batchAction.value === 'delete') {
await Promise.all(ids.map(id => api.delete(`/dev/cloud-constants/${id}`)))
toast.success(t('developer.cloudConstants.batchDeleteSuccess'))
}
else {
const status = batchAction.value === 'enable' ? 'active' : 'inactive'
await Promise.all(selectedRows.value.map(c => api.put(`/dev/cloud-constants/${c.id}`, {
key: c.key,
value: c.value,
var_type: c.var_type,
description: c.description,
status,
})))
toast.success(batchAction.value === 'enable' ? t('developer.cloudConstants.batchEnableSuccess') : t('developer.cloudConstants.batchDisableSuccess'))
}
fetchConstants()
}
catch (error: any) {
console.error('批量操作失败:', error)
toast.error(error.message || t('developer.cloudConstants.batchFailed'))
}
finally {
batchAction.value = null
selectedRows.value = []
}
}
onMounted(async () => {
await fetchApplications()
fetchConstants()
})
</script>
<template>
<BasicPage
:title="t('developer.cloudConstants.title')"
:description="t('developer.cloudConstants.description')"
sticky
>
<template #actions>
<UiButton size="sm" @click="openCreatePage">
<Icon icon="lucide:plus" class="mr-2 h-4 w-4" />
{{ t('developer.cloudConstants.addConstant') }}
</UiButton>
</template>
<div class="space-y-6">
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('developer.cloudConstants.totalConstants') }}
</UiCardTitle>
<Icon icon="lucide:database" class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ filteredConstants.length }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('developer.cloudConstants.linkedApps') }}
</UiCardTitle>
<Icon icon="lucide:link" class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ linkedCount }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('developer.cloudConstants.unlinked') }}
</UiCardTitle>
<Icon icon="lucide:unlink" class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ unlinkedCount }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('developer.cloudConstants.appCount') }}
</UiCardTitle>
<Icon icon="lucide:layout-grid" class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ applications.length }}
</div>
</UiCardContent>
</UiCard>
</div>
<UiCard>
<UiCardContent class="p-6">
<DataTable
:loading
:data="filteredConstants"
:on-edit="openEditPage"
:on-delete="confirmDelete"
:on-toggle-status="handleToggleStatus"
:on-download="handleDownload"
@refresh="fetchConstants"
@batch-action="openBatchDialog"
>
<template #filters>
<SingleFilter
v-model="appFilter"
:title="t('developer.cloudConstants.application')"
:options="applicationOptions"
/>
<DateRangeFilter
v-model:start-model-value="startDate"
v-model:end-model-value="endDate"
/>
</template>
</DataTable>
</UiCardContent>
</UiCard>
</div>
<ConfirmDialog
v-model:open="deleteDialogOpen"
destructive
:confirm-button-text="t('developer.cloudConstants.delete')"
:cancel-button-text="t('common.reset')"
@confirm="handleDelete"
>
<template #title>
{{ t('developer.cloudConstants.deleteConstant') }}
</template>
<template #description>
{{ t('developer.cloudConstants.deleteConfirm', { key: deleteTarget?.key }) }}
</template>
</ConfirmDialog>
<ConfirmDialog
v-model:open="batchDialogOpen"
:destructive="batchAction === 'delete'"
:confirm-button-text="batchAction === 'delete' ? t('developer.cloudConstants.delete') : t('common.confirm')"
:cancel-button-text="t('common.cancel')"
@confirm="handleBatchAction"
>
<template #title>
{{ batchAction === 'delete' ? t('developer.cloudConstants.batchDelete') : batchAction === 'enable' ? t('developer.cloudConstants.batchEnable') : t('developer.cloudConstants.batchDisable') }}
</template>
<template #description>
{{ batchAction === 'delete' ? t('developer.cloudConstants.batchDeleteConfirm', { count: selectedRows.length }) : batchAction === 'enable' ? t('developer.cloudConstants.batchEnableConfirm', { count: selectedRows.length }) : t('developer.cloudConstants.batchDisableConfirm', { count: selectedRows.length }) }}
</template>
</ConfirmDialog>
</BasicPage>
</template>