chore(frontend): introduce prettier + eslint and prune unused code
Backend CI / Backend (push) Has been cancelled
Frontend CI / Frontend (push) Failing after 1m39s

- Add Prettier 3 with prettier-plugin-organize-imports (sorts/removes unused imports)
- Add ESLint 10 flat config with typescript-eslint + eslint-plugin-vue + eslint-config-prettier
- Add root scripts: format, format:check, lint, lint:fix
- Reformat 257 files across admin-web, ops-web, desktop-client, packages
- Remove unused locals/exports flagged by --noUnusedLocals/--noUnusedParameters
- Fix duplicate localTabLabel key, surrogate-pair regex u-flag, NBSP literal in regex
- Skip server/ (Go) and apps/browser-extension/ (deprecated per ADR)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-01 20:39:09 +08:00
parent 21c7892ee4
commit 162abdc97c
258 changed files with 42261 additions and 37556 deletions
+113 -110
View File
@@ -35,11 +35,11 @@
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 'active' ? 'green' : 'red'">
{{ record.status === "active" ? "启用" : "停用" }}
{{ record.status === 'active' ? '启用' : '停用' }}
</a-tag>
</template>
<template v-else-if="column.key === 'last_login_at'">
{{ record.last_login_at ? formatDate(record.last_login_at) : "" }}
{{ record.last_login_at ? formatDate(record.last_login_at) : '' }}
</template>
<template v-else-if="column.key === 'created_at'">
{{ formatDate(record.created_at) }}
@@ -68,7 +68,10 @@
type="text"
shape="circle"
size="small"
:class="['action-btn', record.status === 'active' ? 'action-revoke' : 'action-play']"
:class="[
'action-btn',
record.status === 'active' ? 'action-revoke' : 'action-play',
]"
:disabled="record.id === auth.operator?.id"
>
<StopOutlined v-if="record.status === 'active'" />
@@ -121,203 +124,203 @@
</template>
<script setup lang="ts">
import { KeyOutlined, StopOutlined, PlayCircleOutlined } from "@ant-design/icons-vue";
import type { TablePaginationConfig } from "ant-design-vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { computed, onMounted, reactive, ref } from "vue";
import { KeyOutlined, PlayCircleOutlined, StopOutlined } from '@ant-design/icons-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'
import { OpsApiError, http } from "@/lib/http";
import { useAuthStore } from "@/stores/auth";
import { OpsApiError, http } from '@/lib/http'
import { useAuthStore } from '@/stores/auth'
interface AccountRow {
id: number;
username: string;
display_name: string;
email: string | null;
role: string;
status: string;
last_login_at: string | null;
created_at: string;
updated_at: string;
id: number
username: string
display_name: string
email: string | null
role: string
status: string
last_login_at: string | null
created_at: string
updated_at: string
}
interface ListResult {
items: AccountRow[];
total: number;
page: number;
size: number;
items: AccountRow[]
total: number
page: number
size: number
}
const auth = useAuthStore();
const auth = useAuthStore()
const filter = reactive({
keyword: "",
keyword: '',
status: undefined as string | undefined,
});
})
const statusOptions = [
{ label: "启用", value: "active" },
{ label: "停用", value: "disabled" },
];
{ label: '启用', value: 'active' },
{ label: '停用', value: 'disabled' },
]
const columns = [
{ title: "ID", dataIndex: "id", key: "id", width: 80 },
{ title: "账号", dataIndex: "username", key: "username" },
{ title: "姓名", dataIndex: "display_name", key: "display_name" },
{ title: "邮箱", dataIndex: "email", key: "email" },
{ title: "状态", key: "status", width: 100 },
{ title: "最近登录", key: "last_login_at", width: 180 },
{ title: "创建时间", key: "created_at", width: 180 },
{ title: "操作", key: "actions", width: 200 },
];
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '账号', dataIndex: 'username', key: 'username' },
{ title: '姓名', dataIndex: 'display_name', key: 'display_name' },
{ title: '邮箱', dataIndex: 'email', key: 'email' },
{ title: '状态', key: 'status', width: 100 },
{ title: '最近登录', key: 'last_login_at', width: 180 },
{ title: '创建时间', key: 'created_at', width: 180 },
{ title: '操作', key: 'actions', width: 200 },
]
const rows = ref<AccountRow[]>([]);
const loading = ref(false);
const page = ref(1);
const size = ref(20);
const total = ref(0);
const rows = ref<AccountRow[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(20)
const total = ref(0)
const pagination = computed<TablePaginationConfig>(() => ({
current: page.value,
pageSize: size.value,
total: total.value,
showSizeChanger: true,
pageSizeOptions: ["10", "20", "50", "100"],
}));
pageSizeOptions: ['10', '20', '50', '100'],
}))
let keywordTimer: number | null = null;
let keywordTimer: number | null = null
function onKeywordChange() {
if (keywordTimer) window.clearTimeout(keywordTimer);
if (keywordTimer) window.clearTimeout(keywordTimer)
keywordTimer = window.setTimeout(() => {
page.value = 1;
void reload();
}, 300);
page.value = 1
void reload()
}, 300)
}
async function reload() {
loading.value = true;
loading.value = true
try {
const result = await http.get<ListResult>("/accounts", {
const result = await http.get<ListResult>('/accounts', {
keyword: filter.keyword || undefined,
status: filter.status || undefined,
page: page.value,
size: size.value,
});
rows.value = result.items;
total.value = result.total;
})
rows.value = result.items
total.value = result.total
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
loading.value = false;
loading.value = false
}
}
function onTableChange(pag: TablePaginationConfig) {
page.value = pag.current ?? 1;
size.value = pag.pageSize ?? 20;
void reload();
page.value = pag.current ?? 1
size.value = pag.pageSize ?? 20
void reload()
}
const createOpen = ref(false);
const createLoading = ref(false);
const createOpen = ref(false)
const createLoading = ref(false)
const createForm = reactive({
username: "",
display_name: "",
email: "",
password: "",
});
username: '',
display_name: '',
email: '',
password: '',
})
function resetCreate() {
createForm.username = "";
createForm.display_name = "";
createForm.email = "";
createForm.password = "";
createOpen.value = false;
createForm.username = ''
createForm.display_name = ''
createForm.email = ''
createForm.password = ''
createOpen.value = false
}
function openCreate() {
resetCreate();
createOpen.value = true;
resetCreate()
createOpen.value = true
}
async function submitCreate() {
if (!createForm.username.trim()) {
message.warning("请输入账号");
return;
message.warning('请输入账号')
return
}
if (createForm.password.length < 8) {
message.warning("初始密码至少 8 位");
return;
message.warning('初始密码至少 8 位')
return
}
createLoading.value = true;
createLoading.value = true
try {
await http.post("/accounts", {
await http.post('/accounts', {
username: createForm.username.trim(),
display_name: createForm.display_name.trim() || createForm.username.trim(),
email: createForm.email.trim(),
password: createForm.password,
});
message.success("新建成功");
resetCreate();
void reload();
})
message.success('新建成功')
resetCreate()
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
createLoading.value = false;
createLoading.value = false
}
}
const resetOpen = ref(false);
const resetLoading = ref(false);
const resetTarget = ref<AccountRow | null>(null);
const resetPasswordValue = ref("");
const resetOpen = ref(false)
const resetLoading = ref(false)
const resetTarget = ref<AccountRow | null>(null)
const resetPasswordValue = ref('')
function openResetPassword(row: AccountRow) {
resetTarget.value = row;
resetPasswordValue.value = "";
resetOpen.value = true;
resetTarget.value = row
resetPasswordValue.value = ''
resetOpen.value = true
}
async function submitResetPassword() {
if (!resetTarget.value) return;
if (!resetTarget.value) return
if (resetPasswordValue.value.length < 8) {
message.warning("新密码至少 8 位");
return;
message.warning('新密码至少 8 位')
return
}
resetLoading.value = true;
resetLoading.value = true
try {
await http.post(`/accounts/${resetTarget.value.id}/password`, {
password: resetPasswordValue.value,
});
message.success("重置成功");
resetOpen.value = false;
})
message.success('重置成功')
resetOpen.value = false
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
resetLoading.value = false;
resetLoading.value = false
}
}
async function toggleStatus(row: AccountRow) {
const next = row.status === "active" ? "disabled" : "active";
const next = row.status === 'active' ? 'disabled' : 'active'
try {
await http.post(`/accounts/${row.id}/status`, { status: next });
message.success(next === "active" ? "已启用" : "已停用");
void reload();
await http.post(`/accounts/${row.id}/status`, { status: next })
message.success(next === 'active' ? '已启用' : '已停用')
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
}
}
function formatDate(value: string | null | undefined): string {
return value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "—";
return value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '—'
}
onMounted(() => {
void reload();
});
void reload()
})
</script>
<style scoped>
+301 -262
View File
@@ -43,11 +43,11 @@
{{ record.phone }}
</template>
<template v-else-if="column.key === 'email'">
{{ record.email || "" }}
{{ record.email || '' }}
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 'active' ? 'green' : 'red'">
{{ record.status === "active" ? "启用" : "停用" }}
{{ record.status === 'active' ? '启用' : '停用' }}
</a-tag>
</template>
<template v-else-if="column.key === 'role'">
@@ -66,12 +66,17 @@
<template v-else-if="column.key === 'plan'">
<div class="plan-cell">
<a-space>
<a-tag>{{ record.plan_name || record.plan_code || "—" }}</a-tag>
<a-tag>{{ record.plan_name || record.plan_code || '—' }}</a-tag>
<a-tag :color="record.subscription_status === 'active' ? 'green' : 'default'">
{{ record.subscription_status || "—" }}
{{ record.subscription_status || '—' }}
</a-tag>
</a-space>
<span :class="['plan-cell__expiry', { 'plan-cell__expiry--expired': isExpired(record.subscription_end_at) }]">
<span
:class="[
'plan-cell__expiry',
{ 'plan-cell__expiry--expired': isExpired(record.subscription_end_at) },
]"
>
{{ formatSubscriptionEnd(record.subscription_end_at) }}
</span>
</div>
@@ -86,13 +91,25 @@
<template v-else-if="column.key === 'actions'">
<div class="table-actions-row">
<a-tooltip title="编辑">
<a-button type="text" shape="circle" size="small" class="action-btn action-edit" @click="openEdit(record)">
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-edit"
@click="openEdit(record)"
>
<EditOutlined />
</a-button>
</a-tooltip>
<a-tooltip title="KOL身份">
<a-button type="text" shape="circle" size="small" class="action-btn action-kol" @click="openKol(record)">
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-kol"
@click="openKol(record)"
>
<IdcardOutlined />
</a-button>
</a-tooltip>
@@ -110,7 +127,13 @@
</a-tooltip>
<a-tooltip title="重置密码">
<a-button type="text" shape="circle" size="small" class="action-btn action-key" @click="openResetPassword(record)">
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-key"
@click="openResetPassword(record)"
>
<KeyOutlined />
</a-button>
</a-tooltip>
@@ -120,7 +143,15 @@
:title="record.status === 'active' ? '确认停用该用户?' : '确认启用该用户?'"
@confirm="toggleStatus(record)"
>
<a-button type="text" shape="circle" size="small" :class="['action-btn', record.status === 'active' ? 'action-revoke' : 'action-play']">
<a-button
type="text"
shape="circle"
size="small"
:class="[
'action-btn',
record.status === 'active' ? 'action-revoke' : 'action-play',
]"
>
<StopOutlined v-if="record.status === 'active'" />
<PlayCircleOutlined v-else />
</a-button>
@@ -182,7 +213,11 @@
<a-select v-model:value="editForm.role" :options="roleOptions" />
</a-form-item>
<a-form-item label="套餐" required>
<a-select v-model:value="editForm.plan_code" :options="planOptions" @change="onEditPlanChange" />
<a-select
v-model:value="editForm.plan_code"
:options="planOptions"
@change="onEditPlanChange"
/>
</a-form-item>
<a-form-item label="会员到期日" required>
<a-date-picker
@@ -205,7 +240,11 @@
>
<a-form layout="vertical" :model="kolForm">
<a-form-item label="KOL 身份" required>
<a-switch v-model:checked="kolForm.enabled" checked-children="开通" un-checked-children="停用" />
<a-switch
v-model:checked="kolForm.enabled"
checked-children="开通"
un-checked-children="停用"
/>
</a-form-item>
<a-form-item label="KOL 昵称">
<a-input v-model:value="kolForm.display_name" placeholder="默认使用姓名或手机号" />
@@ -240,482 +279,482 @@
import {
EditOutlined,
IdcardOutlined,
ReloadOutlined,
KeyOutlined,
StopOutlined,
PlayCircleOutlined,
} from "@ant-design/icons-vue";
import type { TableColumnsType, TablePaginationConfig } from "ant-design-vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { computed, onMounted, reactive, ref } from "vue";
ReloadOutlined,
StopOutlined,
} from '@ant-design/icons-vue'
import type { TableColumnsType, TablePaginationConfig } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'
import { OpsApiError, http } from "@/lib/http";
import { OpsApiError, http } from '@/lib/http'
interface AdminUserRow {
id: number;
email: string | null;
phone: string;
name: string | null;
status: string;
tenant_id: number | null;
tenant_name: string | null;
tenant_status: string | null;
tenant_role: string | null;
primary_workspace_id: number | null;
plan_code: string | null;
plan_name: string | null;
subscription_status: string | null;
subscription_end_at: string | null;
kol_profile_id: number | null;
kol_display_name: string | null;
kol_status: string | null;
kol_market_enabled: boolean | null;
created_at: string;
updated_at: string;
id: number
email: string | null
phone: string
name: string | null
status: string
tenant_id: number | null
tenant_name: string | null
tenant_status: string | null
tenant_role: string | null
primary_workspace_id: number | null
plan_code: string | null
plan_name: string | null
subscription_status: string | null
subscription_end_at: string | null
kol_profile_id: number | null
kol_display_name: string | null
kol_status: string | null
kol_market_enabled: boolean | null
created_at: string
updated_at: string
}
interface PlanItem {
id: number;
code: string;
name: string;
status: string;
duration_secs: number;
article_limit: number;
ai_points_monthly: number;
brand_limit: number;
id: number
code: string
name: string
status: string
duration_secs: number
article_limit: number
ai_points_monthly: number
brand_limit: number
}
interface RoleItem {
code: string;
name: string;
description: string;
permissions: string[];
code: string
name: string
description: string
permissions: string[]
}
interface ListResult {
items: AdminUserRow[];
total: number;
page: number;
size: number;
items: AdminUserRow[]
total: number
page: number
size: number
}
interface ResetPlanUsageResult {
user: AdminUserRow;
user: AdminUserRow
reset: {
article_reservations: number;
article_amount: number;
ai_point_reservations: number;
ai_points_amount: number;
ai_point_usage_logs: number;
};
article_reservations: number
article_amount: number
ai_point_reservations: number
ai_points_amount: number
ai_point_usage_logs: number
}
}
const filter = reactive({
keyword: "",
keyword: '',
status: undefined as string | undefined,
});
})
const statusOptions = [
{ label: "启用", value: "active" },
{ label: "停用", value: "disabled" },
];
{ label: '启用', value: 'active' },
{ label: '停用', value: 'disabled' },
]
const columns: TableColumnsType<AdminUserRow> = [
{ title: "用户", key: "identity", width: 180 },
{ title: "手机号", key: "phone", width: 160 },
{ title: "邮箱", key: "email", width: 220 },
{ title: "状态", key: "status", width: 100 },
{ title: "角色", key: "role", width: 120 },
{ title: "套餐", key: "plan", width: 180 },
{ title: "KOL", key: "kol", width: 180 },
{ title: "空间", key: "tenant", width: 100 },
{ title: "创建时间", key: "created_at", width: 180 },
{ title: "操作", key: "actions", width: 300 },
];
{ title: '用户', key: 'identity', width: 180 },
{ title: '手机号', key: 'phone', width: 160 },
{ title: '邮箱', key: 'email', width: 220 },
{ title: '状态', key: 'status', width: 100 },
{ title: '角色', key: 'role', width: 120 },
{ title: '套餐', key: 'plan', width: 180 },
{ title: 'KOL', key: 'kol', width: 180 },
{ title: '空间', key: 'tenant', width: 100 },
{ title: '创建时间', key: 'created_at', width: 180 },
{ title: '操作', key: 'actions', width: 300 },
]
const rows = ref<AdminUserRow[]>([]);
const plans = ref<PlanItem[]>([]);
const roles = ref<RoleItem[]>([]);
const loading = ref(false);
const page = ref(1);
const size = ref(20);
const total = ref(0);
const rows = ref<AdminUserRow[]>([])
const plans = ref<PlanItem[]>([])
const roles = ref<RoleItem[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(20)
const total = ref(0)
const pagination = computed<TablePaginationConfig>(() => ({
current: page.value,
pageSize: size.value,
total: total.value,
showSizeChanger: true,
pageSizeOptions: ["10", "20", "50", "100"],
}));
pageSizeOptions: ['10', '20', '50', '100'],
}))
const planOptions = computed(() =>
plans.value.map((plan) => ({
label: `${plan.name} (${plan.code})`,
value: plan.code,
})),
);
)
const roleOptions = computed(() =>
roles.value.map((role) => ({
label: role.name,
value: role.code,
})),
);
)
let keywordTimer: number | null = null;
let keywordTimer: number | null = null
function onKeywordChange() {
if (keywordTimer) window.clearTimeout(keywordTimer);
if (keywordTimer) window.clearTimeout(keywordTimer)
keywordTimer = window.setTimeout(() => {
page.value = 1;
void reload();
}, 300);
page.value = 1
void reload()
}, 300)
}
async function reload() {
loading.value = true;
loading.value = true
try {
const result = await http.get<ListResult>("/admin-users", {
const result = await http.get<ListResult>('/admin-users', {
keyword: filter.keyword || undefined,
status: filter.status || undefined,
page: page.value,
size: size.value,
});
rows.value = result.items;
total.value = result.total;
})
rows.value = result.items
total.value = result.total
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
loading.value = false;
loading.value = false
}
}
async function loadMeta() {
try {
const [planResult, roleResult] = await Promise.all([
http.get<PlanItem[]>("/plans"),
http.get<RoleItem[]>("/roles"),
]);
plans.value = planResult;
roles.value = roleResult;
http.get<PlanItem[]>('/plans'),
http.get<RoleItem[]>('/roles'),
])
plans.value = planResult
roles.value = roleResult
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
}
}
function onTableChange(pag: TablePaginationConfig) {
page.value = pag.current ?? 1;
size.value = pag.pageSize ?? 20;
void reload();
page.value = pag.current ?? 1
size.value = pag.pageSize ?? 20
void reload()
}
const createOpen = ref(false);
const createLoading = ref(false);
const createOpen = ref(false)
const createLoading = ref(false)
const createForm = reactive({
phone: "",
name: "",
email: "",
password: "",
role: "tenant_admin",
plan_code: "",
});
phone: '',
name: '',
email: '',
password: '',
role: 'tenant_admin',
plan_code: '',
})
function resetCreate() {
createForm.phone = "";
createForm.name = "";
createForm.email = "";
createForm.password = "";
createForm.role = "tenant_admin";
createForm.plan_code = defaultPlanCode();
createOpen.value = false;
createForm.phone = ''
createForm.name = ''
createForm.email = ''
createForm.password = ''
createForm.role = 'tenant_admin'
createForm.plan_code = defaultPlanCode()
createOpen.value = false
}
function openCreate() {
resetCreate();
createOpen.value = true;
resetCreate()
createOpen.value = true
}
async function submitCreate() {
const phone = normalizePhone(createForm.phone);
const phone = normalizePhone(createForm.phone)
if (!phone) {
message.warning("请输入有效手机号");
return;
message.warning('请输入有效手机号')
return
}
if (createForm.password.length < 8) {
message.warning("初始密码至少 8 位");
return;
message.warning('初始密码至少 8 位')
return
}
if (!createForm.role || !createForm.plan_code) {
message.warning("请选择用户角色和套餐");
return;
message.warning('请选择用户角色和套餐')
return
}
createLoading.value = true;
createLoading.value = true
try {
await http.post("/admin-users", {
await http.post('/admin-users', {
phone,
name: createForm.name.trim(),
email: createForm.email.trim(),
password: createForm.password,
role: createForm.role,
plan_code: createForm.plan_code,
});
message.success("新建成功");
resetCreate();
void reload();
})
message.success('新建成功')
resetCreate()
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
createLoading.value = false;
createLoading.value = false
}
}
const editOpen = ref(false);
const editLoading = ref(false);
const editTarget = ref<AdminUserRow | null>(null);
const editOpen = ref(false)
const editLoading = ref(false)
const editTarget = ref<AdminUserRow | null>(null)
const editForm = reactive({
phone: "",
name: "",
email: "",
role: "tenant_admin",
plan_code: "",
subscription_end_date: "",
});
phone: '',
name: '',
email: '',
role: 'tenant_admin',
plan_code: '',
subscription_end_date: '',
})
function openEdit(row: AdminUserRow) {
editTarget.value = row;
editForm.phone = row.phone;
editForm.name = row.name ?? "";
editForm.email = row.email ?? "";
editForm.role = row.tenant_role ?? "tenant_admin";
editForm.plan_code = row.plan_code ?? defaultPlanCode();
editTarget.value = row
editForm.phone = row.phone
editForm.name = row.name ?? ''
editForm.email = row.email ?? ''
editForm.role = row.tenant_role ?? 'tenant_admin'
editForm.plan_code = row.plan_code ?? defaultPlanCode()
editForm.subscription_end_date = row.subscription_end_at
? dayjs(row.subscription_end_at).format("YYYY-MM-DD")
: estimatePlanEndDate(editForm.plan_code);
editOpen.value = true;
? dayjs(row.subscription_end_at).format('YYYY-MM-DD')
: estimatePlanEndDate(editForm.plan_code)
editOpen.value = true
}
function onEditPlanChange(value: unknown) {
if (typeof value === "string") {
editForm.subscription_end_date = estimatePlanEndDate(value);
if (typeof value === 'string') {
editForm.subscription_end_date = estimatePlanEndDate(value)
}
}
async function submitEdit() {
if (!editTarget.value) return;
const phone = normalizePhone(editForm.phone);
if (!editTarget.value) return
const phone = normalizePhone(editForm.phone)
if (!phone) {
message.warning("请输入有效手机号");
return;
message.warning('请输入有效手机号')
return
}
if (!editForm.role || !editForm.plan_code) {
message.warning("请选择用户角色和套餐");
return;
message.warning('请选择用户角色和套餐')
return
}
if (!editForm.subscription_end_date) {
message.warning("请选择会员到期日");
return;
message.warning('请选择会员到期日')
return
}
const originalEndDate = editTarget.value.subscription_end_at
? dayjs(editTarget.value.subscription_end_at).format("YYYY-MM-DD")
: "";
const subscriptionEndAt = dayjs(editForm.subscription_end_date).endOf("day").toISOString();
editLoading.value = true;
? dayjs(editTarget.value.subscription_end_at).format('YYYY-MM-DD')
: ''
const subscriptionEndAt = dayjs(editForm.subscription_end_date).endOf('day').toISOString()
editLoading.value = true
try {
await http.patch(`/admin-users/${editTarget.value.id}`, {
phone,
name: editForm.name.trim(),
email: editForm.email.trim(),
});
})
if (editForm.plan_code !== editTarget.value.plan_code) {
await http.post(`/admin-users/${editTarget.value.id}/plan`, {
plan_code: editForm.plan_code,
});
})
}
if (editForm.role !== editTarget.value.tenant_role) {
await http.post(`/admin-users/${editTarget.value.id}/role`, {
role: editForm.role,
});
})
}
if (editForm.subscription_end_date !== originalEndDate) {
await http.post(`/admin-users/${editTarget.value.id}/subscription-expiry`, {
end_at: subscriptionEndAt,
});
})
}
message.success("用户设置已更新");
editOpen.value = false;
void reload();
message.success('用户设置已更新')
editOpen.value = false
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
editLoading.value = false;
editLoading.value = false
}
}
const resetUsageLoadingId = ref<number | null>(null);
const resetUsageLoadingId = ref<number | null>(null)
async function resetPlanUsage(row: AdminUserRow) {
resetUsageLoadingId.value = row.id;
resetUsageLoadingId.value = row.id
try {
const result = await http.post<ResetPlanUsageResult>(`/admin-users/${row.id}/reset-plan-usage`);
message.success(`已恢复到套餐默认额度:${planQuotaLabel(result.user.plan_code)}`);
rows.value = rows.value.map((item) => (item.id === row.id ? result.user : item));
void reload();
const result = await http.post<ResetPlanUsageResult>(`/admin-users/${row.id}/reset-plan-usage`)
message.success(`已恢复到套餐默认额度:${planQuotaLabel(result.user.plan_code)}`)
rows.value = rows.value.map((item) => (item.id === row.id ? result.user : item))
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
resetUsageLoadingId.value = null;
resetUsageLoadingId.value = null
}
}
const resetOpen = ref(false);
const resetLoading = ref(false);
const resetTarget = ref<AdminUserRow | null>(null);
const resetPasswordValue = ref("");
const resetOpen = ref(false)
const resetLoading = ref(false)
const resetTarget = ref<AdminUserRow | null>(null)
const resetPasswordValue = ref('')
function openResetPassword(row: AdminUserRow) {
resetTarget.value = row;
resetPasswordValue.value = "";
resetOpen.value = true;
resetTarget.value = row
resetPasswordValue.value = ''
resetOpen.value = true
}
async function submitResetPassword() {
if (!resetTarget.value) return;
if (!resetTarget.value) return
if (resetPasswordValue.value.length < 8) {
message.warning("新密码至少 8 位");
return;
message.warning('新密码至少 8 位')
return
}
resetLoading.value = true;
resetLoading.value = true
try {
await http.post(`/admin-users/${resetTarget.value.id}/password`, {
password: resetPasswordValue.value,
});
message.success("密码已重置");
resetOpen.value = false;
})
message.success('密码已重置')
resetOpen.value = false
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
resetLoading.value = false;
resetLoading.value = false
}
}
const kolOpen = ref(false);
const kolLoading = ref(false);
const kolTarget = ref<AdminUserRow | null>(null);
const kolOpen = ref(false)
const kolLoading = ref(false)
const kolTarget = ref<AdminUserRow | null>(null)
const kolForm = reactive({
enabled: false,
display_name: "",
display_name: '',
market_enabled: false,
});
})
function openKol(row: AdminUserRow) {
kolTarget.value = row;
kolForm.enabled = row.kol_status === "active";
kolForm.display_name = row.kol_display_name ?? displayUserName(row);
kolForm.market_enabled = Boolean(row.kol_market_enabled);
kolOpen.value = true;
kolTarget.value = row
kolForm.enabled = row.kol_status === 'active'
kolForm.display_name = row.kol_display_name ?? displayUserName(row)
kolForm.market_enabled = Boolean(row.kol_market_enabled)
kolOpen.value = true
}
async function submitKol() {
if (!kolTarget.value) return;
kolLoading.value = true;
if (!kolTarget.value) return
kolLoading.value = true
try {
await http.post(`/admin-users/${kolTarget.value.id}/kol`, {
enabled: kolForm.enabled,
display_name: kolForm.display_name.trim(),
market_enabled: kolForm.enabled ? kolForm.market_enabled : false,
});
message.success("KOL 身份已更新");
kolOpen.value = false;
void reload();
})
message.success('KOL 身份已更新')
kolOpen.value = false
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
kolLoading.value = false;
kolLoading.value = false
}
}
async function toggleStatus(row: AdminUserRow) {
const next = row.status === "active" ? "disabled" : "active";
const next = row.status === 'active' ? 'disabled' : 'active'
try {
await http.post(`/admin-users/${row.id}/status`, { status: next });
message.success(next === "active" ? "已启用" : "已停用");
void reload();
await http.post(`/admin-users/${row.id}/status`, { status: next })
message.success(next === 'active' ? '已启用' : '已停用')
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
}
}
function normalizePhone(value: string): string {
const phone = value.trim().replace(/[\s-]/g, "");
return /^\+?\d{6,20}$/.test(phone) ? phone : "";
const phone = value.trim().replace(/[\s-]/g, '')
return /^\+?\d{6,20}$/.test(phone) ? phone : ''
}
function displayUserName(row: AdminUserRow): string {
return row.name || row.phone || row.email || `#${row.id}`;
return row.name || row.phone || row.email || `#${row.id}`
}
function defaultPlanCode(): string {
return plans.value[0]?.code ?? "free";
return plans.value[0]?.code ?? 'free'
}
function planQuotaLabel(planCode: string | null): string {
const plan = plans.value.find((item) => item.code === planCode);
if (!plan) return "文章和 AI 点数按当前套餐默认值重置";
return `文章 ${plan.article_limit} 次,AI 点数 ${plan.ai_points_monthly}`;
const plan = plans.value.find((item) => item.code === planCode)
if (!plan) return '文章和 AI 点数按当前套餐默认值重置'
return `文章 ${plan.article_limit} 次,AI 点数 ${plan.ai_points_monthly}`
}
function estimatePlanEndDate(planCode: string): string {
const durationSecs = plans.value.find((plan) => plan.code === planCode)?.duration_secs;
const durationSecs = plans.value.find((plan) => plan.code === planCode)?.duration_secs
if (!durationSecs || durationSecs <= 0) {
return dayjs().format("YYYY-MM-DD");
return dayjs().format('YYYY-MM-DD')
}
return dayjs().add(durationSecs, "second").format("YYYY-MM-DD");
return dayjs().add(durationSecs, 'second').format('YYYY-MM-DD')
}
function roleLabel(role: string | null): string {
return roles.value.find((item) => item.code === role)?.name ?? role ?? "—";
return roles.value.find((item) => item.code === role)?.name ?? role ?? '—'
}
function roleColor(role: string | null): string {
if (role === "tenant_admin") return "blue";
if (role === "editor") return "purple";
if (role === "viewer") return "default";
return "default";
if (role === 'tenant_admin') return 'blue'
if (role === 'editor') return 'purple'
if (role === 'viewer') return 'default'
return 'default'
}
function kolLabel(status: string | null): string {
if (status === "active") return "已开通";
if (status === "suspended") return "已停用";
if (status === "closed") return "已关闭";
return "未开通";
if (status === 'active') return '已开通'
if (status === 'suspended') return '已停用'
if (status === 'closed') return '已关闭'
return '未开通'
}
function kolColor(status: string | null): string {
if (status === "active") return "gold";
if (status === "suspended") return "default";
if (status === "closed") return "red";
return "default";
if (status === 'active') return 'gold'
if (status === 'suspended') return 'default'
if (status === 'closed') return 'red'
return 'default'
}
function formatSubscriptionEnd(value: string | null): string {
if (!value) return "到期:—";
return `到期:${dayjs(value).format("YYYY-MM-DD")}`;
if (!value) return '到期:—'
return `到期:${dayjs(value).format('YYYY-MM-DD')}`
}
function isExpired(value: string | null): boolean {
return Boolean(value && dayjs(value).isBefore(dayjs()));
return Boolean(value && dayjs(value).isBefore(dayjs()))
}
function formatDate(value: string): string {
return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
}
onMounted(() => {
void loadMeta();
void reload();
});
void loadMeta()
void reload()
})
</script>
<style scoped>
+73 -78
View File
@@ -17,12 +17,7 @@
allow-clear
@press-enter="reload"
/>
<a-range-picker
v-model:value="dateRange"
show-time
style="width: 360px"
@change="reload"
/>
<a-range-picker v-model:value="dateRange" show-time style="width: 360px" @change="reload" />
<a-button @click="reload">刷新</a-button>
</div>
@@ -45,7 +40,7 @@
</template>
<template v-else-if="column.key === 'operator'">
<template v-if="record.operator_id">
<span>{{ record.operator_name || "—" }}</span>
<span>{{ record.operator_name || '—' }}</span>
<span style="color: #94a3b8; margin-left: 6px">#{{ record.operator_id }}</span>
</template>
<span v-else style="color: #94a3b8">系统</span>
@@ -53,7 +48,7 @@
<template v-else-if="column.key === 'target'">
<span v-if="record.target_type">
{{ record.target_type }}
<template v-if="record.target_id"> #{{ record.target_id }}</template>
<template v-if="record.target_id">#{{ record.target_id }}</template>
</span>
<span v-else style="color: #94a3b8"></span>
</template>
@@ -78,136 +73,136 @@
</template>
<script setup lang="ts">
import type { TablePaginationConfig } from "ant-design-vue";
import { message } from "ant-design-vue";
import dayjs, { type Dayjs } from "dayjs";
import { computed, onMounted, reactive, ref, watch } from "vue";
import type { TablePaginationConfig } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import dayjs, { type Dayjs } from 'dayjs'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { OpsApiError, http } from "@/lib/http";
import { OpsApiError, http } from '@/lib/http'
interface AuditRow {
id: number;
operator_id: number | null;
operator_name: string | null;
action: string;
target_type: string | null;
target_id: string | null;
metadata: Record<string, unknown> | null;
ip: string | null;
ip_region: string | null;
user_agent: string | null;
request_id: string | null;
created_at: string;
id: number
operator_id: number | null
operator_name: string | null
action: string
target_type: string | null
target_id: string | null
metadata: Record<string, unknown> | null
ip: string | null
ip_region: string | null
user_agent: string | null
request_id: string | null
created_at: string
}
interface ListResult {
items: AuditRow[];
total: number;
page: number;
size: number;
items: AuditRow[]
total: number
page: number
size: number
}
const filter = reactive({
action: "",
});
const operatorIdInput = ref<string>("");
const dateRange = ref<[Dayjs, Dayjs] | null>(null);
action: '',
})
const operatorIdInput = ref<string>('')
const dateRange = ref<[Dayjs, Dayjs] | null>(null)
const columns = [
{ title: "时间", key: "created_at", width: 180 },
{ title: "操作员", key: "operator", width: 200 },
{ title: "动作", key: "action", width: 220 },
{ title: "对象", key: "target", width: 200 },
{ title: "元数据", key: "metadata" },
{ title: "IP", key: "ip", width: 220 },
];
{ title: '时间', key: 'created_at', width: 180 },
{ title: '操作员', key: 'operator', width: 200 },
{ title: '动作', key: 'action', width: 220 },
{ title: '对象', key: 'target', width: 200 },
{ title: '元数据', key: 'metadata' },
{ title: 'IP', key: 'ip', width: 220 },
]
const rows = ref<AuditRow[]>([]);
const loading = ref(false);
const page = ref(1);
const size = ref(50);
const total = ref(0);
const rows = ref<AuditRow[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(50)
const total = ref(0)
const pagination = computed<TablePaginationConfig>(() => ({
current: page.value,
pageSize: size.value,
total: total.value,
showSizeChanger: true,
pageSizeOptions: ["20", "50", "100", "200"],
}));
pageSizeOptions: ['20', '50', '100', '200'],
}))
watch(operatorIdInput, () => {
// user typing — no auto-load, wait for Enter or refresh
});
})
async function reload() {
loading.value = true;
loading.value = true
try {
const params: Record<string, unknown> = {
page: page.value,
size: size.value,
};
if (filter.action.trim()) params.action = filter.action.trim();
}
if (filter.action.trim()) params.action = filter.action.trim()
if (operatorIdInput.value.trim()) {
const id = Number(operatorIdInput.value.trim());
const id = Number(operatorIdInput.value.trim())
if (!Number.isFinite(id) || id <= 0) {
message.warning("操作员 ID 必须是正整数");
loading.value = false;
return;
message.warning('操作员 ID 必须是正整数')
loading.value = false
return
}
params.operator_id = id;
params.operator_id = id
}
if (dateRange.value) {
params.start_at = dateRange.value[0].toISOString();
params.end_at = dateRange.value[1].toISOString();
params.start_at = dateRange.value[0].toISOString()
params.end_at = dateRange.value[1].toISOString()
}
const result = await http.get<ListResult>("/audits", params);
rows.value = result.items;
total.value = result.total;
const result = await http.get<ListResult>('/audits', params)
rows.value = result.items
total.value = result.total
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
loading.value = false;
loading.value = false
}
}
function onTableChange(pag: TablePaginationConfig) {
page.value = pag.current ?? 1;
size.value = pag.pageSize ?? 50;
void reload();
page.value = pag.current ?? 1
size.value = pag.pageSize ?? 50
void reload()
}
function formatDate(value: string): string {
return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
}
function formatMetadata(meta: Record<string, unknown>): string {
try {
return JSON.stringify(meta);
return JSON.stringify(meta)
} catch {
return String(meta);
return String(meta)
}
}
function formatIPRegion(region: string): string {
const parts = region
.split("|")
.split('|')
.map((part) => part.trim())
.filter((part) => part && part !== "0");
return parts.length > 0 ? parts.join(" / ") : region;
.filter((part) => part && part !== '0')
return parts.length > 0 ? parts.join(' / ') : region
}
function resolveActionColor(action: string): string {
if (action.endsWith(".failure") || action.includes("disable")) return "red";
if (action.endsWith(".success") || action.includes("create")) return "green";
if (action.includes("password") || action.includes("update")) return "orange";
return "blue";
if (action.endsWith('.failure') || action.includes('disable')) return 'red'
if (action.endsWith('.success') || action.includes('create')) return 'green'
if (action.includes('password') || action.includes('update')) return 'orange'
return 'blue'
}
onMounted(() => {
void reload();
});
void reload()
})
</script>
<style scoped>
+199 -189
View File
@@ -42,7 +42,7 @@
<div class="primary-cell">
<strong>{{ record.tenant_name }}</strong>
<span>
{{ record.subscriber_phone ? `手机 ${record.subscriber_phone}` : "手机号 —" }}
{{ record.subscriber_phone ? `手机 ${record.subscriber_phone}` : '手机号 —' }}
· 租户 #{{ record.tenant_id }} · 申请 #{{ record.id }}
</span>
</div>
@@ -56,7 +56,7 @@
<template v-else-if="column.key === 'creator'">
<div class="creator-cell">
<a-avatar :src="record.kol_avatar_url || undefined" size="small">
{{ record.kol_display_name.charAt(0) || "K" }}
{{ record.kol_display_name.charAt(0) || 'K' }}
</a-avatar>
<div class="primary-cell">
<strong>{{ record.kol_display_name }}</strong>
@@ -83,7 +83,7 @@
<template v-else-if="column.key === 'period'">
<div class="period-cell">
<span>开始{{ formatOptionalDate(record.start_at) }}</span>
<span>到期{{ formatOptionalDate(record.end_at, "永不过期") }}</span>
<span>到期{{ formatOptionalDate(record.end_at, '永不过期') }}</span>
</div>
</template>
<template v-else-if="column.key === 'created_at'">
@@ -103,23 +103,26 @@
</a-button>
</a-tooltip>
<a-tooltip v-if="record.status === 'pending' || record.status === 'active'" title="撤销订阅">
<a-tooltip
v-if="record.status === 'pending' || record.status === 'active'"
title="撤销订阅"
>
<a-popconfirm
title="确认撤销该订阅?撤销后订阅方将无法使用包内 Prompt。"
:ok-button-props="{ danger: true, loading: revokeLoadingId === record.id }"
@confirm="revoke(record)"
>
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-revoke"
>
<a-button type="text" shape="circle" size="small" class="action-btn action-revoke">
<StopOutlined />
</a-button>
</a-popconfirm>
</a-tooltip>
<span v-if="record.status !== 'pending' && record.status !== 'active'" class="muted-text">无操作</span>
<span
v-if="record.status !== 'pending' && record.status !== 'active'"
class="muted-text"
>
无操作
</span>
</div>
</template>
</template>
@@ -194,16 +197,21 @@
<div v-if="selectedPackage" class="manual-bind-preview">
<div class="creator-cell">
<a-avatar :src="selectedPackage.kol_avatar_url || undefined" size="small">
{{ selectedPackage.kol_display_name.charAt(0) || "K" }}
{{ selectedPackage.kol_display_name.charAt(0) || 'K' }}
</a-avatar>
<div class="primary-cell">
<strong>{{ selectedPackage.name }}</strong>
<span>{{ selectedPackage.kol_display_name }} · {{ selectedPackage.creator_tenant_name }}</span>
<span>
{{ selectedPackage.kol_display_name }} · {{ selectedPackage.creator_tenant_name }}
</span>
</div>
</div>
<a-tag color="blue">{{ selectedPackage.prompt_count }} Prompt</a-tag>
</div>
<a-form-item label="授权有效期" help="留空表示不过期;如果该用户已有待审批/已通过记录,会更新为这里选择的有效期。">
<a-form-item
label="授权有效期"
help="留空表示不过期;如果该用户已有待审批/已通过记录,会更新为这里选择的有效期。"
>
<a-date-picker
v-model:value="manualBindForm.end_date"
class="approve-date-picker"
@@ -218,311 +226,313 @@
</template>
<script setup lang="ts">
import { PlusOutlined, CheckOutlined, StopOutlined } from "@ant-design/icons-vue";
import type { TableColumnsType, TablePaginationConfig } from "ant-design-vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { computed, onMounted, reactive, ref } from "vue";
import { CheckOutlined, PlusOutlined, StopOutlined } from '@ant-design/icons-vue'
import type { TableColumnsType, TablePaginationConfig } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'
import { OpsApiError, http } from "@/lib/http";
import { OpsApiError, http } from '@/lib/http'
interface KolSubscriptionRow {
id: number;
tenant_id: number;
tenant_name: string;
subscriber_name: string | null;
subscriber_phone: string | null;
package_id: number;
package_name: string;
package_status: string;
creator_tenant_id: number;
creator_tenant_name: string;
kol_profile_id: number;
kol_display_name: string;
kol_avatar_url: string | null;
status: string;
prompt_count: number;
access_prompt_count: number;
start_at: string | null;
end_at: string | null;
created_at: string;
updated_at: string;
id: number
tenant_id: number
tenant_name: string
subscriber_name: string | null
subscriber_phone: string | null
package_id: number
package_name: string
package_status: string
creator_tenant_id: number
creator_tenant_name: string
kol_profile_id: number
kol_display_name: string
kol_avatar_url: string | null
status: string
prompt_count: number
access_prompt_count: number
start_at: string | null
end_at: string | null
created_at: string
updated_at: string
}
interface ListResult {
items: KolSubscriptionRow[];
total: number;
page: number;
size: number;
items: KolSubscriptionRow[]
total: number
page: number
size: number
}
interface KolPackageOption {
id: number;
name: string;
status: string;
creator_tenant_id: number;
creator_tenant_name: string;
kol_profile_id: number;
kol_display_name: string;
kol_avatar_url: string | null;
prompt_count: number;
created_at: string;
updated_at: string;
id: number
name: string
status: string
creator_tenant_id: number
creator_tenant_name: string
kol_profile_id: number
kol_display_name: string
kol_avatar_url: string | null
prompt_count: number
created_at: string
updated_at: string
}
const filter = reactive({
keyword: "",
status: "pending" as string | undefined,
});
keyword: '',
status: 'pending' as string | undefined,
})
const statusOptions = [
{ label: "审核中", value: "pending" },
{ label: "已通过", value: "active" },
{ label: "已撤销", value: "revoked" },
{ label: "已过期", value: "expired" },
];
{ label: '审核中', value: 'pending' },
{ label: '已通过', value: 'active' },
{ label: '已撤销', value: 'revoked' },
{ label: '已过期', value: 'expired' },
]
const columns: TableColumnsType<KolSubscriptionRow> = [
{ title: "申请租户", key: "subscriber", width: 220 },
{ title: "订阅包", key: "package", width: 220 },
{ title: "KOL", key: "creator", width: 260 },
{ title: "状态", key: "status", width: 130 },
{ title: "授权 Prompt", key: "prompts", width: 130 },
{ title: "有效期", key: "period", width: 210 },
{ title: "申请时间", key: "created_at", width: 180 },
{ title: "操作", key: "actions", width: 120 },
];
{ title: '申请租户', key: 'subscriber', width: 220 },
{ title: '订阅包', key: 'package', width: 220 },
{ title: 'KOL', key: 'creator', width: 260 },
{ title: '状态', key: 'status', width: 130 },
{ title: '授权 Prompt', key: 'prompts', width: 130 },
{ title: '有效期', key: 'period', width: 210 },
{ title: '申请时间', key: 'created_at', width: 180 },
{ title: '操作', key: 'actions', width: 120 },
]
const rows = ref<KolSubscriptionRow[]>([]);
const packageRows = ref<KolPackageOption[]>([]);
const loading = ref(false);
const packageLoading = ref(false);
const page = ref(1);
const size = ref(20);
const total = ref(0);
const rows = ref<KolSubscriptionRow[]>([])
const packageRows = ref<KolPackageOption[]>([])
const loading = ref(false)
const packageLoading = ref(false)
const page = ref(1)
const size = ref(20)
const total = ref(0)
const pagination = computed<TablePaginationConfig>(() => ({
current: page.value,
pageSize: size.value,
total: total.value,
showSizeChanger: true,
pageSizeOptions: ["10", "20", "50", "100"],
}));
pageSizeOptions: ['10', '20', '50', '100'],
}))
const pendingRowsCount = computed(() => rows.value.filter((row) => row.status === "pending").length);
const pendingRowsCount = computed(() => rows.value.filter((row) => row.status === 'pending').length)
const packageOptions = computed(() =>
packageRows.value.map((item) => ({
label: `${item.name} · ${item.kol_display_name} · ${item.prompt_count} 个 Prompt`,
value: item.id,
})),
);
)
let keywordTimer: number | null = null;
let packageSearchTimer: number | null = null;
let keywordTimer: number | null = null
let packageSearchTimer: number | null = null
function onKeywordChange() {
if (keywordTimer) window.clearTimeout(keywordTimer);
if (keywordTimer) window.clearTimeout(keywordTimer)
keywordTimer = window.setTimeout(() => {
page.value = 1;
void reload();
}, 300);
page.value = 1
void reload()
}, 300)
}
async function reload() {
loading.value = true;
loading.value = true
try {
const result = await http.get<ListResult>("/kol/subscriptions", {
const result = await http.get<ListResult>('/kol/subscriptions', {
keyword: filter.keyword || undefined,
status: filter.status || undefined,
page: page.value,
size: size.value,
});
rows.value = result.items;
total.value = result.total;
})
rows.value = result.items
total.value = result.total
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
loading.value = false;
loading.value = false
}
}
async function loadPackages(keyword = "") {
packageLoading.value = true;
async function loadPackages(keyword = '') {
packageLoading.value = true
try {
packageRows.value = await http.get<KolPackageOption[]>("/kol/packages", {
packageRows.value = await http.get<KolPackageOption[]>('/kol/packages', {
keyword: keyword || undefined,
size: 50,
});
})
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
packageLoading.value = false;
packageLoading.value = false
}
}
function onPackageSearch(value: string) {
if (packageSearchTimer) window.clearTimeout(packageSearchTimer);
if (packageSearchTimer) window.clearTimeout(packageSearchTimer)
packageSearchTimer = window.setTimeout(() => {
void loadPackages(value.trim());
}, 300);
void loadPackages(value.trim())
}, 300)
}
function onTableChange(pag: TablePaginationConfig) {
page.value = pag.current ?? 1;
size.value = pag.pageSize ?? 20;
void reload();
page.value = pag.current ?? 1
size.value = pag.pageSize ?? 20
void reload()
}
const manualBindOpen = ref(false);
const manualBindLoading = ref(false);
const manualBindOpen = ref(false)
const manualBindLoading = ref(false)
const manualBindForm = reactive({
phone: "",
phone: '',
package_id: undefined as number | undefined,
end_date: undefined as string | undefined,
});
})
const selectedPackage = computed(() =>
packageRows.value.find((item) => item.id === manualBindForm.package_id) ?? null,
);
const selectedPackage = computed(
() => packageRows.value.find((item) => item.id === manualBindForm.package_id) ?? null,
)
function resetManualBind() {
manualBindForm.phone = "";
manualBindForm.package_id = undefined;
manualBindForm.end_date = undefined;
manualBindForm.phone = ''
manualBindForm.package_id = undefined
manualBindForm.end_date = undefined
}
function openManualBind() {
resetManualBind();
manualBindOpen.value = true;
void loadPackages();
resetManualBind()
manualBindOpen.value = true
void loadPackages()
}
async function submitManualBind() {
const phone = normalizePhone(manualBindForm.phone);
const phone = normalizePhone(manualBindForm.phone)
if (!phone) {
message.warning("请输入有效手机号");
return;
message.warning('请输入有效手机号')
return
}
if (!manualBindForm.package_id) {
message.warning("请选择精调模板包");
return;
message.warning('请选择精调模板包')
return
}
if (manualBindForm.end_date && dayjs(manualBindForm.end_date).endOf("day").isBefore(dayjs())) {
message.warning("有效期不能早于今天");
return;
if (manualBindForm.end_date && dayjs(manualBindForm.end_date).endOf('day').isBefore(dayjs())) {
message.warning('有效期不能早于今天')
return
}
manualBindLoading.value = true;
manualBindLoading.value = true
try {
const result = await http.post<KolSubscriptionRow>("/kol/subscriptions/manual-bind", {
const result = await http.post<KolSubscriptionRow>('/kol/subscriptions/manual-bind', {
phone,
package_id: manualBindForm.package_id,
end_at: manualBindForm.end_date ? dayjs(manualBindForm.end_date).endOf("day").toISOString() : null,
});
message.success(`已为 ${phone} 绑定「${result.package_name}`);
manualBindOpen.value = false;
filter.keyword = phone;
filter.status = "active";
page.value = 1;
void reload();
end_at: manualBindForm.end_date
? dayjs(manualBindForm.end_date).endOf('day').toISOString()
: null,
})
message.success(`已为 ${phone} 绑定「${result.package_name}`)
manualBindOpen.value = false
filter.keyword = phone
filter.status = 'active'
page.value = 1
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
manualBindLoading.value = false;
manualBindLoading.value = false
}
}
const approveOpen = ref(false);
const approveLoading = ref(false);
const approveTarget = ref<KolSubscriptionRow | null>(null);
const approveOpen = ref(false)
const approveLoading = ref(false)
const approveTarget = ref<KolSubscriptionRow | null>(null)
const approveForm = reactive({
end_date: undefined as string | undefined,
});
})
function openApprove(row: KolSubscriptionRow) {
approveTarget.value = row;
approveForm.end_date = undefined;
approveOpen.value = true;
approveTarget.value = row
approveForm.end_date = undefined
approveOpen.value = true
}
async function submitApprove() {
if (!approveTarget.value) return;
if (approveForm.end_date && dayjs(approveForm.end_date).endOf("day").isBefore(dayjs())) {
message.warning("有效期不能早于今天");
return;
if (!approveTarget.value) return
if (approveForm.end_date && dayjs(approveForm.end_date).endOf('day').isBefore(dayjs())) {
message.warning('有效期不能早于今天')
return
}
approveLoading.value = true;
approveLoading.value = true
try {
await http.post<KolSubscriptionRow>(`/kol/subscriptions/${approveTarget.value.id}/approve`, {
end_at: approveForm.end_date ? dayjs(approveForm.end_date).endOf("day").toISOString() : null,
});
message.success("订阅已通过,Prompt 权限已发放");
approveOpen.value = false;
void reload();
end_at: approveForm.end_date ? dayjs(approveForm.end_date).endOf('day').toISOString() : null,
})
message.success('订阅已通过,Prompt 权限已发放')
approveOpen.value = false
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
approveLoading.value = false;
approveLoading.value = false
}
}
const revokeLoadingId = ref<number | null>(null);
const revokeLoadingId = ref<number | null>(null)
async function revoke(row: KolSubscriptionRow) {
revokeLoadingId.value = row.id;
revokeLoadingId.value = row.id
try {
await http.post<KolSubscriptionRow>(`/kol/subscriptions/${row.id}/revoke`);
message.success("订阅已撤销");
void reload();
await http.post<KolSubscriptionRow>(`/kol/subscriptions/${row.id}/revoke`)
message.success('订阅已撤销')
void reload()
} catch (error) {
if (error instanceof OpsApiError) message.error(error.detail || error.message);
if (error instanceof OpsApiError) message.error(error.detail || error.message)
} finally {
revokeLoadingId.value = null;
revokeLoadingId.value = null
}
}
function statusLabel(status: string): string {
if (status === "pending") return "审核中";
if (status === "active") return "已通过";
if (status === "revoked") return "已撤销";
if (status === "expired") return "已过期";
return status;
if (status === 'pending') return '审核中'
if (status === 'active') return '已通过'
if (status === 'revoked') return '已撤销'
if (status === 'expired') return '已过期'
return status
}
function statusColor(status: string): string {
if (status === "pending") return "orange";
if (status === "active") return "green";
if (status === "revoked") return "red";
if (status === "expired") return "default";
return "default";
if (status === 'pending') return 'orange'
if (status === 'active') return 'green'
if (status === 'revoked') return 'red'
if (status === 'expired') return 'default'
return 'default'
}
function packageStatusLabel(status: string): string {
if (status === "published") return "已发布";
if (status === "draft") return "草稿";
if (status === "archived") return "已归档";
return status;
if (status === 'published') return '已发布'
if (status === 'draft') return '草稿'
if (status === 'archived') return '已归档'
return status
}
function normalizePhone(value: string): string {
const phone = value.trim().replace(/[\s-]/g, "");
return /^\+?\d{6,20}$/.test(phone) ? phone : "";
const phone = value.trim().replace(/[\s-]/g, '')
return /^\+?\d{6,20}$/.test(phone) ? phone : ''
}
function formatOptionalDate(value: string | null, empty = "—"): string {
if (!value) return empty;
return dayjs(value).format("YYYY-MM-DD");
function formatOptionalDate(value: string | null, empty = '—'): string {
if (!value) return empty
return dayjs(value).format('YYYY-MM-DD')
}
function formatDate(value: string): string {
return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
}
onMounted(() => {
void reload();
});
void reload()
})
</script>
<style scoped>
+298 -103
View File
@@ -1,6 +1,11 @@
<template>
<div class="page">
<div class="left" :style="{ background: `linear-gradient(135deg, ${primaryColor}e6, ${primaryColor}, ${primaryColor}cc)` }">
<div
class="left"
:style="{
background: `linear-gradient(135deg, ${primaryColor}e6, ${primaryColor}, ${primaryColor}cc)`,
}"
>
<div class="brand">
<div class="brand-icon"><StarOutlined :style="{ fontSize: '16px' }" /></div>
<span>省心推运营控制台</span>
@@ -31,17 +36,30 @@
<h1>欢迎回来</h1>
<p>运营管理系统 · 仅限授权人员登录</p>
</div>
<form @submit.prevent="handleSubmit" class="form">
<form class="form" @submit.prevent="handleSubmit">
<div class="field">
<label for="login-username">管理员账号</label>
<input id="login-username" type="text" placeholder="请输入管理员账号" v-model="formState.username"
autocomplete="off" @focus="isTyping = true" @blur="isTyping = false" required />
<input
id="login-username"
v-model="formState.username"
type="text"
placeholder="请输入管理员账号"
autocomplete="off"
required
@focus="isTyping = true"
@blur="isTyping = false"
/>
</div>
<div class="field">
<label for="login-password">密码</label>
<div class="password-wrap">
<input id="login-password" :type="showPassword ? 'text' : 'password'"
placeholder="请输入密码" v-model="formState.password" required />
<input
id="login-password"
v-model="formState.password"
:type="showPassword ? 'text' : 'password'"
placeholder="请输入密码"
required
/>
<button type="button" class="eye-btn" @click="showPassword = !showPassword">
<EyeInvisibleOutlined v-if="showPassword" />
<EyeOutlined v-else />
@@ -49,20 +67,31 @@
</div>
</div>
<div class="options">
<label class="remember"><input type="checkbox" v-model="remember" /> 记住登录状态</label>
<label class="remember">
<input v-model="remember" type="checkbox" />
记住登录状态
</label>
</div>
<transition name="fade">
<div v-if="errorMessage" class="error-message">
<svg class="error-icon" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
<path
fill-rule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
clip-rule="evenodd"
/>
</svg>
{{ errorMessage }}
</div>
</transition>
<button type="submit" class="btn-primary" :disabled="submitting"
:style="{ background: primaryColor }">
<button
type="submit"
class="btn-primary"
:disabled="submitting"
:style="{ background: primaryColor }"
>
{{ submitting ? '登录中...' : '登录系统' }}
</button>
</form>
@@ -72,140 +101,278 @@
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { StarOutlined, EyeOutlined, EyeInvisibleOutlined } from "@ant-design/icons-vue";
import { EyeInvisibleOutlined, EyeOutlined, StarOutlined } from '@ant-design/icons-vue'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { OpsApiError } from "@/lib/http";
import { readLoginPreference } from "@/lib/storage";
import { useAuthStore } from "@/stores/auth";
import AnimatedCharacters from "@/components/login-animation/AnimatedCharacters.vue";
import AnimatedCharacters from '@/components/login-animation/AnimatedCharacters.vue'
import { OpsApiError } from '@/lib/http'
import { readLoginPreference } from '@/lib/storage'
import { useAuthStore } from '@/stores/auth'
const authStore = useAuthStore();
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore()
const router = useRouter()
const route = useRoute()
const primaryColor = ref('#4f46e5');
const primaryColor = ref('#4f46e5')
const submitting = ref(false);
const showPassword = ref(false);
const isTyping = ref(false);
const remember = ref(true);
const errorMessage = ref<string | null>(null);
const submitting = ref(false)
const showPassword = ref(false)
const isTyping = ref(false)
const remember = ref(true)
const errorMessage = ref<string | null>(null)
const formState = reactive({
username: "",
password: "",
});
username: '',
password: '',
})
onMounted(() => {
const pref = readLoginPreference();
remember.value = pref.remember;
const pref = readLoginPreference()
remember.value = pref.remember
if (pref.lastUsername) {
formState.username = pref.lastUsername;
formState.username = pref.lastUsername
}
});
})
function formatLoginError(error: unknown): string {
if (error instanceof OpsApiError) {
const messages: Record<string, string> = {
invalid_credentials: "账号或密码错误",
account_disabled: "账号已停用",
login_rate_limited: "登录请求过于频繁",
login_locked: "登录已被临时保护",
login_in_progress: "登录请求正在处理中",
login_guard_unavailable: "登录保护暂时不可用",
};
const message = messages[error.message] ?? error.message;
return error.detail ? `${message}${error.detail}` : message;
invalid_credentials: '账号或密码错误',
account_disabled: '账号已停用',
login_rate_limited: '登录请求过于频繁',
login_locked: '登录已被临时保护',
login_in_progress: '登录请求正在处理中',
login_guard_unavailable: '登录保护暂时不可用',
}
const message = messages[error.message] ?? error.message
return error.detail ? `${message}${error.detail}` : message
}
if (error instanceof Error) {
return error.message;
return error.message
}
return "登录失败,请稍后重试";
return '登录失败,请稍后重试'
}
async function handleSubmit(): Promise<void> {
if (submitting.value) {
return;
return
}
errorMessage.value = null;
errorMessage.value = null
if (!formState.username.trim() || !formState.password) {
errorMessage.value = "请输入账号和密码";
return;
errorMessage.value = '请输入账号和密码'
return
}
submitting.value = true;
submitting.value = true
try {
await authStore.login(formState.username.trim(), formState.password, remember.value);
const redirect = typeof route.query.redirect === "string" ? route.query.redirect : "/admin-users";
await router.replace(redirect);
await authStore.login(formState.username.trim(), formState.password, remember.value)
const redirect =
typeof route.query.redirect === 'string' ? route.query.redirect : '/admin-users'
await router.replace(redirect)
} catch (error) {
errorMessage.value = formatLoginError(error);
errorMessage.value = formatLoginError(error)
} finally {
submitting.value = false;
submitting.value = false
}
}
</script>
<style scoped>
.page {
display: grid;
grid-template-columns: 1fr 1fr;
min-height: 100vh;
.page {
display: grid;
grid-template-columns: 1fr 1fr;
min-height: 100vh;
width: 100%;
flex: 1;
}
.left {
position: relative; display: flex; flex-direction: column; justify-content: space-between;
padding: 48px; color: white; overflow: hidden;
position: relative;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 48px;
color: white;
overflow: hidden;
}
.brand {
position: relative;
z-index: 20;
display: flex;
align-items: center;
gap: 8px;
font-size: 18px;
font-weight: 600;
}
.brand { position: relative; z-index: 20; display: flex; align-items: center; gap: 8px; font-size: 18px; font-weight: 600; }
.brand-icon {
width: 32px; height: 32px; border-radius: 8px; background: rgba(255,255,255,0.1);
backdrop-filter: blur(8px); display: flex; align-items: center; justify-content: center;
width: 32px;
height: 32px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(8px);
display: flex;
align-items: center;
justify-content: center;
}
.characters-area {
position: relative;
z-index: 20;
display: flex;
align-items: flex-end;
justify-content: center;
height: 500px;
transform: scale(0.95);
}
.footer-links {
position: relative;
z-index: 20;
display: flex;
gap: 32px;
font-size: 14px;
}
.footer-links a {
color: rgba(255, 255, 255, 0.6);
transition: color 0.2s;
}
.footer-links a:hover {
color: white;
}
.characters-area { position: relative; z-index: 20; display: flex; align-items: flex-end; justify-content: center; height: 500px; transform: scale(0.95); }
.footer-links { position: relative; z-index: 20; display: flex; gap: 32px; font-size: 14px; }
.footer-links a { color: rgba(255,255,255,0.6); transition: color 0.2s; }
.footer-links a:hover { color: white; }
.deco-grid {
position: absolute; inset: 0;
background-image: linear-gradient(to right, rgba(255,255,255,0.05) 1px, transparent 1px),
linear-gradient(to bottom, rgba(255,255,255,0.05) 1px, transparent 1px);
position: absolute;
inset: 0;
background-image:
linear-gradient(to right, rgba(255, 255, 255, 0.05) 1px, transparent 1px),
linear-gradient(to bottom, rgba(255, 255, 255, 0.05) 1px, transparent 1px);
background-size: 20px 20px;
}
.deco-circle { position: absolute; border-radius: 50%; filter: blur(48px); }
.deco-circle-1 { top: 25%; right: 25%; width: 256px; height: 256px; background: rgba(255,255,255,0.1); }
.deco-circle-2 { bottom: 25%; left: 25%; width: 384px; height: 384px; background: rgba(255,255,255,0.05); }
.right { display: flex; align-items: center; justify-content: center; padding: 32px; background: #fff; }
.form-wrapper { width: 100%; max-width: 420px; }
.mobile-brand { display: none; }
.header { text-align: left; margin-bottom: 40px; }
.header h1 { font-size: 30px; font-weight: 700; letter-spacing: -0.5px; margin-bottom: 8px; color: #18181b; }
.header p { color: #71717a; font-size: 14px; margin: 0; }
.form { display: flex; flex-direction: column; gap: 20px; margin-bottom: 32px; }
.field { display: flex; flex-direction: column; gap: 8px; }
.field label { font-size: 14px; font-weight: 500; color: #18181b; }
.deco-circle {
position: absolute;
border-radius: 50%;
filter: blur(48px);
}
.deco-circle-1 {
top: 25%;
right: 25%;
width: 256px;
height: 256px;
background: rgba(255, 255, 255, 0.1);
}
.deco-circle-2 {
bottom: 25%;
left: 25%;
width: 384px;
height: 384px;
background: rgba(255, 255, 255, 0.05);
}
.right {
display: flex;
align-items: center;
justify-content: center;
padding: 32px;
background: #fff;
}
.form-wrapper {
width: 100%;
max-width: 420px;
}
.mobile-brand {
display: none;
}
.header {
text-align: left;
margin-bottom: 40px;
}
.header h1 {
font-size: 30px;
font-weight: 700;
letter-spacing: -0.5px;
margin-bottom: 8px;
color: #18181b;
}
.header p {
color: #71717a;
font-size: 14px;
margin: 0;
}
.form {
display: flex;
flex-direction: column;
gap: 20px;
margin-bottom: 32px;
}
.field {
display: flex;
flex-direction: column;
gap: 8px;
}
.field label {
font-size: 14px;
font-weight: 500;
color: #18181b;
}
.field input {
height: 48px; padding: 0 12px; border-radius: 6px; border: 1px solid #d4d4d8;
font-size: 14px; outline: none; background: #fff; transition: border-color 0.2s; color: #18181b;
height: 48px;
padding: 0 12px;
border-radius: 6px;
border: 1px solid #d4d4d8;
font-size: 14px;
outline: none;
background: #fff;
transition: border-color 0.2s;
color: #18181b;
}
.field input:focus {
border-color: #4f46e5;
box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.2);
}
.password-wrap {
position: relative;
}
.password-wrap input {
width: 100%;
padding-right: 40px;
box-sizing: border-box;
}
.field input:focus { border-color: #4f46e5; box-shadow: 0 0 0 2px rgba(79,70,229,0.2); }
.password-wrap { position: relative; }
.password-wrap input { width: 100%; padding-right: 40px; box-sizing: border-box; }
.eye-btn {
position: absolute; right: 12px; top: 50%; transform: translateY(-50%);
background: none; border: none; color: #a1a1aa; transition: color 0.2s;
display: flex; align-items: center; justify-content: center; font-size: 18px; cursor: pointer;
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
color: #a1a1aa;
transition: color 0.2s;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
cursor: pointer;
}
.eye-btn:hover {
color: #3f3f46;
}
.options {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
}
.remember {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
color: #18181b;
}
.remember input {
width: 16px;
height: 16px;
accent-color: #4f46e5;
cursor: pointer;
}
.eye-btn:hover { color: #3f3f46; }
.options { display: flex; align-items: center; justify-content: space-between; font-size: 14px; }
.remember { display: flex; align-items: center; gap: 8px; cursor: pointer; color: #18181b; }
.remember input { width: 16px; height: 16px; accent-color: #4f46e5; cursor: pointer; }
.error-message {
display: flex;
@@ -228,7 +395,9 @@ async function handleSubmit(): Promise<void> {
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease, transform 0.3s ease;
transition:
opacity 0.3s ease,
transform 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
@@ -237,15 +406,41 @@ async function handleSubmit(): Promise<void> {
}
.btn-primary {
width: 100%; height: 48px; font-size: 16px; font-weight: 500; border: none; border-radius: 6px;
color: white; transition: opacity 0.2s; cursor: pointer; margin-top: 12px;
width: 100%;
height: 48px;
font-size: 16px;
font-weight: 500;
border: none;
border-radius: 6px;
color: white;
transition: opacity 0.2s;
cursor: pointer;
margin-top: 12px;
}
.btn-primary:hover {
opacity: 0.9;
}
.btn-primary:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-primary:hover { opacity: 0.9; }
.btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
@media (max-width: 1023px) {
.page { grid-template-columns: 1fr; }
.left { display: none; }
.mobile-brand { display: flex; align-items: center; justify-content: flex-start; gap: 8px; font-size: 18px; font-weight: 600; margin-bottom: 48px; color: #18181b; }
.page {
grid-template-columns: 1fr;
}
.left {
display: none;
}
.mobile-brand {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 8px;
font-size: 18px;
font-weight: 600;
margin-bottom: 48px;
color: #18181b;
}
}
</style>
+27 -27
View File
@@ -1,24 +1,24 @@
<template>
<h2 class="ops-page-title">个人资料</h2>
<div class="ops-card" style="max-width: 640px; margin-bottom: 24px;">
<h3 style="margin-top: 0; margin-bottom: 16px; font-size: 16px; font-weight: 600;">账号信息</h3>
<div class="ops-card" style="max-width: 640px; margin-bottom: 24px">
<h3 style="margin-top: 0; margin-bottom: 16px; font-size: 16px; font-weight: 600">账号信息</h3>
<a-descriptions :column="1" bordered>
<a-descriptions-item label="ID">{{ auth.operator?.id }}</a-descriptions-item>
<a-descriptions-item label="账号">{{ auth.operator?.username }}</a-descriptions-item>
<a-descriptions-item label="姓名">{{ auth.operator?.display_name }}</a-descriptions-item>
<a-descriptions-item label="邮箱">{{ auth.operator?.email || "—" }}</a-descriptions-item>
<a-descriptions-item label="邮箱">{{ auth.operator?.email || '—' }}</a-descriptions-item>
<a-descriptions-item label="角色">{{ auth.operator?.role }}</a-descriptions-item>
<a-descriptions-item label="状态">
<a-tag :color="auth.operator?.status === 'active' ? 'green' : 'red'">
{{ auth.operator?.status === "active" ? "启用" : "停用" }}
{{ auth.operator?.status === 'active' ? '启用' : '停用' }}
</a-tag>
</a-descriptions-item>
</a-descriptions>
</div>
<div class="ops-card" style="max-width: 640px">
<h3 style="margin-top: 0; margin-bottom: 16px; font-size: 16px; font-weight: 600;">修改密码</h3>
<h3 style="margin-top: 0; margin-bottom: 16px; font-size: 16px; font-weight: 600">修改密码</h3>
<a-form layout="vertical" :model="form" @submit.prevent="onSubmit">
<a-form-item label="原密码" required>
<a-input-password v-model:value="form.oldPassword" autocomplete="current-password" />
@@ -35,47 +35,47 @@
</template>
<script setup lang="ts">
import { message } from "ant-design-vue";
import { reactive, ref } from "vue";
import { message } from 'ant-design-vue'
import { reactive, ref } from 'vue'
import { OpsApiError, http } from "@/lib/http";
import { useAuthStore } from "@/stores/auth";
import { OpsApiError, http } from '@/lib/http'
import { useAuthStore } from '@/stores/auth'
const auth = useAuthStore();
const auth = useAuthStore()
const form = reactive({
oldPassword: "",
newPassword: "",
confirmPassword: "",
});
oldPassword: '',
newPassword: '',
confirmPassword: '',
})
const loading = ref(false);
const loading = ref(false)
async function onSubmit() {
if (!form.oldPassword || form.newPassword.length < 8) {
message.warning("请输入原密码,并将新密码设为至少 8 位");
return;
message.warning('请输入原密码,并将新密码设为至少 8 位')
return
}
if (form.newPassword !== form.confirmPassword) {
message.warning("两次输入的新密码不一致");
return;
message.warning('两次输入的新密码不一致')
return
}
loading.value = true;
loading.value = true
try {
await http.post("/auth/password", {
await http.post('/auth/password', {
old_password: form.oldPassword,
new_password: form.newPassword,
});
message.success("密码已更新,请使用新密码重新登录");
auth.logout();
})
message.success('密码已更新,请使用新密码重新登录')
auth.logout()
// router redirect handled by 401 interceptor or next route guard
if (typeof window !== "undefined") window.location.href = "/login";
if (typeof window !== 'undefined') window.location.href = '/login'
} catch (error) {
if (error instanceof OpsApiError) {
message.error(error.detail || error.message);
message.error(error.detail || error.message)
}
} finally {
loading.value = false;
loading.value = false
}
}
</script>
+129 -119
View File
@@ -70,15 +70,26 @@
{{ formatDate(record.updated_at) }}
</template>
<template v-else-if="column.key === 'actions'">
<div class="table-actions-row" style="justify-content: flex-end;">
<div class="table-actions-row" style="justify-content: flex-end">
<a-tooltip title="编辑">
<a-button type="text" shape="circle" size="small" class="action-btn action-edit" @click="openEdit(record)">
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-edit"
@click="openEdit(record)"
>
<EditOutlined />
</a-button>
</a-tooltip>
<a-tooltip title="删除">
<a-popconfirm title="确认删除该映射?" @confirm="deleteMapping(record)">
<a-button type="text" shape="circle" size="small" class="action-btn action-delete">
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-delete"
>
<DeleteOutlined />
</a-button>
</a-popconfirm>
@@ -107,7 +118,11 @@
<a-input v-model:value="form.site_name" placeholder="知乎" />
</a-form-item>
<a-form-item label="状态">
<a-switch v-model:checked="form.is_active" checked-children="启用" un-checked-children="停用" />
<a-switch
v-model:checked="form.is_active"
checked-children="启用"
un-checked-children="停用"
/>
</a-form-item>
</a-form>
@@ -122,224 +137,219 @@
</template>
<script setup lang="ts">
import {
DeleteOutlined,
EditOutlined,
PlusOutlined,
ReloadOutlined,
} from "@ant-design/icons-vue";
import type { TablePaginationConfig } from "ant-design-vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { computed, onMounted, reactive, ref } from "vue";
import { DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'
import { OpsApiError, http } from "@/lib/http";
import { OpsApiError, http } from '@/lib/http'
interface SiteDomainMappingRow {
id: number;
registrable_domain: string;
site_key: string;
site_name: string;
is_active: boolean;
created_at: string;
updated_at: string;
id: number
registrable_domain: string
site_key: string
site_name: string
is_active: boolean
created_at: string
updated_at: string
}
interface ListResult {
items: SiteDomainMappingRow[];
total: number;
page: number;
size: number;
items: SiteDomainMappingRow[]
total: number
page: number
size: number
}
const filter = reactive({
keyword: "",
keyword: '',
status: undefined as string | undefined,
});
})
const statusOptions = [
{ label: "启用", value: "true" },
{ label: "停用", value: "false" },
];
{ label: '启用', value: 'true' },
{ label: '停用', value: 'false' },
]
const columns = [
{ title: "域名 / Key", key: "registrable_domain", dataIndex: "registrable_domain", width: "34%" },
{ title: "中文名", key: "site_name", dataIndex: "site_name", width: "22%" },
{ title: "状态", key: "is_active", width: 120 },
{ title: "更新时间", key: "updated_at", width: 180 },
{ title: "操作", key: "actions", width: 120, align: "right" as const },
];
{ title: '域名 / Key', key: 'registrable_domain', dataIndex: 'registrable_domain', width: '34%' },
{ title: '中文名', key: 'site_name', dataIndex: 'site_name', width: '22%' },
{ title: '状态', key: 'is_active', width: 120 },
{ title: '更新时间', key: 'updated_at', width: 180 },
{ title: '操作', key: 'actions', width: 120, align: 'right' as const },
]
const rows = ref<SiteDomainMappingRow[]>([]);
const loading = ref(false);
const page = ref(1);
const size = ref(20);
const total = ref(0);
const statusLoadingId = ref<number | null>(null);
const rows = ref<SiteDomainMappingRow[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(20)
const total = ref(0)
const statusLoadingId = ref<number | null>(null)
const activeRows = computed(() => rows.value.filter((row) => row.is_active).length);
const inactiveRows = computed(() => rows.value.length - activeRows.value);
const activeRows = computed(() => rows.value.filter((row) => row.is_active).length)
const inactiveRows = computed(() => rows.value.length - activeRows.value)
const pagination = computed<TablePaginationConfig>(() => ({
current: page.value,
pageSize: size.value,
total: total.value,
showSizeChanger: true,
pageSizeOptions: ["10", "20", "50", "100"],
}));
pageSizeOptions: ['10', '20', '50', '100'],
}))
let keywordTimer: number | null = null;
let keywordTimer: number | null = null
function onKeywordChange() {
if (keywordTimer) window.clearTimeout(keywordTimer);
if (keywordTimer) window.clearTimeout(keywordTimer)
keywordTimer = window.setTimeout(() => {
page.value = 1;
void reload();
}, 300);
page.value = 1
void reload()
}, 300)
}
function onStatusChange() {
page.value = 1;
void reload();
page.value = 1
void reload()
}
async function reload() {
loading.value = true;
loading.value = true
try {
const result = await http.get<ListResult>("/site-domain-mappings", {
const result = await http.get<ListResult>('/site-domain-mappings', {
keyword: filter.keyword || undefined,
is_active: filter.status || undefined,
page: page.value,
size: size.value,
});
rows.value = result.items;
total.value = result.total;
})
rows.value = result.items
total.value = result.total
} catch (error) {
handleError(error);
handleError(error)
} finally {
loading.value = false;
loading.value = false
}
}
function onTableChange(pag: TablePaginationConfig) {
page.value = pag.current ?? 1;
size.value = pag.pageSize ?? 20;
void reload();
page.value = pag.current ?? 1
size.value = pag.pageSize ?? 20
void reload()
}
const drawerOpen = ref(false);
const saving = ref(false);
const editingRow = ref<SiteDomainMappingRow | null>(null);
const drawerOpen = ref(false)
const saving = ref(false)
const editingRow = ref<SiteDomainMappingRow | null>(null)
const form = reactive({
registrable_domain: "",
site_key: "",
site_name: "",
registrable_domain: '',
site_key: '',
site_name: '',
is_active: true,
});
})
function resetForm() {
form.registrable_domain = "";
form.site_key = "";
form.site_name = "";
form.is_active = true;
editingRow.value = null;
form.registrable_domain = ''
form.site_key = ''
form.site_name = ''
form.is_active = true
editingRow.value = null
}
function openCreate() {
resetForm();
drawerOpen.value = true;
resetForm()
drawerOpen.value = true
}
function openEdit(row: SiteDomainMappingRow) {
editingRow.value = row;
form.registrable_domain = row.registrable_domain;
form.site_key = row.site_key;
form.site_name = row.site_name;
form.is_active = row.is_active;
drawerOpen.value = true;
editingRow.value = row
form.registrable_domain = row.registrable_domain
form.site_key = row.site_key
form.site_name = row.site_name
form.is_active = row.is_active
drawerOpen.value = true
}
function closeDrawer() {
drawerOpen.value = false;
drawerOpen.value = false
}
async function submitForm() {
const domain = form.registrable_domain.trim();
const siteName = form.site_name.trim();
const domain = form.registrable_domain.trim()
const siteName = form.site_name.trim()
if (!domain) {
message.warning("请输入匹配域名");
return;
message.warning('请输入匹配域名')
return
}
if (!siteName) {
message.warning("请输入中文名");
return;
message.warning('请输入中文名')
return
}
saving.value = true;
saving.value = true
try {
const payload = {
registrable_domain: domain,
site_key: form.site_key.trim(),
site_name: siteName,
is_active: form.is_active,
};
if (editingRow.value) {
await http.patch(`/site-domain-mappings/${editingRow.value.id}`, payload);
message.success("已保存");
} else {
await http.post("/site-domain-mappings", payload);
message.success("已新增");
}
drawerOpen.value = false;
resetForm();
void reload();
if (editingRow.value) {
await http.patch(`/site-domain-mappings/${editingRow.value.id}`, payload)
message.success('已保存')
} else {
await http.post('/site-domain-mappings', payload)
message.success('已新增')
}
drawerOpen.value = false
resetForm()
void reload()
} catch (error) {
handleError(error);
handleError(error)
} finally {
saving.value = false;
saving.value = false
}
}
async function setActive(row: SiteDomainMappingRow, active: boolean) {
statusLoadingId.value = row.id;
statusLoadingId.value = row.id
try {
await http.post(`/site-domain-mappings/${row.id}/active`, { is_active: active });
message.success(active ? "已启用" : "已停用");
row.is_active = active;
await http.post(`/site-domain-mappings/${row.id}/active`, { is_active: active })
message.success(active ? '已启用' : '已停用')
row.is_active = active
} catch (error) {
handleError(error);
handleError(error)
} finally {
statusLoadingId.value = null;
statusLoadingId.value = null
}
}
function onActiveSwitchChange(row: SiteDomainMappingRow, checked: unknown) {
void setActive(row, Boolean(checked));
void setActive(row, Boolean(checked))
}
async function deleteMapping(row: SiteDomainMappingRow) {
try {
await http.delete(`/site-domain-mappings/${row.id}`);
message.success("已删除");
void reload();
await http.delete(`/site-domain-mappings/${row.id}`)
message.success('已删除')
void reload()
} catch (error) {
handleError(error);
handleError(error)
}
}
function formatDate(value: string | null | undefined): string {
return value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "—";
return value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '—'
}
function handleError(error: unknown) {
if (error instanceof OpsApiError) {
message.error(error.detail || error.message);
message.error(error.detail || error.message)
}
}
onMounted(() => {
void reload();
});
void reload()
})
</script>
<style scoped>