feat: 完成财务中台核心功能与前后端基础设施搭建
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
# 本地演示环境:默认开启内置 Mock(无需后端即可完整操作)
|
||||
VITE_APP_TITLE=财务中台
|
||||
VITE_USE_MOCK=1
|
||||
VITE_API_BASE=/api
|
||||
@@ -0,0 +1,4 @@
|
||||
# 生产环境:必须关闭 Mock,走真实后端
|
||||
VITE_APP_TITLE=财务中台
|
||||
VITE_USE_MOCK=0
|
||||
VITE_API_BASE=/api
|
||||
@@ -0,0 +1,7 @@
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.DS_Store
|
||||
npm-debug.log*
|
||||
.vite
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<!-- 等保二级:禁止页面被第三方框架嵌套与内容嗅探 -->
|
||||
<meta http-equiv="X-Content-Type-Options" content="nosniff" />
|
||||
<meta name="referrer" content="same-origin" />
|
||||
<title>财务中台 · 中央计费平台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2169
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "finance-web",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "中央计费平台(资金中台)前端",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"type-check": "vue-tsc --noEmit",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.1",
|
||||
"axios": "^1.7.9",
|
||||
"echarts": "^5.5.1",
|
||||
"element-plus": "^2.9.1",
|
||||
"pinia": "^2.3.0",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.2",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"typescript": "~5.7.2",
|
||||
"vite": "^6.0.5",
|
||||
"vue-tsc": "^2.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<script setup lang="ts"></script>
|
||||
|
||||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
@@ -0,0 +1,21 @@
|
||||
import { http } from '@/utils/http'
|
||||
import type { AdminInfo, LoginResult } from '@/types'
|
||||
|
||||
export interface LoginPayload {
|
||||
username: string
|
||||
password: string
|
||||
totp: string
|
||||
}
|
||||
|
||||
export interface ProfileResult {
|
||||
admin: AdminInfo
|
||||
permissions: string[]
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
login: (payload: LoginPayload) => http.post<LoginResult>('/admin/login', payload, { silent: true }),
|
||||
logout: () => http.post<null>('/admin/logout'),
|
||||
profile: () => http.get<ProfileResult>('/admin/profile', undefined, { silent: true }),
|
||||
changePassword: (payload: { oldPassword: string; newPassword: string }) =>
|
||||
http.post<null>('/admin/password/change', payload, { silent: true }),
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { http } from '@/utils/http'
|
||||
import type {
|
||||
AccountInfo,
|
||||
AppInfo,
|
||||
AppTokenInfo,
|
||||
OrderInfo,
|
||||
PageResult,
|
||||
RefundInfo,
|
||||
TransactionInfo,
|
||||
} from '@/types'
|
||||
|
||||
export interface PageQuery {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
}
|
||||
|
||||
export interface AppPayload {
|
||||
appCode?: string
|
||||
appName?: string
|
||||
allowedRedirectHosts?: string
|
||||
webhookUrl?: string
|
||||
tokenTtlSeconds?: number
|
||||
}
|
||||
|
||||
export interface AccountQuery extends PageQuery {
|
||||
appCode?: string
|
||||
keyword?: string
|
||||
minBalance?: number
|
||||
}
|
||||
|
||||
export interface OrderQuery extends PageQuery {
|
||||
appCode?: string
|
||||
status?: string
|
||||
orderType?: string
|
||||
keyword?: string
|
||||
from?: string
|
||||
to?: string
|
||||
}
|
||||
|
||||
export interface TransactionQuery extends PageQuery {
|
||||
appCode?: string
|
||||
type?: string
|
||||
keyword?: string
|
||||
from?: string
|
||||
to?: string
|
||||
}
|
||||
|
||||
export interface RefundQuery extends PageQuery {
|
||||
appCode?: string
|
||||
status?: string
|
||||
keyword?: string
|
||||
from?: string
|
||||
to?: string
|
||||
}
|
||||
|
||||
export interface Approver {
|
||||
id: number
|
||||
username: string
|
||||
role: string
|
||||
}
|
||||
|
||||
export const appApi = {
|
||||
list: () => http.get<AppInfo[]>('/admin/apps'),
|
||||
create: (payload: AppPayload) =>
|
||||
http.post<{ app: AppInfo; clientSecret: string }>('/admin/apps', payload, { silent: true }),
|
||||
update: (appCode: string, payload: AppPayload) => http.put<AppInfo>(`/admin/apps/${appCode}`, payload),
|
||||
rotateSecret: (appCode: string, graceHours: number) =>
|
||||
http.post<{ clientSecret: string; expiresAt: string }>(`/admin/apps/${appCode}/secret/rotate`, { graceHours }, { silent: true }),
|
||||
revokePrevSecret: (appCode: string) => http.post<null>(`/admin/apps/${appCode}/secret/revoke-prev`),
|
||||
toggle: (appCode: string, enabled: number) => http.post<AppInfo>(`/admin/apps/${appCode}/toggle`, { enabled }),
|
||||
listTokens: (appCode: string) => http.get<AppTokenInfo[]>(`/admin/apps/${appCode}/tokens`),
|
||||
revokeTokens: (appCode: string, tokenId?: number) =>
|
||||
http.post<{ revoked: number }>(`/admin/apps/${appCode}/tokens/revoke`, { tokenId }),
|
||||
}
|
||||
|
||||
export interface AccountDetail {
|
||||
account: AccountInfo
|
||||
vip: {
|
||||
planCode: string
|
||||
planName: string
|
||||
vipUntil: string
|
||||
effective: boolean
|
||||
freeDeduction: number
|
||||
} | null
|
||||
transactions: TransactionInfo[]
|
||||
}
|
||||
|
||||
export interface AdjustPayload {
|
||||
appCode: string
|
||||
businessUserId: string
|
||||
amount: number
|
||||
direction: 'IN' | 'OUT'
|
||||
reason: string
|
||||
secondApproverId: number
|
||||
totp: string
|
||||
}
|
||||
|
||||
export const accountApi = {
|
||||
list: (query: AccountQuery) => http.get<PageResult<AccountInfo>>('/admin/accounts', query),
|
||||
detail: (id: number) => http.get<AccountDetail>(`/admin/accounts/${id}`),
|
||||
transactions: (id: number, query: PageQuery) =>
|
||||
http.get<PageResult<TransactionInfo>>(`/admin/accounts/${id}/transactions`, query),
|
||||
adjust: (payload: AdjustPayload) => http.post<AccountInfo>('/admin/accounts/adjust', payload, { silent: true }),
|
||||
}
|
||||
|
||||
export interface ConfirmPayload {
|
||||
voucherNo: string
|
||||
receiveAt?: string
|
||||
secondApproverId?: number
|
||||
totp: string
|
||||
}
|
||||
|
||||
export interface CancelPayload {
|
||||
reason: string
|
||||
totp: string
|
||||
}
|
||||
|
||||
export interface OrderDetail {
|
||||
order: OrderInfo
|
||||
refunds: RefundInfo[]
|
||||
cashFlows: Array<{
|
||||
id: number
|
||||
direction: 'IN' | 'OUT'
|
||||
amountCent: number
|
||||
receivedAt: string
|
||||
voucherNo: string
|
||||
remark: string
|
||||
}>
|
||||
}
|
||||
|
||||
export const orderApi = {
|
||||
list: (query: OrderQuery) => http.get<PageResult<OrderInfo>>('/admin/orders', query),
|
||||
detail: (id: number) => http.get<OrderDetail>(`/admin/orders/${id}`),
|
||||
confirm: (id: number, payload: ConfirmPayload) =>
|
||||
http.post<OrderInfo>(`/admin/orders/${id}/confirm`, payload, { silent: true }),
|
||||
cancel: (id: number, payload: CancelPayload) =>
|
||||
http.post<OrderInfo>(`/admin/orders/${id}/cancel`, payload, { silent: true }),
|
||||
export: (query: OrderQuery) => http.get<OrderInfo[]>('/admin/orders/export', query),
|
||||
approvers: () => http.get<Approver[]>('/admin/approvers'),
|
||||
}
|
||||
|
||||
export interface RefundCreatePayload {
|
||||
orderId: number
|
||||
amountCent: number
|
||||
voucherNo?: string
|
||||
reason: string
|
||||
idempotencyKey: string
|
||||
totp: string
|
||||
}
|
||||
|
||||
export interface RefundReviewPayload {
|
||||
action: 'approve' | 'reject'
|
||||
voucherNo?: string
|
||||
reason?: string
|
||||
totp: string
|
||||
}
|
||||
|
||||
export const refundApi = {
|
||||
list: (query: RefundQuery) => http.get<PageResult<RefundInfo>>('/admin/refunds', query),
|
||||
create: (payload: RefundCreatePayload) => http.post<RefundInfo>('/admin/refunds', payload, { silent: true }),
|
||||
review: (id: number, payload: RefundReviewPayload) =>
|
||||
http.post<RefundInfo>(`/admin/refunds/${id}/review`, payload, { silent: true }),
|
||||
}
|
||||
|
||||
export const transactionApi = {
|
||||
list: (query: TransactionQuery) => http.get<PageResult<TransactionInfo>>('/admin/transactions', query),
|
||||
export: (query: TransactionQuery) => http.get<TransactionInfo[]>('/admin/transactions/export', query),
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { http } from '@/utils/http'
|
||||
import type { OrderStatus, PayOrder, PayPreview } from '@/types'
|
||||
|
||||
export interface PayPreviewQuery {
|
||||
appCode: string
|
||||
ticket: string
|
||||
redirectUri?: string
|
||||
}
|
||||
|
||||
export interface PayCreatePayload {
|
||||
appCode: string
|
||||
ticket: string
|
||||
orderType: 'recharge' | 'vip'
|
||||
amountCent?: number
|
||||
planCode?: string
|
||||
redirectUri?: string
|
||||
/** 幂等键:同一次下单的重复提交必须复用同一个值,服务端据此返回首次结果 */
|
||||
idempotencyKey?: string
|
||||
}
|
||||
|
||||
export interface PayStatus {
|
||||
outTradeNo: string
|
||||
status: OrderStatus
|
||||
amountCent: number
|
||||
pointsGained: number
|
||||
paidAt: string | null
|
||||
expiresAt: string
|
||||
}
|
||||
|
||||
export interface DemoTicket {
|
||||
appCode: string
|
||||
ticket: string
|
||||
businessUserId: string
|
||||
username: string
|
||||
redirectUri: string
|
||||
expiresAt: string
|
||||
}
|
||||
|
||||
export const payApi = {
|
||||
preview: (query: PayPreviewQuery) => http.get<PayPreview>('/pay/preview', query, { silent: true }),
|
||||
createOrder: (payload: PayCreatePayload) => http.post<PayOrder>('/pay/orders', payload, { silent: true }),
|
||||
status: (outTradeNo: string) => http.get<PayStatus>(`/pay/orders/${encodeURIComponent(outTradeNo)}/status`, undefined, { silent: true }),
|
||||
demoTicket: (appCode: string) => http.get<DemoTicket>('/pay/demo-ticket', { appCode }, { silent: true }),
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { http } from '@/utils/http'
|
||||
import type { AppPolicy, ConfigItem, PageResult, PricingItem, ReconcileReport, VipHolder, VipPlan } from '@/types'
|
||||
import type { PageQuery } from './core'
|
||||
|
||||
export interface VipPlanPayload {
|
||||
appCode: string
|
||||
planCode?: string
|
||||
planName?: string
|
||||
durationDays: number
|
||||
priceCent: number
|
||||
freeDeduction: number
|
||||
totp?: string
|
||||
}
|
||||
|
||||
export interface VipHolderQuery extends PageQuery {
|
||||
appCode?: string
|
||||
keyword?: string
|
||||
}
|
||||
|
||||
export const vipApi = {
|
||||
plans: (appCode?: string) => http.get<VipPlan[]>('/admin/vip-plans', appCode ? { appCode } : undefined),
|
||||
createPlan: (payload: VipPlanPayload) => http.post<VipPlan>('/admin/vip-plans', payload, { silent: true }),
|
||||
updatePlan: (id: number, payload: VipPlanPayload) => http.put<VipPlan>(`/admin/vip-plans/${id}`, payload, { silent: true }),
|
||||
togglePlan: (id: number, enabled: number) => http.post<VipPlan>(`/admin/vip-plans/${id}/toggle`, { enabled }),
|
||||
holders: (query: VipHolderQuery) => http.get<PageResult<VipHolder>>('/admin/vips', query),
|
||||
}
|
||||
|
||||
export interface PricingPayload {
|
||||
pointsPerYuan: number
|
||||
enabled: number
|
||||
totp: string
|
||||
}
|
||||
|
||||
export interface PolicyPayload {
|
||||
minCost: number
|
||||
maxPointsPerCharge: number
|
||||
vipExempt: number
|
||||
failedStrategy: 'none' | 'actual'
|
||||
dualControlThresholdCent: number
|
||||
totp: string
|
||||
}
|
||||
|
||||
export const pricingApi = {
|
||||
list: () => http.get<PricingItem[]>('/admin/pricing'),
|
||||
save: (appCode: string, payload: PricingPayload) =>
|
||||
http.put<PricingItem>(`/admin/pricing/${appCode}`, payload, { silent: true }),
|
||||
policies: () => http.get<AppPolicy[]>('/admin/policies'),
|
||||
savePolicy: (appCode: string, payload: PolicyPayload) =>
|
||||
http.put<AppPolicy>(`/admin/policies/${appCode}`, payload, { silent: true }),
|
||||
}
|
||||
|
||||
export interface ReconcileRunPayload {
|
||||
appCode: string
|
||||
windowStart: string
|
||||
windowEnd: string
|
||||
}
|
||||
|
||||
export const reconcileApi = {
|
||||
reports: () => http.get<ReconcileReport[]>('/admin/reconcile/reports'),
|
||||
detail: (id: string) => http.get<ReconcileReport>(`/admin/reconcile/reports/${id}`),
|
||||
run: (payload: ReconcileRunPayload) => http.post<ReconcileReport>('/admin/reconcile/run', payload),
|
||||
}
|
||||
|
||||
export interface ConfigPayload {
|
||||
value: string
|
||||
reason: string
|
||||
totp: string
|
||||
}
|
||||
|
||||
export const configApi = {
|
||||
list: () => http.get<ConfigItem[]>('/admin/configs'),
|
||||
update: (key: string, payload: ConfigPayload) =>
|
||||
http.put<ConfigItem>(`/admin/configs/${encodeURIComponent(key)}`, payload, { silent: true }),
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { http } from '@/utils/http'
|
||||
import type {
|
||||
AdminInfo,
|
||||
AuditLog,
|
||||
ChainVerifyResult,
|
||||
DashboardSummary,
|
||||
AppDistribution,
|
||||
PageResult,
|
||||
Role,
|
||||
TrendPoint,
|
||||
WebhookDelivery,
|
||||
} from '@/types'
|
||||
import type { PageQuery } from './core'
|
||||
|
||||
export interface AdminCreatePayload {
|
||||
username: string
|
||||
role: Role
|
||||
totp: string
|
||||
}
|
||||
|
||||
export interface AdminUpdatePayload {
|
||||
role: Role
|
||||
}
|
||||
|
||||
export interface AuditQuery extends PageQuery {
|
||||
actor?: string
|
||||
action?: string
|
||||
result?: string
|
||||
keyword?: string
|
||||
from?: string
|
||||
to?: string
|
||||
}
|
||||
|
||||
export interface WebhookQuery extends PageQuery {
|
||||
appCode?: string
|
||||
status?: string
|
||||
keyword?: string
|
||||
from?: string
|
||||
to?: string
|
||||
}
|
||||
|
||||
export const adminApi = {
|
||||
list: () => http.get<AdminInfo[]>('/admin/admins'),
|
||||
create: (payload: AdminCreatePayload) =>
|
||||
http.post<{ admin: AdminInfo; initialPassword: string }>('/admin/admins', payload, { silent: true }),
|
||||
updateRole: (id: number, payload: AdminUpdatePayload) => http.put<AdminInfo>(`/admin/admins/${id}`, payload),
|
||||
toggle: (id: number, enabled: number) => http.post<AdminInfo>(`/admin/admins/${id}/toggle`, { enabled }),
|
||||
resetPassword: (id: number, totp: string) =>
|
||||
http.post<{ tempPassword: string }>(`/admin/admins/${id}/reset-password`, { totp }, { silent: true }),
|
||||
resetTotp: (id: number, totp: string) =>
|
||||
http.post<{ message: string }>(`/admin/admins/${id}/reset-totp`, { totp }, { silent: true }),
|
||||
}
|
||||
|
||||
export const auditApi = {
|
||||
list: (query: AuditQuery) => http.get<PageResult<AuditLog>>('/admin/audit-logs', query),
|
||||
detail: (id: number) => http.get<AuditLog>(`/admin/audit-logs/${id}`),
|
||||
verify: () => http.post<ChainVerifyResult>('/admin/audit-logs/verify'),
|
||||
export: (query: AuditQuery) => http.get<AuditLog[]>('/admin/audit-logs/export', query),
|
||||
}
|
||||
|
||||
export const webhookApi = {
|
||||
list: (query: WebhookQuery) => http.get<PageResult<WebhookDelivery>>('/admin/webhooks', query),
|
||||
replay: (id: number, totp: string) =>
|
||||
http.post<WebhookDelivery>(`/admin/webhooks/${id}/replay`, { totp }, { silent: true }),
|
||||
}
|
||||
|
||||
export const dashboardApi = {
|
||||
summary: () => http.get<DashboardSummary>('/admin/dashboard/summary'),
|
||||
trend: () => http.get<TrendPoint[]>('/admin/dashboard/trend'),
|
||||
distribution: () => http.get<AppDistribution[]>('/admin/dashboard/distribution'),
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<script setup lang="ts">
|
||||
import * as echarts from 'echarts'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
|
||||
const props = withDefaults(defineProps<{ option: EChartsOption; height?: string }>(), {
|
||||
height: '300px',
|
||||
})
|
||||
|
||||
const container = ref<HTMLDivElement | null>(null)
|
||||
let chart: echarts.ECharts | null = null
|
||||
let observer: ResizeObserver | null = null
|
||||
|
||||
onMounted(() => {
|
||||
if (!container.value) return
|
||||
chart = echarts.init(container.value)
|
||||
chart.setOption(props.option)
|
||||
observer = new ResizeObserver(() => chart?.resize())
|
||||
observer.observe(container.value)
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.option,
|
||||
option => chart?.setOption(option, true),
|
||||
{ deep: true },
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
observer?.disconnect()
|
||||
observer = null
|
||||
chart?.dispose()
|
||||
chart = null
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="container" :style="{ width: '100%', height }" />
|
||||
</template>
|
||||
@@ -0,0 +1,48 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { confirmAction } from '@/utils/confirm'
|
||||
import { buildCsv, downloadCsv, exportFilename, type CsvColumn } from '@/utils/export'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
filename: string
|
||||
columns: CsvColumn<Record<string, any>>[]
|
||||
fetcher: () => Promise<Record<string, any>[]>
|
||||
label?: string
|
||||
}>(),
|
||||
{ label: '导出 CSV' },
|
||||
)
|
||||
|
||||
const loading = ref(false)
|
||||
|
||||
async function handleExport(): Promise<void> {
|
||||
const confirmed = await confirmAction({
|
||||
title: '导出敏感数据',
|
||||
message: '导出内容包含用户与资金数据,操作会写入审计日志;单次导出上限 1 万行。是否继续?',
|
||||
confirmText: '确认导出',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const rows = await props.fetcher()
|
||||
if (!rows.length) {
|
||||
ElMessage.warning('当前筛选条件下没有可导出的数据')
|
||||
return
|
||||
}
|
||||
downloadCsv(exportFilename(props.filename), buildCsv(props.columns, rows))
|
||||
ElMessage.success(`已导出 ${rows.length} 条记录`)
|
||||
} catch {
|
||||
// 错误提示已由 http 拦截器统一弹出,此处仅需避免未捕获的 Promise 拒绝
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-button :loading="loading" @click="handleExport">
|
||||
<el-icon style="margin-right: 4px"><Download /></el-icon>{{ label }}
|
||||
</el-button>
|
||||
</template>
|
||||
@@ -0,0 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
title: string
|
||||
desc?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h2>{{ title }}</h2>
|
||||
<p v-if="desc" class="desc">{{ desc }}</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,71 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
label: string
|
||||
value: string | number
|
||||
sub?: string
|
||||
tone?: 'default' | 'success' | 'warning' | 'danger' | 'primary'
|
||||
icon?: string
|
||||
}>(),
|
||||
{ tone: 'default' },
|
||||
)
|
||||
|
||||
const toneColor = computed(() => {
|
||||
const map: Record<string, string> = {
|
||||
default: 'var(--fin-text)',
|
||||
primary: 'var(--el-color-primary)',
|
||||
success: 'var(--fin-success)',
|
||||
warning: 'var(--fin-warn)',
|
||||
danger: 'var(--fin-danger)',
|
||||
}
|
||||
return map[props.tone] || map.default
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="stat-card">
|
||||
<div class="head">
|
||||
<span class="label">{{ label }}</span>
|
||||
<el-icon v-if="icon" class="icon"><component :is="icon" /></el-icon>
|
||||
</div>
|
||||
<div class="value num" :style="{ color: toneColor }">{{ value }}</div>
|
||||
<div v-if="sub" class="sub">{{ sub }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.stat-card {
|
||||
background: #fff;
|
||||
border: 1px solid var(--fin-border);
|
||||
border-radius: var(--fin-radius);
|
||||
padding: 16px 18px;
|
||||
box-shadow: var(--fin-shadow);
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
color: var(--fin-text-2);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: var(--fin-text-3);
|
||||
}
|
||||
|
||||
.value {
|
||||
margin-top: 10px;
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.sub {
|
||||
margin-top: 6px;
|
||||
color: var(--fin-text-3);
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { OrderStatus, OrderType, PayMethod, RefundStatus, Role, TxType, WebhookStatus } from '@/types'
|
||||
|
||||
export const APP_TITLE = import.meta.env.VITE_APP_TITLE || '财务中台'
|
||||
|
||||
export const ROLE_LABEL: Record<Role, string> = {
|
||||
SUPER_ADMIN: '超级管理员',
|
||||
FINANCE: '财务专员',
|
||||
AUDITOR: '审计员',
|
||||
}
|
||||
|
||||
export const ROLE_DESC: Record<Role, string> = {
|
||||
SUPER_ADMIN: '管配置与账号,不可确认到账',
|
||||
FINANCE: '管资金操作,不可修改定价',
|
||||
AUDITOR: '只读查询与审计',
|
||||
}
|
||||
|
||||
/** 权限码与设计文档 §8 一致,前端仅做体验层控制,服务端必须二次校验 */
|
||||
export const PERM = {
|
||||
view: 'fin:view',
|
||||
export: 'fin:export',
|
||||
appManage: 'fin:app:manage',
|
||||
pricingEdit: 'fin:pricing:edit',
|
||||
vipManage: 'fin:vip:manage',
|
||||
adminManage: 'fin:admin:manage',
|
||||
configEdit: 'fin:config:edit',
|
||||
auditView: 'fin:audit:view',
|
||||
webhookManage: 'fin:webhook:manage',
|
||||
accountAdjust: 'fin:account:adjust',
|
||||
rechargeConfirm: 'fin:recharge:confirm',
|
||||
refundCreate: 'fin:refund:create',
|
||||
refundReview: 'fin:refund:review',
|
||||
orderCancel: 'fin:order:cancel',
|
||||
reconcileRun: 'fin:reconcile:run',
|
||||
} as const
|
||||
|
||||
export const ORDER_STATUS: Record<OrderStatus, { label: string; tag: 'success' | 'warning' | 'info' | 'danger' }> = {
|
||||
PENDING: { label: '待确认', tag: 'warning' },
|
||||
PAID: { label: '已到账', tag: 'success' },
|
||||
CANCELLED: { label: '已关闭', tag: 'info' },
|
||||
REFUNDED: { label: '已退款', tag: 'danger' },
|
||||
}
|
||||
|
||||
export const ORDER_TYPE_LABEL: Record<OrderType, string> = {
|
||||
recharge: '点数充值',
|
||||
vip: 'VIP 开通/续费',
|
||||
}
|
||||
|
||||
export const PAY_METHOD_LABEL: Record<PayMethod, string> = {
|
||||
offline: '线下转账',
|
||||
wechat: '微信支付',
|
||||
alipay: '支付宝',
|
||||
}
|
||||
|
||||
export const TX_TYPE: Record<TxType, { label: string; sign: 1 | -1 | 0; tag: 'success' | 'danger' | 'info' | 'warning' }> = {
|
||||
RECHARGE: { label: '充值入账', sign: 1, tag: 'success' },
|
||||
CONSUME: { label: '扣费', sign: -1, tag: 'danger' },
|
||||
CONSUME_FREE: { label: 'VIP 免扣', sign: 0, tag: 'info' },
|
||||
REFUND_IN: { label: '点数退款', sign: 1, tag: 'warning' },
|
||||
REFUND_OUT: { label: '现金退款扣回', sign: -1, tag: 'warning' },
|
||||
ADJUST: { label: '人工调账', sign: 0, tag: 'info' },
|
||||
}
|
||||
|
||||
export const REFUND_STATUS: Record<RefundStatus, { label: string; tag: 'warning' | 'success' | 'danger' }> = {
|
||||
PENDING: { label: '待复核', tag: 'warning' },
|
||||
COMPLETED: { label: '已完成', tag: 'success' },
|
||||
REJECTED: { label: '已驳回', tag: 'danger' },
|
||||
}
|
||||
|
||||
export const WEBHOOK_STATUS: Record<WebhookStatus, { label: string; tag: 'info' | 'success' | 'warning' | 'danger' }> = {
|
||||
PENDING: { label: '待投递', tag: 'info' },
|
||||
SENT: { label: '已送达', tag: 'success' },
|
||||
FAILED: { label: '重试中', tag: 'warning' },
|
||||
DEAD: { label: '投递失败', tag: 'danger' },
|
||||
}
|
||||
|
||||
export const TX_TYPE_OPTIONS = (Object.keys(TX_TYPE) as TxType[]).map(value => ({
|
||||
value,
|
||||
label: TX_TYPE[value].label,
|
||||
}))
|
||||
|
||||
export const ORDER_STATUS_OPTIONS = (Object.keys(ORDER_STATUS) as OrderStatus[]).map(value => ({
|
||||
value,
|
||||
label: ORDER_STATUS[value].label,
|
||||
}))
|
||||
|
||||
export const ROLE_OPTIONS = (Object.keys(ROLE_LABEL) as Role[]).map(value => ({
|
||||
value,
|
||||
label: ROLE_LABEL[value],
|
||||
}))
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Directive } from 'vue'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
/**
|
||||
* 按钮级权限指令:无权限时隐藏元素。
|
||||
* 注意:前端隐藏只是体验层,服务端必须用 @PreAuthorize 等再次校验。
|
||||
*/
|
||||
export const permission: Directive<HTMLElement, string | string[]> = {
|
||||
mounted(el, binding) {
|
||||
if (!binding.value) return
|
||||
const store = useUserStore()
|
||||
if (!store.hasPerm(binding.value)) {
|
||||
el.style.display = 'none'
|
||||
el.dataset.permHidden = '1'
|
||||
}
|
||||
},
|
||||
updated(el, binding) {
|
||||
if (!binding.value) return
|
||||
const store = useUserStore()
|
||||
el.style.display = store.hasPerm(binding.value) ? '' : 'none'
|
||||
},
|
||||
}
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare module '*.vue' {
|
||||
import type { DefineComponent } from 'vue'
|
||||
const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>
|
||||
export default component
|
||||
}
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_TITLE: string
|
||||
readonly VITE_USE_MOCK: string
|
||||
readonly VITE_API_BASE: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { APP_TITLE, ROLE_LABEL } from '@/constants'
|
||||
import { MENU_GROUPS } from '@/router/menu'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { SESSION_IDLE_MS, SESSION_WARN_MS } from '@/utils/session'
|
||||
import { secondsText } from '@/utils/format'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = useUserStore()
|
||||
|
||||
const groups = computed(() =>
|
||||
MENU_GROUPS.map(group => ({
|
||||
...group,
|
||||
items: group.items.filter(item => !item.perm || store.hasPerm(item.perm)),
|
||||
})).filter(group => group.items.length > 0),
|
||||
)
|
||||
|
||||
const currentTitle = computed(() => (route.meta.title as string) || '资金中台')
|
||||
|
||||
const warnVisible = ref(false)
|
||||
const remainMs = ref(SESSION_WARN_MS)
|
||||
let lastActive = Date.now()
|
||||
let timer = 0
|
||||
|
||||
const ACTIVITY_EVENTS = ['mousedown', 'keydown', 'touchstart', 'scroll', 'mousemove']
|
||||
|
||||
function markActive(): void {
|
||||
lastActive = Date.now()
|
||||
}
|
||||
|
||||
function tick(): void {
|
||||
const idle = Date.now() - lastActive
|
||||
if (idle >= SESSION_IDLE_MS) {
|
||||
forceLogout('长时间未操作,会话已自动退出')
|
||||
return
|
||||
}
|
||||
if (idle >= SESSION_IDLE_MS - SESSION_WARN_MS) {
|
||||
remainMs.value = SESSION_IDLE_MS - idle
|
||||
warnVisible.value = true
|
||||
} else if (warnVisible.value) {
|
||||
warnVisible.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function keepAlive(): void {
|
||||
markActive()
|
||||
warnVisible.value = false
|
||||
}
|
||||
|
||||
function forceLogout(message?: string): void {
|
||||
window.clearInterval(timer)
|
||||
store.logout()
|
||||
router.replace({ path: '/login', query: message ? { reason: 'expired', message } : { redirect: route.fullPath } })
|
||||
}
|
||||
|
||||
async function handleLogout(): Promise<void> {
|
||||
try {
|
||||
await ElMessageBox.confirm('退出后需重新进行双因子验证,是否继续?', '退出登录', {
|
||||
confirmButtonText: '退出登录',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
})
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
window.clearInterval(timer)
|
||||
store.logout()
|
||||
router.replace('/login')
|
||||
}
|
||||
|
||||
function goPassword(): void {
|
||||
router.push('/password')
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
ACTIVITY_EVENTS.forEach(event => window.addEventListener(event, markActive, { passive: true }))
|
||||
timer = window.setInterval(tick, 1000)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
ACTIVITY_EVENTS.forEach(event => window.removeEventListener(event, markActive))
|
||||
window.clearInterval(timer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="layout">
|
||||
<aside class="sidebar">
|
||||
<div class="brand">
|
||||
<div class="logo">F</div>
|
||||
<div class="brand-text">
|
||||
<div class="name">{{ APP_TITLE }}</div>
|
||||
<div class="sub">中央计费平台</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-menu class="side-menu" :default-active="route.path" router>
|
||||
<template v-for="group in groups" :key="group.title">
|
||||
<div class="group-title">{{ group.title }}</div>
|
||||
<el-menu-item v-for="item in group.items" :key="item.path" :index="item.path">
|
||||
<el-icon><component :is="item.icon" /></el-icon>
|
||||
<span>{{ item.title }}</span>
|
||||
</el-menu-item>
|
||||
</template>
|
||||
</el-menu>
|
||||
|
||||
<div class="sidebar-foot">
|
||||
<div>资金权威 · 全量审计</div>
|
||||
<div class="ver">v1.0.0 · 等保二级基线</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="main">
|
||||
<header class="topbar">
|
||||
<div class="left">
|
||||
<span class="page-title">{{ currentTitle }}</span>
|
||||
<el-tag size="small" type="info" effect="plain" class="env-tag">生产内网</el-tag>
|
||||
</div>
|
||||
<div class="right">
|
||||
<span class="session-hint" title="连续 30 分钟无操作将自动退出">
|
||||
<el-icon><Lock /></el-icon> 会话 30 分钟自动锁定
|
||||
</span>
|
||||
<el-tag size="small" effect="light" :type="store.role === 'AUDITOR' ? 'info' : store.role === 'FINANCE' ? 'success' : 'primary'">
|
||||
{{ store.role ? ROLE_LABEL[store.role] : '—' }}
|
||||
</el-tag>
|
||||
<el-dropdown trigger="click">
|
||||
<span class="user">
|
||||
<el-icon><UserFilled /></el-icon>
|
||||
<span>{{ store.displayName }}</span>
|
||||
<el-icon><ArrowDown /></el-icon>
|
||||
</span>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item @click="goPassword">修改密码</el-dropdown-item>
|
||||
<el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<router-view />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<el-dialog
|
||||
v-model="warnVisible"
|
||||
title="会话即将超时"
|
||||
width="420px"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="false"
|
||||
:show-close="false"
|
||||
>
|
||||
<p class="idle-text">
|
||||
检测到您已长时间未操作,系统将在
|
||||
<strong class="countdown">{{ secondsText(remainMs) }}</strong>
|
||||
后自动退出并清除本地会话。
|
||||
</p>
|
||||
<p class="idle-sub">如仍在处理资金业务,请点击「继续使用」。</p>
|
||||
<template #footer>
|
||||
<el-button @click="forceLogout('已手动退出会话')">立即退出</el-button>
|
||||
<el-button type="primary" @click="keepAlive">继续使用</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.layout {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 228px;
|
||||
flex: 0 0 228px;
|
||||
background: var(--fin-sidebar);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
color: #e6edf9;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 18px 18px 16px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #2f6bf0, #1d5bdb);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 800;
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.brand-text .name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
|
||||
.brand-text .sub {
|
||||
font-size: 11px;
|
||||
color: var(--fin-sidebar-text);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.side-menu {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.group-title {
|
||||
padding: 14px 24px 6px;
|
||||
font-size: 11px;
|
||||
color: #5f7392;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.sidebar-foot {
|
||||
padding: 12px 20px 16px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.06);
|
||||
font-size: 11px;
|
||||
color: #5f7392;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.sidebar-foot .ver {
|
||||
color: #465a78;
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
height: 56px;
|
||||
flex: 0 0 56px;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid var(--fin-border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 24px;
|
||||
}
|
||||
|
||||
.topbar .left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.env-tag {
|
||||
color: var(--fin-text-2);
|
||||
}
|
||||
|
||||
.topbar .right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.session-hint {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--fin-text-3);
|
||||
}
|
||||
|
||||
.user {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--fin-text);
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.idle-text {
|
||||
margin: 0 0 8px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.countdown {
|
||||
color: var(--el-color-danger);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.idle-sub {
|
||||
margin: 0;
|
||||
color: var(--fin-text-3);
|
||||
font-size: 13px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,37 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import { permission } from './directives/permission'
|
||||
import { setUnauthorizedHandler } from './utils/http'
|
||||
import { useUserStore } from './stores/user'
|
||||
import './styles/index.css'
|
||||
|
||||
const app = createApp(App)
|
||||
const pinia = createPinia()
|
||||
|
||||
app.use(pinia)
|
||||
app.use(router)
|
||||
app.use(ElementPlus, { locale: zhCn })
|
||||
|
||||
Object.entries(ElementPlusIconsVue).forEach(([key, component]) => {
|
||||
app.component(key, component)
|
||||
})
|
||||
|
||||
app.directive('perm', permission)
|
||||
|
||||
// 401 统一出口:清理本地会话并回到登录页
|
||||
setUnauthorizedHandler(() => {
|
||||
const store = useUserStore(pinia)
|
||||
store.logout()
|
||||
const current = router.currentRoute.value
|
||||
if (current.path !== '/login') {
|
||||
router.replace({ path: '/login', query: { redirect: current.fullPath } })
|
||||
}
|
||||
})
|
||||
|
||||
app.mount('#app')
|
||||
@@ -0,0 +1,986 @@
|
||||
import type {
|
||||
AccountInfo,
|
||||
AdminInfo,
|
||||
AppInfo,
|
||||
AppPolicy,
|
||||
AuditLog,
|
||||
ConfigItem,
|
||||
OrderInfo,
|
||||
PricingItem,
|
||||
ReconcileDiff,
|
||||
ReconcileReport,
|
||||
RefundInfo,
|
||||
TransactionInfo,
|
||||
TrendPoint,
|
||||
TxType,
|
||||
VipPlan,
|
||||
WebhookDelivery,
|
||||
} from '@/types'
|
||||
import { maskPhone } from '@/utils/mask'
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* 本地演示数据(Mock):仅用于前端联调与验收演示,不含任何真实密钥。
|
||||
* 真实环境由后端 MySQL 提供数据,前端不持有 client_secret 明文。
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
const pad = (n: number): string => String(n).padStart(2, '0')
|
||||
|
||||
export function timestamp(date: Date): string {
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
|
||||
date.getHours(),
|
||||
)}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
|
||||
export function daysAgo(days: number, hour = 10, minute = 0): string {
|
||||
const date = new Date()
|
||||
date.setDate(date.getDate() - days)
|
||||
date.setHours(hour, minute, 0, 0)
|
||||
return timestamp(date)
|
||||
}
|
||||
|
||||
export function now(): string {
|
||||
return timestamp(new Date())
|
||||
}
|
||||
|
||||
export function plusMinutes(minutes: number): string {
|
||||
const date = new Date()
|
||||
date.setMinutes(date.getMinutes() + minutes)
|
||||
return timestamp(date)
|
||||
}
|
||||
|
||||
export function plusDays(days: number): string {
|
||||
const date = new Date()
|
||||
date.setDate(date.getDate() + days)
|
||||
return timestamp(date)
|
||||
}
|
||||
|
||||
let seq = 100000
|
||||
export function nextId(): number {
|
||||
seq += 1
|
||||
return seq
|
||||
}
|
||||
|
||||
let seed = 20261027
|
||||
function rnd(): number {
|
||||
seed = (seed * 1103515245 + 12345) & 0x7fffffff
|
||||
return seed / 0x7fffffff
|
||||
}
|
||||
function int(min: number, max: number): number {
|
||||
return Math.floor(rnd() * (max - min + 1)) + min
|
||||
}
|
||||
function pick<T>(list: T[]): T {
|
||||
return list[Math.floor(rnd() * list.length)]
|
||||
}
|
||||
|
||||
/** 64 位十六进制摘要:仅用于 Mock 审计链演示,真实环境使用 SHA-256/SM3 */
|
||||
export function digest(input: string): string {
|
||||
let h1 = 0x811c9dc5
|
||||
let h2 = 0x01000193
|
||||
let h3 = 0x9e3779b9
|
||||
let h4 = 0x85ebca6b
|
||||
for (let i = 0; i < input.length; i += 1) {
|
||||
const code = input.charCodeAt(i)
|
||||
h1 = ((h1 ^ code) * 16777619) >>> 0
|
||||
h2 = ((h2 + code) * 2654435761) >>> 0
|
||||
h3 = ((h3 ^ (code << 3)) * 2246822519) >>> 0
|
||||
h4 = ((h4 + code * 131) * 3266489917) >>> 0
|
||||
}
|
||||
const hex = (value: number): string => (value >>> 0).toString(16).padStart(8, '0')
|
||||
return (
|
||||
hex(h1) + hex(h2) + hex(h3) + hex(h4) +
|
||||
hex(h1 ^ h2) + hex(h3 ^ h4) + hex((h1 + h3) >>> 0) + hex((h2 + h4) >>> 0)
|
||||
)
|
||||
}
|
||||
|
||||
/** 审计哈希链统一算法:种子数据、实时写入、链校验必须共用同一实现,否则校验必然误报断链 */
|
||||
export function auditHash(
|
||||
item: {
|
||||
id: number
|
||||
actorId: number | null
|
||||
actorName: string
|
||||
action: string
|
||||
targetType: string
|
||||
targetId: number | null
|
||||
beforeJson: string | null
|
||||
afterJson: string | null
|
||||
result: string
|
||||
createTime: string
|
||||
},
|
||||
prevHash: string,
|
||||
): string {
|
||||
return digest(
|
||||
JSON.stringify([
|
||||
item.id,
|
||||
item.actorId,
|
||||
item.actorName,
|
||||
item.action,
|
||||
item.targetType,
|
||||
item.targetId,
|
||||
item.beforeJson,
|
||||
item.afterJson,
|
||||
item.result,
|
||||
item.createTime,
|
||||
prevHash,
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
export const ROLE_PERMISSIONS: Record<string, string[]> = {
|
||||
SUPER_ADMIN: [
|
||||
'fin:view',
|
||||
'fin:export',
|
||||
'fin:app:manage',
|
||||
'fin:pricing:edit',
|
||||
'fin:vip:manage',
|
||||
'fin:admin:manage',
|
||||
'fin:config:edit',
|
||||
'fin:audit:view',
|
||||
'fin:webhook:manage',
|
||||
'fin:account:adjust',
|
||||
'fin:refund:review',
|
||||
'fin:order:cancel',
|
||||
'fin:reconcile:run',
|
||||
],
|
||||
FINANCE: [
|
||||
'fin:view',
|
||||
'fin:export',
|
||||
'fin:recharge:confirm',
|
||||
'fin:refund:create',
|
||||
'fin:refund:review',
|
||||
'fin:order:cancel',
|
||||
'fin:reconcile:run',
|
||||
],
|
||||
AUDITOR: ['fin:view', 'fin:export', 'fin:audit:view'],
|
||||
}
|
||||
|
||||
export interface AdminRecord extends AdminInfo {
|
||||
password: string
|
||||
passwordHistory: string[]
|
||||
}
|
||||
|
||||
export interface AppRecord extends AppInfo {
|
||||
/** 审计目标 ID(库表中应用以 app_code 为业务主键,此 ID 仅用于审计留痕) */
|
||||
id: number
|
||||
clientSecretHash: string
|
||||
clientSecretPrevHash: string
|
||||
webhookSecretEnc: string
|
||||
}
|
||||
|
||||
export interface PlanRecord extends VipPlan {}
|
||||
|
||||
export interface VipRecord {
|
||||
id: number
|
||||
appCode: string
|
||||
businessUserId: string
|
||||
vipPlanCode: string
|
||||
vipUntil: string
|
||||
}
|
||||
|
||||
export interface CashFlowRecord {
|
||||
id: number
|
||||
appCode: string
|
||||
orderId: number
|
||||
direction: 'IN' | 'OUT'
|
||||
amountCent: number
|
||||
receivedAt: string
|
||||
voucherNo: string
|
||||
operatorAdminId: number
|
||||
remark: string
|
||||
}
|
||||
|
||||
export interface RefundRecord extends RefundInfo {}
|
||||
|
||||
export interface TxRecord extends TransactionInfo {}
|
||||
|
||||
export interface OrderRecord extends OrderInfo {}
|
||||
|
||||
export interface WebhookRecord extends WebhookDelivery {}
|
||||
|
||||
export interface AuditRecord extends AuditLog {}
|
||||
|
||||
export interface ConfigRecord extends ConfigItem {}
|
||||
|
||||
export interface PricingRecord extends PricingItem {}
|
||||
|
||||
export interface PolicyRecord extends AppPolicy {}
|
||||
|
||||
export interface AccountRecord extends AccountInfo {
|
||||
phoneHash: string
|
||||
status: 'ACTIVE'
|
||||
firstSeenAt: string
|
||||
}
|
||||
|
||||
export interface AppTokenRecord {
|
||||
id: number
|
||||
appCode: string
|
||||
tokenHash: string
|
||||
expiresAt: string
|
||||
revokedAt: string | null
|
||||
issuedIp: string
|
||||
createTime: string
|
||||
}
|
||||
|
||||
export interface TicketRecord {
|
||||
ticket: string
|
||||
appCode: string
|
||||
businessUserId: string
|
||||
expiresAt: string
|
||||
usedAt: string | null
|
||||
}
|
||||
|
||||
export interface ReconcileRecord extends ReconcileReport {}
|
||||
|
||||
export interface MockState {
|
||||
admins: AdminRecord[]
|
||||
apps: AppRecord[]
|
||||
accounts: AccountRecord[]
|
||||
orders: OrderRecord[]
|
||||
transactions: TxRecord[]
|
||||
refunds: RefundRecord[]
|
||||
cashFlows: CashFlowRecord[]
|
||||
plans: PlanRecord[]
|
||||
vips: VipRecord[]
|
||||
pricing: PricingRecord[]
|
||||
policies: PolicyRecord[]
|
||||
configs: ConfigRecord[]
|
||||
audits: AuditRecord[]
|
||||
webhooks: WebhookRecord[]
|
||||
tokens: AppTokenRecord[]
|
||||
tickets: TicketRecord[]
|
||||
reports: ReconcileRecord[]
|
||||
sessions: Map<string, { adminId: number; expiresAt: number }>
|
||||
/** 支付下单幂等索引:幂等键 → 订单 ID,防止网络重试造成重复下单 */
|
||||
idempotency: Map<string, number>
|
||||
}
|
||||
|
||||
const USERS = [
|
||||
{ id: 'u10001', name: '张伟', phone: '13800138000' },
|
||||
{ id: 'u10002', name: '李娜', phone: '13912345678' },
|
||||
{ id: 'u10003', name: '王强', phone: '13755556666' },
|
||||
{ id: 'u10004', name: '刘洋', phone: '15011112222' },
|
||||
{ id: 'u10005', name: '陈静', phone: '18800009999' },
|
||||
{ id: 'u10006', name: '杨帆', phone: '13566667777' },
|
||||
{ id: 'u10007', name: '赵敏', phone: '13633334444' },
|
||||
{ id: 'u10008', name: '周涛', phone: '15988887777' },
|
||||
{ id: 'u10009', name: '孙悦', phone: '13322221111' },
|
||||
{ id: 'u10010', name: '吴斌', phone: '18900001111' },
|
||||
{ id: 'u10011', name: '郑凯', phone: '18655554444' },
|
||||
{ id: 'u10012', name: '冯雪', phone: '13277778888' },
|
||||
]
|
||||
|
||||
function buildAdmins(): AdminRecord[] {
|
||||
const base = {
|
||||
isActive: 1,
|
||||
mustChangePassword: 0,
|
||||
totpBound: true,
|
||||
failedAttempts: 0,
|
||||
lockedUntil: null,
|
||||
lastLoginIp: '10.10.8.21',
|
||||
createTime: '2025-12-01 09:00:00',
|
||||
}
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
id: 1,
|
||||
username: 'admin',
|
||||
password: 'Super@Fin2026',
|
||||
passwordHistory: [],
|
||||
role: 'SUPER_ADMIN',
|
||||
lastLoginAt: daysAgo(0, 8, 42),
|
||||
},
|
||||
{
|
||||
...base,
|
||||
id: 2,
|
||||
username: 'finance',
|
||||
password: 'Fin@2026Fund',
|
||||
passwordHistory: [],
|
||||
role: 'FINANCE',
|
||||
lastLoginAt: daysAgo(0, 9, 12),
|
||||
},
|
||||
{
|
||||
...base,
|
||||
id: 3,
|
||||
username: 'auditor',
|
||||
password: 'Audit@2026View',
|
||||
passwordHistory: [],
|
||||
role: 'AUDITOR',
|
||||
lastLoginAt: daysAgo(1, 16, 5),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function buildApps(): AppRecord[] {
|
||||
return [
|
||||
{
|
||||
id: nextId(),
|
||||
appCode: 'litho-sim',
|
||||
appName: '光刻仿真平台',
|
||||
allowedRedirectHosts: 'sim.gaszk.com,sim.gaszk.cn',
|
||||
webhookUrl: 'https://sim.gaszk.com/api/finance/webhook',
|
||||
webhookSecretEnc: 'enc:webhook:litho',
|
||||
tokenTtlSeconds: 900,
|
||||
enabled: 1,
|
||||
clientSecretHash: '$argon2id$mock$litho',
|
||||
clientSecretPrevHash: '',
|
||||
hasPrevSecret: false,
|
||||
secretExpiresAt: null,
|
||||
createTime: daysAgo(180, 9, 0),
|
||||
accountCount: 0,
|
||||
todayAmountCent: 0,
|
||||
},
|
||||
{
|
||||
id: nextId(),
|
||||
appCode: 'libs-platform',
|
||||
appName: 'LIBS 显微检测数据中台',
|
||||
allowedRedirectHosts: 'libs.gaszk.com',
|
||||
webhookUrl: 'https://libs.gaszk.com/api/fin/webhook',
|
||||
webhookSecretEnc: 'enc:webhook:libs',
|
||||
tokenTtlSeconds: 900,
|
||||
enabled: 1,
|
||||
clientSecretHash: '$argon2id$mock$libs',
|
||||
clientSecretPrevHash: '',
|
||||
hasPrevSecret: false,
|
||||
secretExpiresAt: null,
|
||||
createTime: daysAgo(120, 10, 30),
|
||||
accountCount: 0,
|
||||
todayAmountCent: 0,
|
||||
},
|
||||
{
|
||||
id: nextId(),
|
||||
appCode: 'mall-pro',
|
||||
appName: '工业耗材商城',
|
||||
allowedRedirectHosts: 'mall.gaszk.com',
|
||||
webhookUrl: '',
|
||||
webhookSecretEnc: 'enc:webhook:mall',
|
||||
tokenTtlSeconds: 1800,
|
||||
enabled: 0,
|
||||
clientSecretHash: '$argon2id$mock$mall',
|
||||
clientSecretPrevHash: '',
|
||||
hasPrevSecret: false,
|
||||
secretExpiresAt: null,
|
||||
createTime: daysAgo(60, 14, 0),
|
||||
accountCount: 0,
|
||||
todayAmountCent: 0,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function buildPlans(apps: AppRecord[]): PlanRecord[] {
|
||||
const defs: Array<[string, string, string, number, number, number]> = [
|
||||
['litho-sim', 'VIP_MONTH', '专业版 · 月付', 30, 9900, 1],
|
||||
['litho-sim', 'VIP_QUARTER', '专业版 · 季付', 90, 26900, 1],
|
||||
['litho-sim', 'VIP_YEAR', '专业版 · 年付', 365, 89900, 1],
|
||||
['libs-platform', 'PRO_MONTH', '检测专业版 · 月付', 30, 19900, 0],
|
||||
['libs-platform', 'PRO_QUARTER', '检测专业版 · 季付', 90, 53900, 0],
|
||||
]
|
||||
return defs.map(([appCode, planCode, planName, durationDays, priceCent, freeDeduction]) => ({
|
||||
id: nextId(),
|
||||
appCode,
|
||||
appName: apps.find(item => item.appCode === appCode)?.appName || appCode,
|
||||
planCode,
|
||||
planName,
|
||||
durationDays,
|
||||
priceCent,
|
||||
freeDeduction,
|
||||
enabled: 1,
|
||||
holderCount: 0,
|
||||
createTime: daysAgo(90, 9, 0),
|
||||
}))
|
||||
}
|
||||
|
||||
function buildAccounts(apps: AppRecord[], plans: PlanRecord[], transactions: TxRecord[], vips: VipRecord[]): AccountRecord[] {
|
||||
const map: Record<string, number[]> = {
|
||||
'litho-sim': [0, 1, 2, 3, 4, 5, 6, 7, 8],
|
||||
'libs-platform': [0, 1, 2, 3, 4, 5],
|
||||
'mall-pro': [6, 7, 8, 9, 10, 11],
|
||||
}
|
||||
const accounts: AccountRecord[] = []
|
||||
|
||||
apps.forEach(app => {
|
||||
const indexes = map[app.appCode] || [0, 1]
|
||||
indexes.forEach((userIndex, order) => {
|
||||
const user = USERS[userIndex]
|
||||
const accountId = nextId()
|
||||
let balance = 0
|
||||
let totalSpent = 0
|
||||
let versionNo = 0
|
||||
const txCount = 4 + int(0, 5)
|
||||
for (let i = 0; i < txCount; i += 1) {
|
||||
let type: TxType = 'RECHARGE'
|
||||
const roll = rnd()
|
||||
if (i === 0) type = 'RECHARGE'
|
||||
else if (roll < 0.5) type = 'CONSUME'
|
||||
else if (roll < 0.65) type = 'RECHARGE'
|
||||
else if (roll < 0.8) type = 'CONSUME_FREE'
|
||||
else if (roll < 0.92) type = 'CONSUME'
|
||||
else type = 'REFUND_IN'
|
||||
|
||||
let amount = 0
|
||||
if (type === 'RECHARGE') amount = pick([1000, 2000, 3000, 5000, 10000, 20000])
|
||||
else if (type === 'REFUND_IN') amount = int(50, 300)
|
||||
else if (type === 'CONSUME_FREE') amount = 0
|
||||
else amount = int(30, 1200)
|
||||
|
||||
if (type === 'CONSUME' && balance < amount) {
|
||||
type = 'RECHARGE'
|
||||
amount = pick([2000, 5000, 10000])
|
||||
}
|
||||
|
||||
const before = balance
|
||||
if (type === 'RECHARGE' || type === 'REFUND_IN') balance += amount
|
||||
else if (type === 'CONSUME') {
|
||||
balance -= amount
|
||||
totalSpent += amount
|
||||
}
|
||||
|
||||
versionNo += 1
|
||||
transactions.push({
|
||||
id: nextId(),
|
||||
appCode: app.appCode,
|
||||
appName: app.appName,
|
||||
businessUserId: user.id,
|
||||
usernameSnapshot: user.name,
|
||||
type,
|
||||
amount,
|
||||
balanceBefore: before,
|
||||
balanceAfter: balance,
|
||||
businessRefId: type === 'CONSUME' ? `${app.appCode}:task:${9000 + order * 10 + i}` : null,
|
||||
idempotencyKey:
|
||||
type === 'RECHARGE'
|
||||
? `order:RC${app.appCode}:${order}${i}`
|
||||
: `${app.appCode}:${type.toLowerCase()}:${order}${i}${int(100, 999)}`,
|
||||
orderId: null,
|
||||
outTradeNo: null,
|
||||
refundOfId: null,
|
||||
refundedPoints: 0,
|
||||
operatorAdminName: type === 'RECHARGE' ? 'finance' : null,
|
||||
remark: type === 'CONSUME_FREE' ? 'VIP_FREE' : '',
|
||||
createTime: daysAgo(20 - Math.floor((i * 18) / txCount), 9 + int(0, 8), int(0, 59)),
|
||||
})
|
||||
}
|
||||
|
||||
const account: AccountRecord = {
|
||||
id: accountId,
|
||||
appCode: app.appCode,
|
||||
appName: app.appName,
|
||||
businessUserId: user.id,
|
||||
usernameSnapshot: user.name,
|
||||
phoneMasked: maskPhone(user.phone),
|
||||
phoneHash: digest(user.phone),
|
||||
status: 'ACTIVE',
|
||||
balance,
|
||||
totalSpent,
|
||||
versionNo,
|
||||
vipPlanCode: null,
|
||||
vipUntil: null,
|
||||
firstSeenAt: daysAgo(30 - order),
|
||||
createTime: daysAgo(30 - order),
|
||||
updateTime: daysAgo(0, 9, 30),
|
||||
}
|
||||
|
||||
const plan = plans.find(item => item.appCode === app.appCode && item.freeDeduction === 1)
|
||||
if (plan && order % 3 === 0) {
|
||||
account.vipPlanCode = plan.planCode
|
||||
account.vipUntil = plusDays(int(5, 200))
|
||||
vips.push({
|
||||
id: nextId(),
|
||||
appCode: app.appCode,
|
||||
businessUserId: user.id,
|
||||
vipPlanCode: plan.planCode,
|
||||
vipUntil: account.vipUntil,
|
||||
})
|
||||
}
|
||||
|
||||
accounts.push(account)
|
||||
})
|
||||
})
|
||||
|
||||
return accounts
|
||||
}
|
||||
|
||||
function buildOrders(apps: AppRecord[], accounts: AccountRecord[], plans: PlanRecord[], admins: AdminRecord[]): {
|
||||
orders: OrderRecord[]
|
||||
cashFlows: CashFlowRecord[]
|
||||
refunds: RefundRecord[]
|
||||
webhooks: WebhookRecord[]
|
||||
} {
|
||||
const enabledApps = apps.filter(app => app.enabled === 1)
|
||||
const orders: OrderRecord[] = []
|
||||
const cashFlows: CashFlowRecord[] = []
|
||||
const refunds: RefundRecord[] = []
|
||||
const webhooks: WebhookRecord[] = []
|
||||
const finance = admins.find(item => item.role === 'FINANCE') || admins[1]
|
||||
const superAdmin = admins.find(item => item.role === 'SUPER_ADMIN') || admins[0]
|
||||
const threshold = 500000
|
||||
|
||||
for (let i = 0; i < 46; i += 1) {
|
||||
const app = pick(enabledApps)
|
||||
const candidates = accounts.filter(item => item.appCode === app.appCode)
|
||||
if (!candidates.length) continue
|
||||
const account = pick(candidates)
|
||||
const orderType = rnd() < 0.22 ? 'vip' : 'recharge'
|
||||
const planList = plans.filter(item => item.appCode === app.appCode && item.enabled === 1)
|
||||
const plan = planList.length ? pick(planList) : null
|
||||
const amountCent = orderType === 'vip' && plan ? plan.priceCent : pick([1000, 2000, 5000, 10000, 20000, 50000])
|
||||
const pricingRate = app.appCode === 'libs-platform' ? 80 : 100
|
||||
const pointsGained = orderType === 'vip' ? 0 : Math.floor((amountCent / 100) * pricingRate)
|
||||
const dayAgo = i < 8 ? 0 : int(0, 18)
|
||||
const createTime = daysAgo(dayAgo, int(8, 19), int(0, 59))
|
||||
|
||||
const roll = rnd()
|
||||
let status: OrderRecord['status'] = 'PAID'
|
||||
if (roll > 0.94) status = 'REFUNDED'
|
||||
else if (roll > 0.82) status = 'PENDING'
|
||||
else if (roll > 0.76) status = 'CANCELLED'
|
||||
|
||||
const datePart = createTime.slice(0, 10).replace(/-/g, '')
|
||||
const outTradeNo = `${orderType === 'vip' ? 'VIP' : 'RC'}${datePart}${String(1000 + i).slice(-4)}`
|
||||
const needDualControl = amountCent >= threshold
|
||||
const paidAt = status === 'PAID' || status === 'REFUNDED' ? createTime.replace(/(\d\d):(\d\d):\d\d$/, '$1:$2:30') : null
|
||||
const secondApprover = needDualControl ? superAdmin : null
|
||||
|
||||
orders.push({
|
||||
id: nextId(),
|
||||
outTradeNo,
|
||||
appCode: app.appCode,
|
||||
appName: app.appName,
|
||||
businessUserId: account.businessUserId,
|
||||
usernameSnapshot: account.usernameSnapshot,
|
||||
orderType,
|
||||
payMethod: 'offline',
|
||||
amountCent,
|
||||
pointsGained,
|
||||
vipPlanCode: orderType === 'vip' && plan ? plan.planCode : null,
|
||||
status,
|
||||
expiresAt: status === 'PENDING' ? plusDays(1) : createTime,
|
||||
paidAt,
|
||||
confirmedByAdminId: paidAt ? finance.id : null,
|
||||
confirmedByAdminName: paidAt ? finance.username : null,
|
||||
secondApproverId: paidAt && secondApprover ? secondApprover.id : null,
|
||||
secondApproverName: paidAt && secondApprover ? secondApprover.username : null,
|
||||
remark: status === 'CANCELLED' ? '用户取消' : '',
|
||||
createTime,
|
||||
refundedAmountCent: 0,
|
||||
cashInCent: 0,
|
||||
cashOutCent: 0,
|
||||
needDualControl,
|
||||
})
|
||||
}
|
||||
|
||||
orders.forEach(order => {
|
||||
if (order.status === 'PAID' || order.status === 'REFUNDED') {
|
||||
const cashId = nextId()
|
||||
cashFlows.push({
|
||||
id: cashId,
|
||||
appCode: order.appCode,
|
||||
orderId: order.id,
|
||||
direction: 'IN',
|
||||
amountCent: order.amountCent,
|
||||
receivedAt: order.paidAt || order.createTime,
|
||||
voucherNo: `BK${order.createTime.slice(0, 10).replace(/-/g, '')}${String(order.id).slice(-4)}`,
|
||||
operatorAdminId: order.confirmedByAdminId || 2,
|
||||
remark: '对公转账到账',
|
||||
})
|
||||
order.cashInCent = order.amountCent
|
||||
}
|
||||
})
|
||||
|
||||
const refundTargets = orders.filter(item => item.status === 'REFUNDED')
|
||||
refundTargets.forEach((order, index) => {
|
||||
const status: RefundInfo['status'] = index === 0 ? 'COMPLETED' : index === 1 ? 'PENDING' : index === 2 ? 'REJECTED' : 'COMPLETED'
|
||||
const pointsDeducted = Math.max(0, Math.min(order.pointsGained, order.pointsGained))
|
||||
const refund: RefundRecord = {
|
||||
id: nextId(),
|
||||
appCode: order.appCode,
|
||||
appName: order.appName,
|
||||
businessUserId: order.businessUserId,
|
||||
usernameSnapshot: order.usernameSnapshot,
|
||||
orderId: order.id,
|
||||
outTradeNo: order.outTradeNo,
|
||||
amountCent: order.amountCent,
|
||||
pointsDeducted,
|
||||
status,
|
||||
operatorAdminId: 2,
|
||||
operatorAdminName: 'finance',
|
||||
reviewerAdminId: status === 'PENDING' ? null : 1,
|
||||
reviewerAdminName: status === 'PENDING' ? null : 'admin',
|
||||
voucherNo: status === 'REJECTED' ? '' : `RF${order.createTime.slice(0, 10).replace(/-/g, '')}${String(order.id).slice(-4)}`,
|
||||
remark: status === 'REJECTED' ? '客户撤销退款申请' : '客户申请退费',
|
||||
createTime: order.paidAt ? order.paidAt.replace(/(\d\d):(\d\d):\d\d$/, '$1:$2:40') : order.createTime,
|
||||
updateTime: now(),
|
||||
}
|
||||
refunds.push(refund)
|
||||
order.refundedAmountCent = status === 'REJECTED' ? 0 : order.amountCent
|
||||
order.cashOutCent = status === 'COMPLETED' ? order.amountCent : 0
|
||||
if (status === 'COMPLETED') {
|
||||
cashFlows.push({
|
||||
id: nextId(),
|
||||
appCode: order.appCode,
|
||||
orderId: order.id,
|
||||
direction: 'OUT',
|
||||
amountCent: order.amountCent,
|
||||
receivedAt: refund.updateTime,
|
||||
voucherNo: refund.voucherNo,
|
||||
operatorAdminId: 2,
|
||||
remark: '现金退款',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
orders.forEach(order => {
|
||||
if (order.status === 'PAID' || order.status === 'REFUNDED') {
|
||||
const events = ['order.paid']
|
||||
if (order.status === 'REFUNDED') events.push('order.refunded')
|
||||
events.forEach(eventType => {
|
||||
const roll = rnd()
|
||||
const status: WebhookDelivery['status'] = roll < 0.72 ? 'SENT' : roll < 0.9 ? 'FAILED' : 'DEAD'
|
||||
webhooks.push({
|
||||
id: nextId(),
|
||||
appCode: order.appCode,
|
||||
appName: order.appName,
|
||||
eventId: `evt_${digest(`${order.outTradeNo}${eventType}`).slice(0, 20)}`,
|
||||
eventType,
|
||||
status,
|
||||
attempts: status === 'SENT' ? 1 : status === 'FAILED' ? 3 : 6,
|
||||
nextRetryAt: status === 'FAILED' ? plusMinutes(30) : null,
|
||||
lastError: status === 'SENT' ? '' : status === 'FAILED' ? 'connect timeout (10s)' : 'HTTP 502 连续 6 次失败',
|
||||
payload: JSON.stringify(
|
||||
{
|
||||
eventId: `evt_${order.outTradeNo}`,
|
||||
eventType,
|
||||
appCode: order.appCode,
|
||||
businessUserId: order.businessUserId,
|
||||
outTradeNo: order.outTradeNo,
|
||||
amountCent: order.amountCent,
|
||||
points: order.pointsGained,
|
||||
occurredAt: order.paidAt,
|
||||
},
|
||||
null,
|
||||
0,
|
||||
),
|
||||
createTime: order.paidAt || order.createTime,
|
||||
updateTime: order.paidAt || order.createTime,
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return { orders, cashFlows, refunds, webhooks }
|
||||
}
|
||||
|
||||
function buildConfigs(): ConfigRecord[] {
|
||||
const list: Array<[string, string, string, 'HIGH' | 'NORMAL']> = [
|
||||
['order.pending.timeout_hours', '24', '待确认订单超时关单时长(小时),对公转账晚到可调至 72', 'NORMAL'],
|
||||
['review.threshold_cent', '500000', '双人复核金额阈值(分),默认 ¥5000', 'NORMAL'],
|
||||
['admin.lock.threshold', '5', '管理员登录失败锁定次数', 'NORMAL'],
|
||||
['admin.lock.minutes', '15', '管理员锁定时长(分钟)', 'NORMAL'],
|
||||
['ticket.ttl_minutes', '5', '一次性凭证有效期(分钟)', 'NORMAL'],
|
||||
['token.ttl_seconds', '900', 'client token 有效期(秒)', 'NORMAL'],
|
||||
['secret.rotate.grace_hours', '24', '密钥轮换宽限期(小时)', 'NORMAL'],
|
||||
['charge.retry.max', '3', '乐观锁冲突服务端重试次数', 'NORMAL'],
|
||||
['webhook.max_retry', '6', 'webhook 最大重试次数', 'NORMAL'],
|
||||
['pii.mask.enabled', '1', 'PII 掩码开关,关闭属高危变更', 'HIGH'],
|
||||
]
|
||||
return list.map(([configKey, configValue, description, risk], index) => ({
|
||||
configKey,
|
||||
configValue,
|
||||
description,
|
||||
risk,
|
||||
updateBy: index % 4 === 0 ? 'admin' : 'system',
|
||||
updateTime: daysAgo(index + 3, 10, 20),
|
||||
}))
|
||||
}
|
||||
|
||||
function buildAudits(admins: AdminRecord[], apps: AppRecord[]): AuditRecord[] {
|
||||
const actions: Array<[string, string, string, string, string]> = [
|
||||
['LOGIN', '管理员登录', 'ADMIN', '', ''],
|
||||
['ORDER_CONFIRM', '确认订单到账', 'ORDER', '{"status":"PENDING"}', '{"status":"PAID"}'],
|
||||
['PRICING_UPDATE', '修改兑率', 'PRICING', '{"pointsPerYuan":90}', '{"pointsPerYuan":100}'],
|
||||
['APP_SECRET_ROTATE', '轮换应用密钥', 'APP', '', '{"graceHours":24}'],
|
||||
['REFUND_CREATE', '发起现金退款', 'REFUND', '', '{"status":"PENDING"}'],
|
||||
['REFUND_REVIEW', '复核现金退款', 'REFUND', '{"status":"PENDING"}', '{"status":"COMPLETED"}'],
|
||||
['ADMIN_CREATE', '创建管理员', 'ADMIN', '', '{"role":"FINANCE"}'],
|
||||
['CONFIG_UPDATE', '修改全局参数', 'CONFIG', '{"value":"24"}', '{"value":"72"}'],
|
||||
['ORDER_CANCEL', '关闭订单', 'ORDER', '{"status":"PENDING"}', '{"status":"CANCELLED"}'],
|
||||
['ACCOUNT_ADJUST', '人工调账', 'ACCOUNT', '{"balance":100}', '{"balance":200}'],
|
||||
]
|
||||
const audits: AuditRecord[] = []
|
||||
let prevHash = ''
|
||||
for (let i = 0; i < 48; i += 1) {
|
||||
const actor = pick(admins)
|
||||
const [action, actionLabel, targetType, beforeJson, afterJson] = pick(actions)
|
||||
const createTime = daysAgo(14 - Math.floor(i / 4), 8 + (i % 10), (i * 7) % 60)
|
||||
const app = pick(apps)
|
||||
const record: AuditRecord = {
|
||||
id: nextId(),
|
||||
actorType: 'ADMIN',
|
||||
actorId: actor.id,
|
||||
actorName: actor.username,
|
||||
action,
|
||||
actionLabel,
|
||||
targetType: action === 'APP_SECRET_ROTATE' ? 'APP' : targetType,
|
||||
targetId: action === 'APP_SECRET_ROTATE' ? app.id : nextId(),
|
||||
beforeJson: beforeJson || null,
|
||||
afterJson: afterJson || null,
|
||||
ip: `10.10.8.${20 + (i % 8)}`,
|
||||
ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/126.0',
|
||||
result: i % 17 === 0 ? 'FAILED' : 'SUCCESS',
|
||||
prevHash,
|
||||
curHash: '',
|
||||
createTime,
|
||||
}
|
||||
record.curHash = auditHash(record, prevHash)
|
||||
audits.push(record)
|
||||
prevHash = record.curHash
|
||||
}
|
||||
return audits
|
||||
}
|
||||
|
||||
export function appendAudit(input: {
|
||||
actorId: number | null
|
||||
actorName: string
|
||||
action: string
|
||||
actionLabel: string
|
||||
targetType: string
|
||||
targetId: number | null
|
||||
beforeJson?: string | null
|
||||
afterJson?: string | null
|
||||
ip?: string
|
||||
result?: 'SUCCESS' | 'FAILED'
|
||||
}): AuditRecord {
|
||||
const lastHash = db.audits.length ? db.audits[db.audits.length - 1].curHash : ''
|
||||
const createTime = now()
|
||||
const record: AuditRecord = {
|
||||
id: nextId(),
|
||||
actorType: input.actorId ? 'ADMIN' : 'SYSTEM',
|
||||
actorId: input.actorId,
|
||||
actorName: input.actorName,
|
||||
action: input.action,
|
||||
actionLabel: input.actionLabel,
|
||||
targetType: input.targetType,
|
||||
targetId: input.targetId,
|
||||
beforeJson: input.beforeJson || null,
|
||||
afterJson: input.afterJson || null,
|
||||
ip: input.ip || '10.10.8.21',
|
||||
ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/126.0',
|
||||
result: input.result || 'SUCCESS',
|
||||
prevHash: lastHash,
|
||||
curHash: '',
|
||||
createTime,
|
||||
}
|
||||
record.curHash = auditHash(record, lastHash)
|
||||
db.audits.push(record)
|
||||
return record
|
||||
}
|
||||
|
||||
function computeTrend(): TrendPoint[] {
|
||||
const points: TrendPoint[] = []
|
||||
for (let i = 13; i >= 0; i -= 1) {
|
||||
const date = daysAgo(i).slice(0, 10)
|
||||
const amountCent = db.cashFlows
|
||||
.filter(item => item.direction === 'IN' && item.receivedAt.slice(0, 10) === date)
|
||||
.reduce((sum, item) => sum + item.amountCent, 0)
|
||||
const consumed = db.transactions
|
||||
.filter(item => item.type === 'CONSUME' && item.createTime.slice(0, 10) === date)
|
||||
.reduce((sum, item) => sum + item.amount, 0)
|
||||
const orderCount = db.orders.filter(item => item.createTime.slice(0, 10) === date).length
|
||||
points.push({ date: date.slice(5), amountCent, points: consumed, orderCount })
|
||||
}
|
||||
return points
|
||||
}
|
||||
|
||||
export function trendData(): TrendPoint[] {
|
||||
return computeTrend()
|
||||
}
|
||||
|
||||
export function buildReport(appCode: string, windowStart: string, windowEnd: string, createdBy: string): ReconcileRecord {
|
||||
const app = db.apps.find(item => item.appCode === appCode)
|
||||
const start = `${windowStart} 00:00:00`
|
||||
const end = `${windowEnd} 23:59:59`
|
||||
const inRange = (value: string | null): boolean => !!value && value >= start && value <= end
|
||||
|
||||
const cashInCent = db.cashFlows
|
||||
.filter(item => item.appCode === appCode && item.direction === 'IN' && inRange(item.receivedAt))
|
||||
.reduce((sum, item) => sum + item.amountCent, 0)
|
||||
const cashOutCent = db.cashFlows
|
||||
.filter(item => item.appCode === appCode && item.direction === 'OUT' && inRange(item.receivedAt))
|
||||
.reduce((sum, item) => sum + item.amountCent, 0)
|
||||
const cashPaidOrderCent = db.orders
|
||||
.filter(item => item.appCode === appCode && (item.status === 'PAID' || item.status === 'REFUNDED') && inRange(item.paidAt))
|
||||
.reduce((sum, item) => sum + item.amountCent, 0)
|
||||
const cashRefundedCent = db.refunds
|
||||
.filter(item => item.appCode === appCode && item.status === 'COMPLETED' && inRange(item.updateTime))
|
||||
.reduce((sum, item) => sum + item.amountCent, 0)
|
||||
|
||||
const accounts = db.accounts.filter(item => item.appCode === appCode)
|
||||
const walletSum = accounts.reduce((sum, item) => sum + item.balance, 0)
|
||||
let computedSum = 0
|
||||
let brokenChains = 0
|
||||
|
||||
accounts.forEach(account => {
|
||||
const txList = db.transactions
|
||||
.filter(item => item.appCode === appCode && item.businessUserId === account.businessUserId)
|
||||
.sort((a, b) => a.createTime.localeCompare(b.createTime))
|
||||
let expected = 0
|
||||
let broken = false
|
||||
txList.forEach(tx => {
|
||||
if (tx.balanceBefore !== expected) broken = true
|
||||
if (tx.type === 'RECHARGE' || tx.type === 'REFUND_IN') expected += tx.amount
|
||||
else if (tx.type === 'CONSUME' || tx.type === 'REFUND_OUT') expected -= tx.amount
|
||||
else if (tx.type === 'ADJUST') expected += tx.balanceAfter - tx.balanceBefore
|
||||
})
|
||||
computedSum += expected
|
||||
if (broken) brokenChains += 1
|
||||
})
|
||||
|
||||
const cashDiffCent = cashInCent - cashPaidOrderCent - (cashOutCent - cashRefundedCent)
|
||||
const pointsDiff = walletSum - computedSum
|
||||
const details: ReconcileDiff[] = []
|
||||
if (pointsDiff !== 0) {
|
||||
details.push({
|
||||
level: 'APP',
|
||||
target: appCode,
|
||||
expected: computedSum,
|
||||
actual: walletSum,
|
||||
diff: pointsDiff,
|
||||
reason: '流水累计与钱包余额不一致,需人工核查是否存在漏记流水',
|
||||
})
|
||||
}
|
||||
if (brokenChains > 0) {
|
||||
details.push({
|
||||
level: 'APP',
|
||||
target: appCode,
|
||||
expected: 0,
|
||||
actual: brokenChains,
|
||||
diff: brokenChains,
|
||||
reason: `${brokenChains} 个账户流水前后余额断链(疑似篡改或漏记)`,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
id: `RC${windowEnd.replace(/-/g, '')}${String(db.reports.length + 1).padStart(3, '0')}`,
|
||||
appCode,
|
||||
appName: app?.appName || appCode,
|
||||
windowStart,
|
||||
windowEnd,
|
||||
snapshotAt: now(),
|
||||
cashInCent,
|
||||
cashPaidOrderCent,
|
||||
cashOutCent,
|
||||
cashRefundedCent,
|
||||
cashDiffCent,
|
||||
walletSum,
|
||||
computedSum,
|
||||
pointsDiff,
|
||||
brokenChains,
|
||||
diffCount: details.length,
|
||||
status: details.length === 0 ? 'BALANCED' : 'DIFF',
|
||||
createdBy,
|
||||
createTime: now(),
|
||||
details,
|
||||
}
|
||||
}
|
||||
|
||||
function buildSeedReports(): ReconcileRecord[] {
|
||||
const yesterday = daysAgo(1).slice(0, 10)
|
||||
const balanced = buildReport('litho-sim', yesterday, yesterday, 'system')
|
||||
balanced.id = 'RC' + yesterday.replace(/-/g, '') + '001'
|
||||
balanced.createTime = daysAgo(1, 2, 0)
|
||||
balanced.snapshotAt = daysAgo(1, 2, 0)
|
||||
|
||||
const threeDaysAgo = daysAgo(3).slice(0, 10)
|
||||
const diff = buildReport('libs-platform', threeDaysAgo, threeDaysAgo, 'system')
|
||||
diff.id = 'RC' + threeDaysAgo.replace(/-/g, '') + '002'
|
||||
diff.createTime = daysAgo(3, 2, 0)
|
||||
diff.snapshotAt = daysAgo(3, 2, 0)
|
||||
diff.pointsDiff = 60
|
||||
diff.walletSum = diff.computedSum + 60
|
||||
diff.diffCount = 1
|
||||
diff.status = 'DIFF'
|
||||
diff.details = [
|
||||
{
|
||||
level: 'SUBJECT',
|
||||
target: 'u10003',
|
||||
expected: diff.computedSum - 120,
|
||||
actual: diff.computedSum - 60,
|
||||
diff: 60,
|
||||
reason: '点数侧钱包余额高于流水累计 60 点,疑似漏记一笔扣费流水',
|
||||
},
|
||||
]
|
||||
return [balanced, diff]
|
||||
}
|
||||
|
||||
function initState(): MockState {
|
||||
const admins = buildAdmins()
|
||||
const apps = buildApps()
|
||||
const plans = buildPlans(apps)
|
||||
const transactions: TxRecord[] = []
|
||||
const vips: VipRecord[] = []
|
||||
const accounts = buildAccounts(apps, plans, transactions, vips)
|
||||
const { orders, cashFlows, refunds, webhooks } = buildOrders(apps, accounts, plans, admins)
|
||||
|
||||
const pricing: PricingRecord[] = apps.map(app => ({
|
||||
appCode: app.appCode,
|
||||
appName: app.appName,
|
||||
pointsPerYuan: app.appCode === 'libs-platform' ? 80 : 100,
|
||||
enabled: app.enabled,
|
||||
updateTime: daysAgo(12, 11, 0),
|
||||
}))
|
||||
|
||||
const policies: PolicyRecord[] = apps.map(app => ({
|
||||
appCode: app.appCode,
|
||||
appName: app.appName,
|
||||
minCost: app.appCode === 'libs-platform' ? 200 : 100,
|
||||
maxPointsPerCharge: app.appCode === 'libs-platform' ? 20000 : 50000,
|
||||
vipExempt: app.appCode === 'libs-platform' ? 0 : 1,
|
||||
failedStrategy: 'none',
|
||||
dualControlThresholdCent: 500000,
|
||||
enabled: app.enabled,
|
||||
updateTime: daysAgo(12, 11, 5),
|
||||
}))
|
||||
|
||||
const state: MockState = {
|
||||
admins,
|
||||
apps,
|
||||
accounts,
|
||||
orders,
|
||||
transactions,
|
||||
refunds,
|
||||
cashFlows,
|
||||
plans,
|
||||
vips,
|
||||
pricing,
|
||||
policies,
|
||||
configs: buildConfigs(),
|
||||
audits: [],
|
||||
webhooks,
|
||||
tokens: [],
|
||||
tickets: [],
|
||||
reports: [],
|
||||
sessions: new Map(),
|
||||
idempotency: new Map(),
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
export const db: MockState = initState()
|
||||
db.audits = buildAudits(db.admins, db.apps)
|
||||
db.reports = buildSeedReports()
|
||||
|
||||
// 应用维度统计(首页/应用列表用)
|
||||
export function refreshAppStats(): void {
|
||||
const today = now().slice(0, 10)
|
||||
db.apps.forEach(app => {
|
||||
app.accountCount = db.accounts.filter(item => item.appCode === app.appCode).length
|
||||
app.todayAmountCent = db.cashFlows
|
||||
.filter(item => item.appCode === app.appCode && item.direction === 'IN' && item.receivedAt.slice(0, 10) === today)
|
||||
.reduce((sum, item) => sum + item.amountCent, 0)
|
||||
})
|
||||
db.plans.forEach(plan => {
|
||||
plan.holderCount = db.vips.filter(
|
||||
item => item.appCode === plan.appCode && item.vipPlanCode === plan.planCode && item.vipUntil > now(),
|
||||
).length
|
||||
})
|
||||
}
|
||||
|
||||
refreshAppStats()
|
||||
@@ -0,0 +1,2 @@
|
||||
export { mockAdapter } from './router'
|
||||
export { db } from './db'
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,181 @@
|
||||
import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { APP_TITLE } from '@/constants'
|
||||
import { HOME_BY_ROLE } from './menu'
|
||||
|
||||
declare module 'vue-router' {
|
||||
interface RouteMeta {
|
||||
title?: string
|
||||
perm?: string
|
||||
public?: boolean
|
||||
layout?: 'blank'
|
||||
}
|
||||
}
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/login',
|
||||
name: 'login',
|
||||
component: () => import('@/views/login/LoginView.vue'),
|
||||
meta: { title: '管理员登录', public: true, layout: 'blank' },
|
||||
},
|
||||
{
|
||||
path: '/password',
|
||||
name: 'password',
|
||||
component: () => import('@/views/password/ChangePasswordView.vue'),
|
||||
meta: { title: '修改密码', layout: 'blank' },
|
||||
},
|
||||
{
|
||||
path: '/pay',
|
||||
name: 'pay',
|
||||
component: () => import('@/views/pay/PayView.vue'),
|
||||
meta: { title: '收银台', public: true, layout: 'blank' },
|
||||
},
|
||||
{
|
||||
path: '/403',
|
||||
name: 'forbidden',
|
||||
component: () => import('@/views/error/ForbiddenView.vue'),
|
||||
meta: { title: '无访问权限', public: true, layout: 'blank' },
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
component: () => import('@/layouts/AppLayout.vue'),
|
||||
redirect: '/dashboard',
|
||||
children: [
|
||||
{
|
||||
path: 'dashboard',
|
||||
name: 'dashboard',
|
||||
component: () => import('@/views/dashboard/DashboardView.vue'),
|
||||
meta: { title: '资金看板', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'apps',
|
||||
name: 'apps',
|
||||
component: () => import('@/views/apps/AppListView.vue'),
|
||||
meta: { title: '接入应用', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'accounts',
|
||||
name: 'accounts',
|
||||
component: () => import('@/views/accounts/AccountListView.vue'),
|
||||
meta: { title: '钱包账户', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'orders',
|
||||
name: 'orders',
|
||||
component: () => import('@/views/orders/OrderListView.vue'),
|
||||
meta: { title: '充值订单', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'refunds',
|
||||
name: 'refunds',
|
||||
component: () => import('@/views/refunds/RefundListView.vue'),
|
||||
meta: { title: '退款单', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'transactions',
|
||||
name: 'transactions',
|
||||
component: () => import('@/views/transactions/TransactionListView.vue'),
|
||||
meta: { title: '点数流水', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'vip-plans',
|
||||
name: 'vip-plans',
|
||||
component: () => import('@/views/vip/VipPlanView.vue'),
|
||||
meta: { title: 'VIP 档位', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'vips',
|
||||
name: 'vips',
|
||||
component: () => import('@/views/vip/VipHolderView.vue'),
|
||||
meta: { title: 'VIP 持有', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'pricing',
|
||||
name: 'pricing',
|
||||
component: () => import('@/views/pricing/PricingView.vue'),
|
||||
meta: { title: '兑率与策略', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'reconcile',
|
||||
name: 'reconcile',
|
||||
component: () => import('@/views/reconcile/ReconcileView.vue'),
|
||||
meta: { title: '对账中心', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'webhooks',
|
||||
name: 'webhooks',
|
||||
component: () => import('@/views/system/WebhookView.vue'),
|
||||
meta: { title: 'Webhook 投递', perm: 'fin:view' },
|
||||
},
|
||||
{
|
||||
path: 'admins',
|
||||
name: 'admins',
|
||||
component: () => import('@/views/system/AdminListView.vue'),
|
||||
meta: { title: '管理员', perm: 'fin:admin:manage' },
|
||||
},
|
||||
{
|
||||
path: 'audit',
|
||||
name: 'audit',
|
||||
component: () => import('@/views/system/AuditLogView.vue'),
|
||||
meta: { title: '审计日志', perm: 'fin:audit:view' },
|
||||
},
|
||||
{
|
||||
path: 'config',
|
||||
name: 'config',
|
||||
component: () => import('@/views/system/ConfigView.vue'),
|
||||
meta: { title: '全局参数', perm: 'fin:config:edit' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
name: 'not-found',
|
||||
component: () => import('@/views/error/NotFoundView.vue'),
|
||||
meta: { title: '页面不存在', public: true, layout: 'blank' },
|
||||
},
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(),
|
||||
routes,
|
||||
scrollBehavior: () => ({ top: 0 }),
|
||||
})
|
||||
|
||||
router.beforeEach(async to => {
|
||||
document.title = to.meta.title ? `${to.meta.title} · ${APP_TITLE}` : APP_TITLE
|
||||
|
||||
if (to.meta.public) return true
|
||||
|
||||
const store = useUserStore()
|
||||
if (!store.isLoggedIn) {
|
||||
return { path: '/login', query: { redirect: to.fullPath } }
|
||||
}
|
||||
|
||||
if (!store.admin) {
|
||||
try {
|
||||
await store.loadProfile()
|
||||
} catch {
|
||||
store.logout()
|
||||
return { path: '/login', query: { redirect: to.fullPath } }
|
||||
}
|
||||
}
|
||||
|
||||
// 首次登录强制改密:除改密页外一律拦截
|
||||
if (store.mustChangePassword && to.path !== '/password') {
|
||||
return { path: '/password' }
|
||||
}
|
||||
|
||||
if (to.meta.perm && !store.hasPerm(to.meta.perm)) {
|
||||
return { path: '/403', query: { from: to.fullPath } }
|
||||
}
|
||||
|
||||
if (to.path === '/' || to.path === '/dashboard') {
|
||||
const home = HOME_BY_ROLE[store.admin!.role]
|
||||
if (home !== '/dashboard' && to.path === '/') return { path: home }
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Role } from '@/types'
|
||||
|
||||
export interface MenuItem {
|
||||
path: string
|
||||
title: string
|
||||
icon: string
|
||||
perm?: string | string[]
|
||||
}
|
||||
|
||||
export interface MenuGroup {
|
||||
title: string
|
||||
items: MenuItem[]
|
||||
}
|
||||
|
||||
/** 菜单结构:页面级权限仅做体验层隐藏,服务端必须二次校验 */
|
||||
export const MENU_GROUPS: MenuGroup[] = [
|
||||
{
|
||||
title: '资金运营',
|
||||
items: [
|
||||
{ path: '/dashboard', title: '资金看板', icon: 'DataLine' },
|
||||
{ path: '/orders', title: '充值订单', icon: 'Tickets' },
|
||||
{ path: '/refunds', title: '退款单', icon: 'RefreshLeft' },
|
||||
{ path: '/accounts', title: '钱包账户', icon: 'Wallet' },
|
||||
{ path: '/transactions', title: '点数流水', icon: 'Coin' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: '应用与计费',
|
||||
items: [
|
||||
{ path: '/apps', title: '接入应用', icon: 'Connection' },
|
||||
{ path: '/vip-plans', title: 'VIP 档位', icon: 'Medal' },
|
||||
{ path: '/vips', title: 'VIP 持有', icon: 'Star' },
|
||||
{ path: '/pricing', title: '兑率与策略', icon: 'SetUp' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: '对账与审计',
|
||||
items: [
|
||||
{ path: '/reconcile', title: '对账中心', icon: 'DocumentChecked' },
|
||||
{ path: '/audit', title: '审计日志', icon: 'Lock', perm: 'fin:audit:view' },
|
||||
{ path: '/webhooks', title: 'Webhook 投递', icon: 'Promotion' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: '系统管理',
|
||||
items: [
|
||||
{ path: '/admins', title: '管理员', icon: 'User', perm: 'fin:admin:manage' },
|
||||
{ path: '/config', title: '全局参数', icon: 'Setting', perm: 'fin:config:edit' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export const HOME_BY_ROLE: Record<Role, string> = {
|
||||
SUPER_ADMIN: '/dashboard',
|
||||
FINANCE: '/orders',
|
||||
AUDITOR: '/dashboard',
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref } from 'vue'
|
||||
import type { AdminInfo, LoginResult } from '@/types'
|
||||
import type { LoginPayload } from '@/api/auth'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { clearSession, getToken, setToken } from '@/utils/session'
|
||||
|
||||
export const useUserStore = defineStore('user', () => {
|
||||
const token = ref(getToken())
|
||||
const admin = ref<AdminInfo | null>(null)
|
||||
const permissions = ref<string[]>([])
|
||||
|
||||
const isLoggedIn = computed(() => Boolean(token.value))
|
||||
const role = computed(() => admin.value?.role || null)
|
||||
const mustChangePassword = computed(() => admin.value?.mustChangePassword === 1)
|
||||
const displayName = computed(() => admin.value?.username || '')
|
||||
|
||||
function hasPerm(code: string | string[]): boolean {
|
||||
if (!admin.value) return false
|
||||
const codes = Array.isArray(code) ? code : [code]
|
||||
return codes.some(item => permissions.value.includes(item))
|
||||
}
|
||||
|
||||
async function login(payload: LoginPayload): Promise<LoginResult> {
|
||||
const result = await authApi.login(payload)
|
||||
token.value = result.token
|
||||
setToken(result.token)
|
||||
admin.value = result.admin
|
||||
permissions.value = result.permissions
|
||||
return result
|
||||
}
|
||||
|
||||
async function loadProfile(): Promise<void> {
|
||||
const result = await authApi.profile()
|
||||
admin.value = result.admin
|
||||
permissions.value = result.permissions
|
||||
}
|
||||
|
||||
function logout(): void {
|
||||
token.value = ''
|
||||
admin.value = null
|
||||
permissions.value = []
|
||||
clearSession()
|
||||
}
|
||||
|
||||
async function changePassword(oldPassword: string, newPassword: string): Promise<void> {
|
||||
await authApi.changePassword({ oldPassword, newPassword })
|
||||
if (admin.value) admin.value.mustChangePassword = 0
|
||||
}
|
||||
|
||||
return {
|
||||
token,
|
||||
admin,
|
||||
permissions,
|
||||
isLoggedIn,
|
||||
role,
|
||||
mustChangePassword,
|
||||
displayName,
|
||||
hasPerm,
|
||||
login,
|
||||
loadProfile,
|
||||
logout,
|
||||
changePassword,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,295 @@
|
||||
:root {
|
||||
/* 品牌色(同时覆盖 Element Plus 主色) */
|
||||
--el-color-primary: #1d5bdb;
|
||||
--el-color-primary-light-3: #5b87e5;
|
||||
--el-color-primary-light-5: #8fb0ee;
|
||||
--el-color-primary-light-7: #c3d5f7;
|
||||
--el-color-primary-light-8: #dbe6fb;
|
||||
--el-color-primary-light-9: #eef3fe;
|
||||
--el-color-primary-dark-2: #1749af;
|
||||
--el-color-success: #0f9d70;
|
||||
--el-color-warning: #c47d0a;
|
||||
--el-color-danger: #c0392b;
|
||||
--el-color-info: #64748b;
|
||||
|
||||
--fin-bg: #f4f6fb;
|
||||
--fin-card: #ffffff;
|
||||
--fin-border: #e5eaf2;
|
||||
--fin-border-strong: #d3dbe8;
|
||||
--fin-text: #17202f;
|
||||
--fin-text-2: #5b6a80;
|
||||
--fin-text-3: #8a97a8;
|
||||
--fin-sidebar: #0d1728;
|
||||
--fin-sidebar-2: #14213a;
|
||||
--fin-sidebar-text: #9fb0c9;
|
||||
--fin-sidebar-active: #ffffff;
|
||||
--fin-gold: #c8a45c;
|
||||
--fin-radius: 10px;
|
||||
--fin-shadow: 0 1px 2px rgba(16, 24, 40, 0.04), 0 8px 24px rgba(16, 24, 40, 0.06);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--fin-bg);
|
||||
color: var(--fin-text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB',
|
||||
'Microsoft YaHei', 'Helvetica Neue', Arial, sans-serif;
|
||||
font-size: 14px;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
/* 通用版式 */
|
||||
.page {
|
||||
padding: 20px 24px 32px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.page-header h2 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.page-header .desc {
|
||||
margin: 0;
|
||||
color: var(--fin-text-2);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.page-header .actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--fin-card);
|
||||
border: 1px solid var(--fin-border);
|
||||
border-radius: var(--fin-radius);
|
||||
box-shadow: var(--fin-shadow);
|
||||
padding: 18px 20px;
|
||||
}
|
||||
|
||||
.card + .card {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin: 0 0 14px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.filter-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.filter-bar .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.table-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
/* 数字排版 */
|
||||
.num {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-feature-settings: 'tnum';
|
||||
}
|
||||
|
||||
.money {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 600;
|
||||
color: var(--fin-text);
|
||||
}
|
||||
|
||||
.money-in {
|
||||
color: var(--fin-success);
|
||||
}
|
||||
|
||||
.money-out {
|
||||
color: var(--fin-danger);
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--fin-text-3);
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 提示条 */
|
||||
.notice {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: flex-start;
|
||||
padding: 10px 14px;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.notice.info {
|
||||
background: #f0f5ff;
|
||||
border-color: #d6e4ff;
|
||||
color: #1f4fa8;
|
||||
}
|
||||
|
||||
.notice.warn {
|
||||
background: #fff8e6;
|
||||
border-color: #ffe7b0;
|
||||
color: #8a5a00;
|
||||
}
|
||||
|
||||
.notice.danger {
|
||||
background: #fdf1f0;
|
||||
border-color: #f6d4d0;
|
||||
color: #a33125;
|
||||
}
|
||||
|
||||
/* 统计卡片 */
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
|
||||
gap: 14px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* Element Plus 微调 */
|
||||
.el-table {
|
||||
--el-table-header-bg-color: #f8fafc;
|
||||
--el-table-border-color: var(--fin-border);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.el-table th.el-table__cell {
|
||||
font-weight: 600;
|
||||
color: var(--fin-text-2);
|
||||
}
|
||||
|
||||
.el-descriptions__label {
|
||||
color: var(--fin-text-2) !important;
|
||||
width: 132px;
|
||||
}
|
||||
|
||||
.el-dialog__body {
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.code-block {
|
||||
background: #0f172a;
|
||||
color: #d7e3f4;
|
||||
border-radius: 8px;
|
||||
padding: 12px 14px;
|
||||
font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
max-height: 380px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.hash {
|
||||
font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
|
||||
font-size: 11px;
|
||||
color: var(--fin-text-2);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* 侧边栏 */
|
||||
.side-menu.el-menu {
|
||||
border-right: none;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.side-menu .el-menu-item,
|
||||
.side-menu .el-sub-menu__title {
|
||||
height: 42px;
|
||||
line-height: 42px;
|
||||
color: var(--fin-sidebar-text);
|
||||
border-radius: 8px;
|
||||
margin: 2px 10px;
|
||||
padding-left: 14px !important;
|
||||
}
|
||||
|
||||
.side-menu .el-menu-item:hover,
|
||||
.side-menu .el-sub-menu__title:hover {
|
||||
background: var(--fin-sidebar-2);
|
||||
color: #e6edf9;
|
||||
}
|
||||
|
||||
.side-menu .el-menu-item.is-active {
|
||||
background: linear-gradient(90deg, rgba(29, 91, 219, 0.95), rgba(29, 91, 219, 0.65));
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.side-menu .el-sub-menu.is-active > .el-sub-menu__title {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.side-menu .el-menu {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.side-menu .el-sub-menu .el-menu-item {
|
||||
padding-left: 38px !important;
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #c8d2e0;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
/** 后台角色:三角色职责分离(D5) */
|
||||
export type Role = 'SUPER_ADMIN' | 'FINANCE' | 'AUDITOR'
|
||||
|
||||
export type OrderStatus = 'PENDING' | 'PAID' | 'CANCELLED' | 'REFUNDED'
|
||||
export type OrderType = 'recharge' | 'vip'
|
||||
export type PayMethod = 'offline' | 'wechat' | 'alipay'
|
||||
export type TxType = 'RECHARGE' | 'CONSUME' | 'CONSUME_FREE' | 'REFUND_IN' | 'REFUND_OUT' | 'ADJUST'
|
||||
export type RefundStatus = 'PENDING' | 'COMPLETED' | 'REJECTED'
|
||||
export type WebhookStatus = 'PENDING' | 'SENT' | 'FAILED' | 'DEAD'
|
||||
|
||||
export interface PageResult<T> {
|
||||
records: T[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
export interface AdminInfo {
|
||||
id: number
|
||||
username: string
|
||||
role: Role
|
||||
isActive: number
|
||||
mustChangePassword: number
|
||||
totpBound: boolean
|
||||
failedAttempts: number
|
||||
lockedUntil: string | null
|
||||
lastLoginAt: string | null
|
||||
lastLoginIp: string | null
|
||||
createTime: string
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
token: string
|
||||
admin: AdminInfo
|
||||
permissions: string[]
|
||||
}
|
||||
|
||||
export interface AppInfo {
|
||||
appCode: string
|
||||
appName: string
|
||||
allowedRedirectHosts: string
|
||||
webhookUrl: string
|
||||
tokenTtlSeconds: number
|
||||
enabled: number
|
||||
secretExpiresAt: string | null
|
||||
hasPrevSecret: boolean
|
||||
createTime: string
|
||||
accountCount: number
|
||||
todayAmountCent: number
|
||||
}
|
||||
|
||||
export interface AppTokenInfo {
|
||||
id: number
|
||||
appCode: string
|
||||
tokenPrefix: string
|
||||
expiresAt: string
|
||||
revokedAt: string | null
|
||||
issuedIp: string
|
||||
createTime: string
|
||||
}
|
||||
|
||||
export interface AccountInfo {
|
||||
id: number
|
||||
appCode: string
|
||||
appName: string
|
||||
businessUserId: string
|
||||
usernameSnapshot: string
|
||||
phoneMasked: string
|
||||
balance: number
|
||||
totalSpent: number
|
||||
versionNo: number
|
||||
vipPlanCode: string | null
|
||||
vipUntil: string | null
|
||||
createTime: string
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
export interface OrderInfo {
|
||||
id: number
|
||||
outTradeNo: string
|
||||
appCode: string
|
||||
appName: string
|
||||
businessUserId: string
|
||||
usernameSnapshot: string
|
||||
orderType: OrderType
|
||||
payMethod: PayMethod
|
||||
amountCent: number
|
||||
pointsGained: number
|
||||
vipPlanCode: string | null
|
||||
status: OrderStatus
|
||||
expiresAt: string
|
||||
paidAt: string | null
|
||||
confirmedByAdminId: number | null
|
||||
confirmedByAdminName: string | null
|
||||
secondApproverId: number | null
|
||||
secondApproverName: string | null
|
||||
remark: string
|
||||
createTime: string
|
||||
refundedAmountCent: number
|
||||
cashInCent: number
|
||||
cashOutCent: number
|
||||
needDualControl: boolean
|
||||
}
|
||||
|
||||
export interface TransactionInfo {
|
||||
id: number
|
||||
appCode: string
|
||||
appName: string
|
||||
businessUserId: string
|
||||
usernameSnapshot: string
|
||||
type: TxType
|
||||
amount: number
|
||||
balanceBefore: number
|
||||
balanceAfter: number
|
||||
businessRefId: string | null
|
||||
idempotencyKey: string
|
||||
orderId: number | null
|
||||
outTradeNo: string | null
|
||||
refundOfId: number | null
|
||||
refundedPoints: number
|
||||
operatorAdminName: string | null
|
||||
remark: string
|
||||
createTime: string
|
||||
}
|
||||
|
||||
export interface RefundInfo {
|
||||
id: number
|
||||
appCode: string
|
||||
appName: string
|
||||
businessUserId: string
|
||||
usernameSnapshot: string
|
||||
orderId: number
|
||||
outTradeNo: string
|
||||
amountCent: number
|
||||
pointsDeducted: number
|
||||
status: RefundStatus
|
||||
operatorAdminId: number
|
||||
operatorAdminName: string
|
||||
reviewerAdminId: number | null
|
||||
reviewerAdminName: string | null
|
||||
voucherNo: string
|
||||
remark: string
|
||||
createTime: string
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
export interface VipPlan {
|
||||
id: number
|
||||
appCode: string
|
||||
appName: string
|
||||
planCode: string
|
||||
planName: string
|
||||
durationDays: number
|
||||
priceCent: number
|
||||
freeDeduction: number
|
||||
enabled: number
|
||||
holderCount: number
|
||||
createTime: string
|
||||
}
|
||||
|
||||
export interface VipHolder {
|
||||
id: number
|
||||
appCode: string
|
||||
appName: string
|
||||
businessUserId: string
|
||||
usernameSnapshot: string
|
||||
vipPlanCode: string
|
||||
vipUntil: string
|
||||
effective: boolean
|
||||
}
|
||||
|
||||
export interface PricingItem {
|
||||
appCode: string
|
||||
appName: string
|
||||
pointsPerYuan: number
|
||||
enabled: number
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
export interface AppPolicy {
|
||||
appCode: string
|
||||
appName: string
|
||||
minCost: number
|
||||
maxPointsPerCharge: number
|
||||
vipExempt: number
|
||||
failedStrategy: 'none' | 'actual'
|
||||
dualControlThresholdCent: number
|
||||
enabled: number
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
export interface ConfigItem {
|
||||
configKey: string
|
||||
configValue: string
|
||||
description: string
|
||||
risk: 'HIGH' | 'NORMAL'
|
||||
updateBy: string
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
export interface AuditLog {
|
||||
id: number
|
||||
actorType: 'ADMIN' | 'SYSTEM' | 'BIZ'
|
||||
actorId: number | null
|
||||
actorName: string
|
||||
action: string
|
||||
actionLabel: string
|
||||
targetType: string
|
||||
targetId: number | null
|
||||
beforeJson: string | null
|
||||
afterJson: string | null
|
||||
ip: string
|
||||
ua: string
|
||||
result: 'SUCCESS' | 'FAILED'
|
||||
prevHash: string
|
||||
curHash: string
|
||||
createTime: string
|
||||
}
|
||||
|
||||
export interface ChainVerifyResult {
|
||||
valid: boolean
|
||||
checked: number
|
||||
brokenAtId: number | null
|
||||
checkedAt: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface WebhookDelivery {
|
||||
id: number
|
||||
appCode: string
|
||||
appName: string
|
||||
eventId: string
|
||||
eventType: string
|
||||
status: WebhookStatus
|
||||
attempts: number
|
||||
nextRetryAt: string | null
|
||||
lastError: string
|
||||
payload: string
|
||||
createTime: string
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
export interface ReconcileDiff {
|
||||
level: 'ORDER' | 'SUBJECT' | 'APP'
|
||||
target: string
|
||||
expected: number
|
||||
actual: number
|
||||
diff: number
|
||||
reason: string
|
||||
}
|
||||
|
||||
export interface ReconcileReport {
|
||||
id: string
|
||||
appCode: string
|
||||
appName: string
|
||||
windowStart: string
|
||||
windowEnd: string
|
||||
snapshotAt: string
|
||||
cashInCent: number
|
||||
cashPaidOrderCent: number
|
||||
cashOutCent: number
|
||||
cashRefundedCent: number
|
||||
cashDiffCent: number
|
||||
walletSum: number
|
||||
computedSum: number
|
||||
pointsDiff: number
|
||||
brokenChains: number
|
||||
diffCount: number
|
||||
status: 'BALANCED' | 'DIFF'
|
||||
createdBy: string
|
||||
createTime: string
|
||||
details: ReconcileDiff[]
|
||||
}
|
||||
|
||||
export interface DashboardSummary {
|
||||
todayAmountCent: number
|
||||
todayOrderCount: number
|
||||
pendingOrderCount: number
|
||||
pendingAmountCent: number
|
||||
todayConsumedPoints: number
|
||||
pendingRefundCount: number
|
||||
totalBalancePoints: number
|
||||
deadWebhookCount: number
|
||||
diffReportCount: number
|
||||
dualControlThresholdCent: number
|
||||
}
|
||||
|
||||
export interface TrendPoint {
|
||||
date: string
|
||||
amountCent: number
|
||||
points: number
|
||||
orderCount: number
|
||||
}
|
||||
|
||||
export interface AppDistribution {
|
||||
appCode: string
|
||||
appName: string
|
||||
amountCent: number
|
||||
orderCount: number
|
||||
}
|
||||
|
||||
export interface AppTokenIssue {
|
||||
clientSecret: string
|
||||
expiresAt: string
|
||||
}
|
||||
|
||||
export interface PayPreview {
|
||||
appCode: string
|
||||
appName: string
|
||||
businessUserId: string
|
||||
usernameSnapshot: string
|
||||
balance: number
|
||||
pointsPerYuan: number
|
||||
minAmountCent: number
|
||||
vip: {
|
||||
planCode: string
|
||||
planName: string
|
||||
vipUntil: string
|
||||
freeDeduction: number
|
||||
} | null
|
||||
plans: Array<{
|
||||
planCode: string
|
||||
planName: string
|
||||
durationDays: number
|
||||
priceCent: number
|
||||
freeDeduction: number
|
||||
}>
|
||||
ticketExpiresAt: string
|
||||
}
|
||||
|
||||
export interface PayOrder {
|
||||
outTradeNo: string
|
||||
amountCent: number
|
||||
pointsGained: number
|
||||
orderType: OrderType
|
||||
vipPlanCode: string | null
|
||||
status: OrderStatus
|
||||
expiresAt: string
|
||||
payee: {
|
||||
accountName: string
|
||||
bankName: string
|
||||
accountNo: string
|
||||
}
|
||||
redirectUri: string | null
|
||||
createTime: string
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
|
||||
export interface ConfirmOptions {
|
||||
title?: string
|
||||
message: string
|
||||
confirmText?: string
|
||||
type?: 'warning' | 'info' | 'error' | 'success'
|
||||
/** 需要手动输入的确认文本(资金类高危操作强制使用) */
|
||||
requireType?: string
|
||||
/** 输入框提示 */
|
||||
inputHint?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 高危操作二次确认:
|
||||
* - 默认弹窗确认
|
||||
* - requireType 场景要求人工输入指定文本,防止误点
|
||||
*/
|
||||
export async function confirmAction(options: ConfirmOptions): Promise<boolean> {
|
||||
const title = options.title || '操作确认'
|
||||
const confirmButtonText = options.confirmText || '确定'
|
||||
|
||||
try {
|
||||
if (options.requireType) {
|
||||
await ElMessageBox.prompt(options.message, title, {
|
||||
confirmButtonText,
|
||||
cancelButtonText: '取消',
|
||||
type: options.type || 'warning',
|
||||
inputPlaceholder: options.inputHint || `请输入「${options.requireType}」`,
|
||||
inputValidator: (value: string) => (value === options.requireType ? true : `输入不一致,请重新输入「${options.requireType}」`),
|
||||
closeOnClickModal: false,
|
||||
distinguishCancelAndClose: true,
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
await ElMessageBox.confirm(options.message, title, {
|
||||
confirmButtonText,
|
||||
cancelButtonText: '取消',
|
||||
type: options.type || 'warning',
|
||||
closeOnClickModal: false,
|
||||
distinguishCancelAndClose: true,
|
||||
})
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** TOTP 输入弹窗:返回 6 位验证码,取消返回 null */
|
||||
export async function askTotp(actionName: string): Promise<string | null> {
|
||||
try {
|
||||
const result = await ElMessageBox.prompt(
|
||||
`执行「${actionName}」需要二次身份验证,请输入身份验证器中的 6 位动态码。`,
|
||||
'动态口令(TOTP)',
|
||||
{
|
||||
confirmButtonText: '验证并继续',
|
||||
cancelButtonText: '取消',
|
||||
inputPlaceholder: '6 位数字动态码',
|
||||
inputPattern: /^\d{6}$/,
|
||||
inputErrorMessage: '动态码必须为 6 位数字',
|
||||
closeOnClickModal: false,
|
||||
distinguishCancelAndClose: true,
|
||||
},
|
||||
)
|
||||
return result.value
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 输入备注/原因(必填) */
|
||||
export async function askReason(title: string, message: string): Promise<string | null> {
|
||||
try {
|
||||
const result = await ElMessageBox.prompt(message, title, {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
inputPlaceholder: '请填写原因(不少于 5 个字)',
|
||||
inputValidator: (value: string) => ((value || '').trim().length >= 5 ? true : '原因不少于 5 个字'),
|
||||
closeOnClickModal: false,
|
||||
distinguishCancelAndClose: true,
|
||||
})
|
||||
return result.value.trim()
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
export interface CsvColumn<T> {
|
||||
label: string
|
||||
value: (row: T) => string | number | null | undefined
|
||||
}
|
||||
|
||||
/** 防 CSV 注入:以 = + - @ 或制表符开头的单元格强制转义 */
|
||||
function safeCell(value: unknown): string {
|
||||
const text = value === null || value === undefined ? '' : String(value)
|
||||
const protectedText = /^[=+\-@\t]/.test(text) ? `'${text}` : text
|
||||
return `"${protectedText.replace(/"/g, '""')}"`
|
||||
}
|
||||
|
||||
export function buildCsv<T>(columns: CsvColumn<T>[], rows: T[]): string {
|
||||
const head = columns.map(col => safeCell(col.label)).join(',')
|
||||
const body = rows.map(row => columns.map(col => safeCell(col.value(row))).join(','))
|
||||
return [head, ...body].join('\r\n')
|
||||
}
|
||||
|
||||
export function downloadCsv(filename: string, csv: string): void {
|
||||
// BOM 保证 Excel 正确识别 UTF-8 中文
|
||||
const blob = new Blob([`\uFEFF${csv}`], { type: 'text/csv;charset=utf-8' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = filename
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
export function exportFilename(prefix: string): string {
|
||||
const now = new Date()
|
||||
const stamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(
|
||||
now.getDate(),
|
||||
).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`
|
||||
return `${prefix}-${stamp}.csv`
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
const pad = (n: number): string => String(n).padStart(2, '0')
|
||||
|
||||
export function formatDateTime(value?: string | null): string {
|
||||
if (!value) return '—'
|
||||
return String(value).slice(0, 19).replace('T', ' ')
|
||||
}
|
||||
|
||||
export function formatDate(value?: string | null): string {
|
||||
if (!value) return '—'
|
||||
return String(value).slice(0, 10)
|
||||
}
|
||||
|
||||
export function toLocalString(date: Date): string {
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
|
||||
date.getHours(),
|
||||
)}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
|
||||
export function todayString(): string {
|
||||
const now = new Date()
|
||||
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
|
||||
}
|
||||
|
||||
export function dateOffset(days: number): string {
|
||||
const date = new Date()
|
||||
date.setDate(date.getDate() + days)
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
|
||||
}
|
||||
|
||||
export function defaultRange(days = 7): [string, string] {
|
||||
return [dateOffset(-(days - 1)), todayString()]
|
||||
}
|
||||
|
||||
/** 剩余时间文案(订单过期、ticket 过期) */
|
||||
export function remainText(expireAt?: string | null): string {
|
||||
if (!expireAt) return '—'
|
||||
const diff = new Date(expireAt.replace(' ', 'T')).getTime() - Date.now()
|
||||
if (Number.isNaN(diff)) return '—'
|
||||
if (diff <= 0) return '已过期'
|
||||
const minutes = Math.floor(diff / 60000)
|
||||
if (minutes < 60) return `${minutes} 分钟`
|
||||
const hours = Math.floor(minutes / 60)
|
||||
if (hours < 24) return `${hours} 小时 ${minutes % 60} 分`
|
||||
return `${Math.floor(hours / 24)} 天 ${hours % 24} 小时`
|
||||
}
|
||||
|
||||
export function secondsText(ms: number): string {
|
||||
const total = Math.max(0, Math.ceil(ms / 1000))
|
||||
const m = Math.floor(total / 60)
|
||||
const s = total % 60
|
||||
return `${pad(m)}:${pad(s)}`
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import axios, { type AxiosRequestConfig } from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { mockAdapter } from '@/mock'
|
||||
import { clearSession, getToken } from '@/utils/session'
|
||||
|
||||
export interface ApiResult<T = unknown> {
|
||||
code: number
|
||||
message: string
|
||||
data: T
|
||||
traceId?: string
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
code: number
|
||||
traceId?: string
|
||||
|
||||
constructor(code: number, message: string, traceId?: string) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.code = code
|
||||
this.traceId = traceId
|
||||
}
|
||||
}
|
||||
|
||||
declare module 'axios' {
|
||||
export interface AxiosRequestConfig {
|
||||
/** 静默模式:不在页面弹提示,由调用方自行处理 */
|
||||
silent?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
const KNOWN_MESSAGES: Record<number, string> = {
|
||||
401: '登录状态已失效,请重新登录',
|
||||
4010: '登录状态已失效,请重新登录',
|
||||
403: '当前账号无权执行该操作',
|
||||
4091: '重复提交已被拦截,已返回首次结果',
|
||||
4092: '并发操作冲突,请稍后重试',
|
||||
4093: '单据状态已变更,请刷新后重试',
|
||||
422: '提交内容不符合规范,请检查后重试',
|
||||
429: '操作过于频繁,请稍后再试',
|
||||
6001: '账户余额不足,无法完成扣费',
|
||||
6002: '超出单次扣费上限,已被拒绝',
|
||||
6003: '点数必须为正整数',
|
||||
6004: '退款金额超出可退上限',
|
||||
7001: '凭证无效、已过期或已被使用',
|
||||
}
|
||||
|
||||
/** 错误文案统一出口:不向用户回显堆栈、SQL、内部主机名 */
|
||||
export function userMessage(error: ApiError): string {
|
||||
if (KNOWN_MESSAGES[error.code]) return KNOWN_MESSAGES[error.code]
|
||||
const message = (error.message || '').trim()
|
||||
if (!message) return '操作失败,请稍后重试'
|
||||
if (/(sql|jdbc|mysql|exception|stack|nullpointer|select\s|insert\s|update\s)/i.test(message)) {
|
||||
return '操作失败,请稍后重试'
|
||||
}
|
||||
return message.length > 120 ? '操作失败,请稍后重试' : message
|
||||
}
|
||||
|
||||
let unauthorizedHandler: (() => void) | null = null
|
||||
|
||||
export function setUnauthorizedHandler(handler: () => void): void {
|
||||
unauthorizedHandler = handler
|
||||
}
|
||||
|
||||
const instance = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE || '/api',
|
||||
timeout: 20000,
|
||||
withCredentials: false,
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
})
|
||||
|
||||
// 本地演示:内置 Mock adapter(生产构建必须 VITE_USE_MOCK=0)
|
||||
if (import.meta.env.VITE_USE_MOCK === '1') {
|
||||
instance.defaults.adapter = mockAdapter
|
||||
}
|
||||
|
||||
instance.interceptors.request.use(config => {
|
||||
const token = getToken()
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
async function request<T>(config: AxiosRequestConfig): Promise<T> {
|
||||
let response
|
||||
try {
|
||||
response = await instance.request<ApiResult<T>>(config)
|
||||
} catch (error) {
|
||||
const message = axios.isAxiosError(error) && error.code === 'ECONNABORTED' ? '请求超时,请稍后重试' : '网络异常,请稍后重试'
|
||||
if (!config.silent) ElMessage.error(message)
|
||||
throw new ApiError(-1, message)
|
||||
}
|
||||
|
||||
const body = response.data
|
||||
if (!body || typeof body.code !== 'number') {
|
||||
if (!config.silent) ElMessage.error('服务响应异常,请稍后重试')
|
||||
throw new ApiError(-2, '服务响应异常')
|
||||
}
|
||||
|
||||
if (body.code !== 0) {
|
||||
const error = new ApiError(body.code, body.message || '操作失败', body.traceId)
|
||||
if (body.code === 401 || body.code === 4010) {
|
||||
clearSession()
|
||||
unauthorizedHandler?.()
|
||||
}
|
||||
if (!config.silent) ElMessage.error(userMessage(error))
|
||||
throw error
|
||||
}
|
||||
|
||||
return body.data
|
||||
}
|
||||
|
||||
export const http = {
|
||||
get<T>(url: string, params?: object, config: AxiosRequestConfig = {}): Promise<T> {
|
||||
return request<T>({ ...config, url, method: 'get', params })
|
||||
},
|
||||
post<T>(url: string, data?: unknown, config: AxiosRequestConfig = {}): Promise<T> {
|
||||
return request<T>({ ...config, url, method: 'post', data })
|
||||
},
|
||||
put<T>(url: string, data?: unknown, config: AxiosRequestConfig = {}): Promise<T> {
|
||||
return request<T>({ ...config, url, method: 'put', data })
|
||||
},
|
||||
delete<T>(url: string, config: AxiosRequestConfig = {}): Promise<T> {
|
||||
return request<T>({ ...config, url, method: 'delete' })
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/** PII 脱敏工具:前端展示层兜底,服务端必须已完成掩码存储 */
|
||||
|
||||
export function maskPhone(phone: string | null | undefined): string {
|
||||
if (!phone) return '—'
|
||||
const text = String(phone)
|
||||
if (text.length < 7) return '***'
|
||||
return `${text.slice(0, 3)}****${text.slice(-4)}`
|
||||
}
|
||||
|
||||
export function maskEmail(email: string | null | undefined): string {
|
||||
if (!email) return '—'
|
||||
const [name, domain] = String(email).split('@')
|
||||
if (!domain) return '***'
|
||||
const head = name.slice(0, 2)
|
||||
return `${head}***@${domain}`
|
||||
}
|
||||
|
||||
export function maskUserId(id: string): string {
|
||||
if (!id) return '—'
|
||||
if (id.length <= 7) return id
|
||||
return `${id.slice(0, 4)}***${id.slice(-3)}`
|
||||
}
|
||||
|
||||
/** 密钥只展示前缀,禁止完整回显(页面一次性展示场景除外) */
|
||||
export function maskSecret(secret: string): string {
|
||||
if (!secret) return '<REDACTED>'
|
||||
return `${secret.slice(0, 6)}••••••••${secret.slice(-4)}`
|
||||
}
|
||||
|
||||
/** 凭证号等准敏感标识:保留首尾便于人工核对 */
|
||||
export function maskVoucher(no: string | null | undefined): string {
|
||||
if (!no) return '—'
|
||||
const text = String(no)
|
||||
if (text.length <= 6) return text
|
||||
return `${text.slice(0, 3)}****${text.slice(-3)}`
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
const yuanFmt = new Intl.NumberFormat('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})
|
||||
const intFmt = new Intl.NumberFormat('zh-CN')
|
||||
|
||||
/** 分 → ¥ 展示(金额一律以分存储,前端只做展示转换) */
|
||||
export function formatCent(cent: number | null | undefined, withSymbol = true): string {
|
||||
if (cent === null || cent === undefined || !Number.isFinite(cent)) return '—'
|
||||
return `${withSymbol ? '¥ ' : ''}${yuanFmt.format(cent / 100)}`
|
||||
}
|
||||
|
||||
export function formatPoints(points: number | null | undefined): string {
|
||||
if (points === null || points === undefined || !Number.isFinite(points)) return '—'
|
||||
return intFmt.format(points)
|
||||
}
|
||||
|
||||
export function formatSignedPoints(points: number, sign: number): string {
|
||||
if (sign === 0) return '0'
|
||||
return `${sign > 0 ? '+' : '-'}${intFmt.format(Math.abs(points))}`
|
||||
}
|
||||
|
||||
export function formatPercent(value: number): string {
|
||||
return `${(value * 100).toFixed(2)}%`
|
||||
}
|
||||
|
||||
/** 严格解析「元」输入为分:仅允许最多两位小数、必须大于 0 */
|
||||
export function yuanInputToCent(input: string): number | null {
|
||||
const text = String(input ?? '').trim()
|
||||
if (!/^\d{1,9}(\.\d{1,2})?$/.test(text)) return null
|
||||
const cent = Math.round(Number(text) * 100)
|
||||
if (!Number.isInteger(cent) || cent <= 0) return null
|
||||
return cent
|
||||
}
|
||||
|
||||
export function centToYuanInput(cent: number | null | undefined): string {
|
||||
if (cent === null || cent === undefined || !Number.isFinite(cent)) return ''
|
||||
return (cent / 100).toFixed(2)
|
||||
}
|
||||
|
||||
/** 点数必须为正整数(设计文档 §5:拒绝小数/字符串/NaN) */
|
||||
export function parsePositiveInt(input: unknown): number | null {
|
||||
if (typeof input === 'number') {
|
||||
return Number.isInteger(input) && input > 0 ? input : null
|
||||
}
|
||||
if (typeof input === 'string' && /^\d{1,9}$/.test(input)) {
|
||||
const value = Number(input)
|
||||
return Number.isInteger(value) && value > 0 ? value : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 会话存储:token 仅放 sessionStorage(关闭标签页即失效),不落 localStorage。
|
||||
* 生产环境后端可改为 httpOnly + SameSite=Strict Cookie,前端不接触 token。
|
||||
*/
|
||||
const TOKEN_KEY = 'fin.admin.token'
|
||||
const LOGIN_AT_KEY = 'fin.admin.loginAt'
|
||||
|
||||
/** 空闲 30 分钟自动登出(等保二级:会话超时) */
|
||||
export const SESSION_IDLE_MS = 30 * 60 * 1000
|
||||
/** 到期前 5 分钟提醒 */
|
||||
export const SESSION_WARN_MS = 5 * 60 * 1000
|
||||
|
||||
export function getToken(): string {
|
||||
try {
|
||||
return sessionStorage.getItem(TOKEN_KEY) || ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function setToken(token: string): void {
|
||||
try {
|
||||
sessionStorage.setItem(TOKEN_KEY, token)
|
||||
sessionStorage.setItem(LOGIN_AT_KEY, String(Date.now()))
|
||||
} catch {
|
||||
/* 存储不可用时降级为内存态,由调用方保证 */
|
||||
}
|
||||
}
|
||||
|
||||
export function getLoginAt(): number {
|
||||
try {
|
||||
return Number(sessionStorage.getItem(LOGIN_AT_KEY) || 0)
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSession(): void {
|
||||
try {
|
||||
sessionStorage.removeItem(TOKEN_KEY)
|
||||
sessionStorage.removeItem(LOGIN_AT_KEY)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/** 前端校验:仅体验层,服务端必须使用同一套规则重新校验(设计文档 §5) */
|
||||
|
||||
export interface PasswordRule {
|
||||
key: string
|
||||
label: string
|
||||
ok: boolean
|
||||
}
|
||||
|
||||
export interface PasswordCheck {
|
||||
valid: boolean
|
||||
score: number
|
||||
levelText: string
|
||||
rules: PasswordRule[]
|
||||
}
|
||||
|
||||
const SPECIAL = /[^A-Za-z0-9]/
|
||||
|
||||
export function checkPassword(password: string): PasswordCheck {
|
||||
const pwd = password || ''
|
||||
const rules: PasswordRule[] = [
|
||||
{ key: 'length', label: '长度不少于 12 位', ok: pwd.length >= 12 },
|
||||
{ key: 'upper', label: '包含大写字母', ok: /[A-Z]/.test(pwd) },
|
||||
{ key: 'lower', label: '包含小写字母', ok: /[a-z]/.test(pwd) },
|
||||
{ key: 'digit', label: '包含数字', ok: /\d/.test(pwd) },
|
||||
{ key: 'special', label: '包含特殊符号', ok: SPECIAL.test(pwd) },
|
||||
{ key: 'space', label: '不含空格与中文', ok: pwd.length > 0 && /^[\x21-\x7e]+$/.test(pwd) },
|
||||
]
|
||||
const passed = rules.filter(item => item.ok).length
|
||||
const score = Math.round((passed / rules.length) * 100)
|
||||
const levelText = score >= 100 ? '很强' : score >= 83 ? '强' : score >= 66 ? '中' : '弱'
|
||||
return { valid: passed === rules.length, score, levelText, rules }
|
||||
}
|
||||
|
||||
export function isBusinessUserId(value: string): boolean {
|
||||
return /^[A-Za-z0-9_-]{1,64}$/.test(value || '')
|
||||
}
|
||||
|
||||
export function isIdempotencyKey(value: string): boolean {
|
||||
return /^[A-Za-z0-9:_-]{8,64}$/.test(value || '')
|
||||
}
|
||||
|
||||
export function newIdempotencyKey(prefix: string): string {
|
||||
const random =
|
||||
typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
||||
? crypto.randomUUID().replace(/-/g, '')
|
||||
: `${Date.now()}${Math.random().toString(16).slice(2)}`
|
||||
return `${prefix}:${random}`.slice(0, 64)
|
||||
}
|
||||
|
||||
export function isPositiveInt(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value > 0
|
||||
}
|
||||
|
||||
/** 跳转白名单展示用校验:必须是 https 或内网 http 的精确主机名,禁止 IP 直连与通配符 */
|
||||
export function isSafeRedirectHost(host: string): boolean {
|
||||
const text = (host || '').trim()
|
||||
if (!text) return false
|
||||
if (text.includes('*')) return false
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(text)) return false
|
||||
if (text.includes('/') || text.includes(':')) return false
|
||||
return /^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(text)
|
||||
}
|
||||
|
||||
/** 高危操作二次确认文本 */
|
||||
export function confirmTextOf(action: string): string {
|
||||
return `确认${action}`
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { FormInstance, FormRules } from 'element-plus'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import {
|
||||
accountApi,
|
||||
appApi,
|
||||
orderApi,
|
||||
type AccountDetail,
|
||||
type AccountQuery,
|
||||
type AdjustPayload,
|
||||
type Approver,
|
||||
} from '@/api/core'
|
||||
import type { AccountInfo, AppInfo, TxType } from '@/types'
|
||||
import { PERM, TX_TYPE } from '@/constants'
|
||||
import { formatPoints, formatSignedPoints, parsePositiveInt } from '@/utils/money'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { confirmAction } from '@/utils/confirm'
|
||||
import { userMessage, type ApiError } from '@/utils/http'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
const router = useRouter()
|
||||
const store = useUserStore()
|
||||
|
||||
/* ------------------------------ 列表与筛选 ------------------------------ */
|
||||
|
||||
const apps = ref<AppInfo[]>([])
|
||||
const filter = reactive({
|
||||
appCode: '',
|
||||
keyword: '',
|
||||
minBalance: undefined as number | undefined,
|
||||
})
|
||||
|
||||
const rows = ref<AccountInfo[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const loading = ref(false)
|
||||
const listError = ref('')
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
try {
|
||||
apps.value = await appApi.list()
|
||||
} catch {
|
||||
// 非 silent 接口已由 http 层提示,筛选下拉降级为空
|
||||
apps.value = []
|
||||
}
|
||||
}
|
||||
|
||||
function buildQuery(): AccountQuery {
|
||||
const query: AccountQuery = { page: page.value, pageSize: pageSize.value }
|
||||
if (filter.appCode) query.appCode = filter.appCode
|
||||
const keyword = filter.keyword.trim()
|
||||
if (keyword) query.keyword = keyword
|
||||
if (filter.minBalance !== undefined && filter.minBalance !== null) query.minBalance = filter.minBalance
|
||||
return query
|
||||
}
|
||||
|
||||
async function loadAccounts(): Promise<void> {
|
||||
loading.value = true
|
||||
listError.value = ''
|
||||
try {
|
||||
const result = await accountApi.list(buildQuery())
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch (error) {
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
listError.value = userMessage(error as ApiError)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSearch(): void {
|
||||
page.value = 1
|
||||
void loadAccounts()
|
||||
}
|
||||
|
||||
function handleReset(): void {
|
||||
filter.appCode = ''
|
||||
filter.keyword = ''
|
||||
filter.minBalance = undefined
|
||||
page.value = 1
|
||||
void loadAccounts()
|
||||
}
|
||||
|
||||
function handlePageChange(value: number): void {
|
||||
page.value = value
|
||||
void loadAccounts()
|
||||
}
|
||||
|
||||
function handleSizeChange(value: number): void {
|
||||
pageSize.value = value
|
||||
page.value = 1
|
||||
void loadAccounts()
|
||||
}
|
||||
|
||||
function vipActive(row: AccountInfo): boolean {
|
||||
if (!row.vipUntil) return false
|
||||
return new Date(row.vipUntil.replace(' ', 'T')).getTime() > Date.now()
|
||||
}
|
||||
|
||||
/* ------------------------------ 账户详情 ------------------------------ */
|
||||
|
||||
const detail = reactive({
|
||||
visible: false,
|
||||
loading: false,
|
||||
error: '',
|
||||
data: null as AccountDetail | null,
|
||||
})
|
||||
|
||||
async function openDetail(row: AccountInfo): Promise<void> {
|
||||
detail.visible = true
|
||||
detail.loading = true
|
||||
detail.error = ''
|
||||
detail.data = null
|
||||
try {
|
||||
detail.data = await accountApi.detail(row.id)
|
||||
} catch (error) {
|
||||
detail.error = userMessage(error as ApiError)
|
||||
} finally {
|
||||
detail.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
function goAllTransactions(): void {
|
||||
const account = detail.data?.account
|
||||
if (!account) return
|
||||
void router.push({ path: '/transactions', query: { keyword: account.businessUserId } })
|
||||
}
|
||||
|
||||
function txTag(type: TxType): 'success' | 'danger' | 'info' | 'warning' {
|
||||
return TX_TYPE[type].tag
|
||||
}
|
||||
|
||||
function txLabel(type: TxType): string {
|
||||
return TX_TYPE[type].label
|
||||
}
|
||||
|
||||
function txSign(type: TxType): number {
|
||||
return TX_TYPE[type].sign
|
||||
}
|
||||
|
||||
/* ------------------------------ 人工调账 ------------------------------ */
|
||||
|
||||
const adjustFormRef = ref<FormInstance>()
|
||||
const approvers = ref<Approver[]>([])
|
||||
const approversLoading = ref(false)
|
||||
|
||||
const adjust = reactive({
|
||||
visible: false,
|
||||
submitting: false,
|
||||
account: null as AccountInfo | null,
|
||||
direction: 'IN' as 'IN' | 'OUT',
|
||||
amount: '',
|
||||
reason: '',
|
||||
approverId: undefined as number | undefined,
|
||||
totp: '',
|
||||
})
|
||||
|
||||
const adjustRules: FormRules = {
|
||||
amount: [
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
if (parsePositiveInt(value) === null) return callback(new Error('点数必须为正整数(1~999999999)'))
|
||||
callback()
|
||||
},
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
reason: [
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
if (String(value || '').trim().length < 5) return callback(new Error('调账原因不少于 5 个字'))
|
||||
callback()
|
||||
},
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
approverId: [
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
if (!value) return callback(new Error('必须选择第二复核人'))
|
||||
if (value === store.admin?.id) return callback(new Error('复核人不得为当前登录人'))
|
||||
callback()
|
||||
},
|
||||
trigger: 'change',
|
||||
},
|
||||
],
|
||||
totp: [
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
if (!/^\d{6}$/.test(String(value || '').trim())) return callback(new Error('动态码必须为 6 位数字'))
|
||||
callback()
|
||||
},
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const outInsufficient = computed(() => {
|
||||
if (adjust.direction !== 'OUT' || !adjust.account) return false
|
||||
const amount = parsePositiveInt(adjust.amount)
|
||||
return amount !== null && amount > adjust.account.balance
|
||||
})
|
||||
|
||||
async function loadApprovers(): Promise<void> {
|
||||
approversLoading.value = true
|
||||
try {
|
||||
const list = await orderApi.approvers()
|
||||
approvers.value = list.filter(item => item.id !== store.admin?.id)
|
||||
} catch {
|
||||
approvers.value = []
|
||||
} finally {
|
||||
approversLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleDirectionChange(value: string | number | boolean): void {
|
||||
adjust.direction = value === 'OUT' ? 'OUT' : 'IN'
|
||||
}
|
||||
|
||||
function openAdjust(row: AccountInfo): void {
|
||||
adjust.account = row
|
||||
adjust.direction = 'IN'
|
||||
adjust.amount = ''
|
||||
adjust.reason = ''
|
||||
adjust.approverId = undefined
|
||||
adjust.totp = ''
|
||||
adjust.visible = true
|
||||
void nextTick(() => adjustFormRef.value?.clearValidate())
|
||||
void loadApprovers()
|
||||
}
|
||||
|
||||
async function submitAdjust(): Promise<void> {
|
||||
const instance = adjustFormRef.value
|
||||
const account = adjust.account
|
||||
if (!instance || !account) return
|
||||
|
||||
const valid = await instance.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
const amount = parsePositiveInt(adjust.amount)
|
||||
if (amount === null) {
|
||||
ElMessage.error('点数必须为正整数')
|
||||
return
|
||||
}
|
||||
if (adjust.direction === 'OUT' && amount > account.balance) {
|
||||
ElMessage.warning(`调减后余额不能为负,当前余额 ${formatPoints(account.balance)} 点`)
|
||||
return
|
||||
}
|
||||
if (!adjust.approverId) {
|
||||
ElMessage.error('必须选择第二复核人')
|
||||
return
|
||||
}
|
||||
const approverId = adjust.approverId
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '人工调账',
|
||||
message: `确认为「${account.appName}」用户 ${account.businessUserId} ${
|
||||
adjust.direction === 'IN' ? '调增' : '调减'
|
||||
} ${formatPoints(amount)} 点?该操作需第二人复核并写入全量审计日志。`,
|
||||
confirmText: '确认调账',
|
||||
type: 'warning',
|
||||
requireType: '确认调账',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const payload: AdjustPayload = {
|
||||
appCode: account.appCode,
|
||||
businessUserId: account.businessUserId,
|
||||
amount,
|
||||
direction: adjust.direction,
|
||||
reason: adjust.reason.trim(),
|
||||
secondApproverId: approverId,
|
||||
totp: adjust.totp.trim(),
|
||||
}
|
||||
|
||||
adjust.submitting = true
|
||||
try {
|
||||
await accountApi.adjust(payload)
|
||||
ElMessage.success('调账成功,账户余额已更新')
|
||||
adjust.visible = false
|
||||
await loadAccounts()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
adjust.submitting = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void Promise.all([loadApps(), loadAccounts()])
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="钱包账户" desc="业务用户钱包余额、累计消耗与人工调账">
|
||||
<el-button :loading="loading" @click="loadAccounts">
|
||||
<el-icon style="margin-right: 4px"><Refresh /></el-icon>刷新
|
||||
</el-button>
|
||||
</PageHeader>
|
||||
|
||||
<div class="notice warn" style="margin-bottom: 16px">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<div>人工调账必须双人复核(发起人 ≠ 复核人),需 TOTP 动态码,调账全量写入审计日志且不可删除。</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<el-select v-model="filter.appCode" placeholder="全部应用" clearable style="width: 220px">
|
||||
<el-option
|
||||
v-for="app in apps"
|
||||
:key="app.appCode"
|
||||
:label="`${app.appName}(${app.appCode})`"
|
||||
:value="app.appCode"
|
||||
/>
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="filter.keyword"
|
||||
placeholder="业务用户ID / 用户名 / 手机号"
|
||||
clearable
|
||||
style="width: 240px"
|
||||
@keyup.enter="handleSearch"
|
||||
/>
|
||||
<el-input-number
|
||||
v-model="filter.minBalance"
|
||||
:min="0"
|
||||
:step="100"
|
||||
controls-position="right"
|
||||
placeholder="最低余额点数"
|
||||
style="width: 180px"
|
||||
/>
|
||||
<el-button type="primary" @click="handleSearch">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
</div>
|
||||
|
||||
<div v-if="listError" class="notice danger" style="margin-bottom: 14px">{{ listError }}</div>
|
||||
|
||||
<el-table v-loading="loading" :data="rows" row-key="id" stripe>
|
||||
<el-table-column label="应用" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.appName }}</div>
|
||||
<div class="small muted mono">{{ row.appCode }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="businessUserId"
|
||||
label="业务用户ID"
|
||||
min-width="170"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span class="mono" :title="row.businessUserId">{{ row.businessUserId }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="usernameSnapshot" label="用户名" min-width="120" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.usernameSnapshot || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="手机(脱敏)" width="140">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.phoneMasked || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="余额点数" width="120" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="money">{{ formatPoints(row.balance) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="累计消耗点数" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num muted">{{ formatPoints(row.totalSpent) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="VIP" min-width="170">
|
||||
<template #default="{ row }">
|
||||
<template v-if="row.vipPlanCode">
|
||||
<el-tag :type="vipActive(row) ? 'success' : 'info'" size="small" effect="light">
|
||||
{{ row.vipPlanCode }} · {{ vipActive(row) ? '生效中' : '已过期' }}
|
||||
</el-tag>
|
||||
<div class="small muted">至 {{ formatDateTime(row.vipUntil) }}</div>
|
||||
</template>
|
||||
<span v-else class="muted">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="versionNo" label="versionNo" width="100" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ row.versionNo }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="更新时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.updateTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="140" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="openDetail(row)">详情</el-button>
|
||||
<el-button v-perm="PERM.accountAdjust" link type="warning" @click="openAdjust(row)">调账</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<el-empty description="暂无符合条件的钱包账户" :image-size="90" />
|
||||
</template>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
:total="total"
|
||||
:current-page="page"
|
||||
:page-size="pageSize"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
@current-change="handlePageChange"
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 详情抽屉 -->
|
||||
<el-drawer v-model="detail.visible" size="760px" :with-header="true">
|
||||
<template #header>
|
||||
<div>
|
||||
<div style="font-size: 16px; font-weight: 600">钱包账户详情</div>
|
||||
<div class="small muted">余额变动以点数流水为准,最近展示 10 条</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-loading="detail.loading">
|
||||
<div v-if="detail.error" class="notice danger" style="margin-bottom: 14px">{{ detail.error }}</div>
|
||||
|
||||
<template v-if="detail.data">
|
||||
<el-descriptions :column="2" border size="small">
|
||||
<el-descriptions-item label="所属应用">
|
||||
{{ detail.data.account.appName }}
|
||||
<span class="mono muted">({{ detail.data.account.appCode }})</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="业务用户ID">
|
||||
<span class="mono">{{ detail.data.account.businessUserId }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="用户名">{{ detail.data.account.usernameSnapshot || '—' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="手机号">
|
||||
<span class="mono">{{ detail.data.account.phoneMasked || '—' }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="当前余额">
|
||||
<span class="money">{{ formatPoints(detail.data.account.balance) }} 点</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="累计消耗">
|
||||
<span class="num">{{ formatPoints(detail.data.account.totalSpent) }} 点</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="VIP 状态">
|
||||
<template v-if="detail.data.vip">
|
||||
<el-tag :type="detail.data.vip.effective ? 'success' : 'info'" size="small" effect="light">
|
||||
{{ detail.data.vip.planName }} · {{ detail.data.vip.effective ? '生效中' : '已过期' }}
|
||||
</el-tag>
|
||||
<span class="small muted" style="margin-left: 6px">
|
||||
至 {{ formatDateTime(detail.data.vip.vipUntil) }},免扣 {{ formatPoints(detail.data.vip.freeDeduction) }} 次
|
||||
</span>
|
||||
</template>
|
||||
<span v-else class="muted">非 VIP</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="versionNo">
|
||||
<span class="num">{{ detail.data.account.versionNo }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="创建时间">{{ formatDateTime(detail.data.account.createTime) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="更新时间">{{ formatDateTime(detail.data.account.updateTime) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div class="card-title" style="margin-top: 18px">最近流水</div>
|
||||
<el-table :data="detail.data.transactions" size="small" stripe>
|
||||
<el-table-column label="类型" width="140">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="txTag(row.type)" size="small" effect="light">{{ txLabel(row.type) }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="点数变动" width="110" align="right">
|
||||
<template #default="{ row }">
|
||||
<span :class="txSign(row.type) > 0 ? 'money money-in' : txSign(row.type) < 0 ? 'money money-out' : 'money'">
|
||||
{{ formatSignedPoints(row.amount, txSign(row.type)) }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="变动后余额" width="120" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ formatPoints(row.balanceAfter) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="备注" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.remark || '—' }}</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<el-empty description="暂无流水记录" :image-size="70" />
|
||||
</template>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-button link type="primary" @click="goAllTransactions">查看全部流水</el-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-empty
|
||||
v-else-if="!detail.loading && !detail.error"
|
||||
description="暂无账户详情"
|
||||
:image-size="90"
|
||||
/>
|
||||
</div>
|
||||
</el-drawer>
|
||||
|
||||
<!-- 调账对话框 -->
|
||||
<el-dialog
|
||||
v-model="adjust.visible"
|
||||
title="人工调账"
|
||||
width="580px"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<div v-if="adjust.account" class="notice warn" style="margin-bottom: 14px">
|
||||
当前账户:{{ adjust.account.appName }} · <span class="mono">{{ adjust.account.businessUserId }}</span>
|
||||
,可用余额 <strong>{{ formatPoints(adjust.account.balance) }}</strong> 点。
|
||||
调账必须由另一名管理员复核,且复核人不得为本人。
|
||||
</div>
|
||||
|
||||
<el-form ref="adjustFormRef" :model="adjust" :rules="adjustRules" label-width="96px">
|
||||
<el-form-item label="调账方向" prop="direction">
|
||||
<el-radio-group :model-value="adjust.direction" @change="handleDirectionChange">
|
||||
<el-radio-button value="IN">调增(IN)</el-radio-button>
|
||||
<el-radio-button value="OUT">调减(OUT)</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="点数" prop="amount">
|
||||
<el-input v-model="adjust.amount" maxlength="9" placeholder="正整数,例如 100" />
|
||||
<div v-if="outInsufficient" class="small money-out">
|
||||
调减点数超过当前余额 {{ formatPoints(adjust.account?.balance) }} 点,提交将被服务端拒绝。
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="调账原因" prop="reason">
|
||||
<el-input
|
||||
v-model="adjust.reason"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
maxlength="200"
|
||||
show-word-limit
|
||||
placeholder="不少于 5 个字,将写入审计日志"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="复核人" prop="approverId">
|
||||
<el-select
|
||||
v-model="adjust.approverId"
|
||||
:loading="approversLoading"
|
||||
placeholder="请选择第二复核人"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option
|
||||
v-for="approver in approvers"
|
||||
:key="approver.id"
|
||||
:label="`${approver.username} · ${approver.role}`"
|
||||
:value="approver.id"
|
||||
/>
|
||||
</el-select>
|
||||
<div class="small muted">仅展示非当前登录人的启用管理员</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="动态口令" prop="totp">
|
||||
<el-input v-model="adjust.totp" maxlength="6" placeholder="6 位数字动态码" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<template #footer>
|
||||
<el-button @click="adjust.visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="adjust.submitting" @click="submitAdjust">提交调账</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.el-input-number .el-input__inner) {
|
||||
text-align: left;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,771 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { FormInstance, FormRules } from 'element-plus'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { appApi, type AppPayload } from '@/api/core'
|
||||
import type { AppInfo, AppTokenInfo } from '@/types'
|
||||
import { PERM } from '@/constants'
|
||||
import { formatCent } from '@/utils/money'
|
||||
import { formatDateTime, remainText } from '@/utils/format'
|
||||
import { askTotp, confirmAction } from '@/utils/confirm'
|
||||
import { isSafeRedirectHost } from '@/utils/validate'
|
||||
import { userMessage, type ApiError } from '@/utils/http'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
const store = useUserStore()
|
||||
const canManage = computed(() => store.hasPerm(PERM.appManage))
|
||||
|
||||
/* ------------------------------ 应用列表 ------------------------------ */
|
||||
|
||||
const apps = ref<AppInfo[]>([])
|
||||
const loading = ref(false)
|
||||
const listError = ref('')
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
loading.value = true
|
||||
listError.value = ''
|
||||
try {
|
||||
apps.value = await appApi.list()
|
||||
} catch (error) {
|
||||
apps.value = []
|
||||
listError.value = userMessage(error as ApiError)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function hostList(value: string): string[] {
|
||||
return String(value || '')
|
||||
.split(',')
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
/* ------------------------------ 新建 / 编辑 ------------------------------ */
|
||||
|
||||
interface AppFormState {
|
||||
appCode: string
|
||||
appName: string
|
||||
allowedRedirectHosts: string
|
||||
webhookUrl: string
|
||||
tokenTtlSeconds: number
|
||||
}
|
||||
|
||||
const formRef = ref<FormInstance>()
|
||||
const formVisible = ref(false)
|
||||
const submitting = ref(false)
|
||||
const editTarget = ref<AppInfo | null>(null)
|
||||
const isEdit = computed(() => Boolean(editTarget.value))
|
||||
|
||||
const form = reactive<AppFormState>({
|
||||
appCode: '',
|
||||
appName: '',
|
||||
allowedRedirectHosts: '',
|
||||
webhookUrl: '',
|
||||
tokenTtlSeconds: 900,
|
||||
})
|
||||
|
||||
const rules: FormRules = {
|
||||
appCode: [
|
||||
{ required: true, message: '请输入 app_code', trigger: 'blur' },
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
if (isEdit.value) return callback()
|
||||
if (!/^[a-z][a-z0-9-]{2,31}$/.test(String(value || '').trim())) {
|
||||
return callback(new Error('app_code 需为 3~32 位小写字母、数字或短横线,且以小写字母开头'))
|
||||
}
|
||||
callback()
|
||||
},
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
appName: [
|
||||
{ required: true, message: '请输入应用名称', trigger: 'blur' },
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
if (String(value || '').trim().length < 2) return callback(new Error('应用名称至少 2 个字'))
|
||||
callback()
|
||||
},
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
allowedRedirectHosts: [
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
const hosts = hostList(String(value || ''))
|
||||
if (!hosts.length) return callback(new Error('必须配置跳转域名白名单'))
|
||||
const invalid = hosts.filter(host => !isSafeRedirectHost(host))
|
||||
if (invalid.length) {
|
||||
return callback(new Error(`不合法域名:${invalid.join('、')}(禁止通配符与 IP 直连)`))
|
||||
}
|
||||
callback()
|
||||
},
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
webhookUrl: [
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
const url = String(value || '').trim()
|
||||
if (!url) return callback()
|
||||
if (!/^https:\/\//.test(url)) return callback(new Error('webhook 地址必须使用 HTTPS'))
|
||||
callback()
|
||||
},
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
tokenTtlSeconds: [
|
||||
{
|
||||
validator: (_rule, value, callback) => {
|
||||
const ttl = Number(value)
|
||||
if (!Number.isInteger(ttl) || ttl < 60 || ttl > 86400) {
|
||||
return callback(new Error('token 有效期需在 60~86400 秒之间'))
|
||||
}
|
||||
callback()
|
||||
},
|
||||
trigger: 'change',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
function resetForm(): void {
|
||||
form.appCode = ''
|
||||
form.appName = ''
|
||||
form.allowedRedirectHosts = ''
|
||||
form.webhookUrl = ''
|
||||
form.tokenTtlSeconds = 900
|
||||
editTarget.value = null
|
||||
void nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function openCreate(): void {
|
||||
resetForm()
|
||||
formVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(row: AppInfo): void {
|
||||
resetForm()
|
||||
editTarget.value = row
|
||||
form.appCode = row.appCode
|
||||
form.appName = row.appName
|
||||
form.allowedRedirectHosts = row.allowedRedirectHosts
|
||||
form.webhookUrl = row.webhookUrl
|
||||
form.tokenTtlSeconds = row.tokenTtlSeconds
|
||||
formVisible.value = true
|
||||
}
|
||||
|
||||
async function submitForm(): Promise<void> {
|
||||
const instance = formRef.value
|
||||
if (!instance) return
|
||||
const valid = await instance.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
const payload: AppPayload = {
|
||||
appName: form.appName.trim(),
|
||||
allowedRedirectHosts: hostList(form.allowedRedirectHosts).join(','),
|
||||
webhookUrl: form.webhookUrl.trim(),
|
||||
tokenTtlSeconds: form.tokenTtlSeconds,
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
const target = editTarget.value
|
||||
if (target) {
|
||||
try {
|
||||
await appApi.update(target.appCode, payload)
|
||||
ElMessage.success('应用配置已更新')
|
||||
formVisible.value = false
|
||||
await loadApps()
|
||||
} catch {
|
||||
// 非 silent 接口已由 http 层提示错误,保持对话框不关闭便于修正
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
payload.appCode = form.appCode.trim()
|
||||
try {
|
||||
const result = await appApi.create(payload)
|
||||
formVisible.value = false
|
||||
await loadApps()
|
||||
openSecretDialog('应用创建成功', result.clientSecret, '')
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 一次性密钥 ------------------------------ */
|
||||
|
||||
const secretDialog = reactive({
|
||||
visible: false,
|
||||
title: '',
|
||||
value: '',
|
||||
expiresAt: '',
|
||||
})
|
||||
const countdown = ref(60)
|
||||
let secretTimer = 0
|
||||
|
||||
function clearSecretTimer(): void {
|
||||
if (secretTimer) {
|
||||
window.clearInterval(secretTimer)
|
||||
secretTimer = 0
|
||||
}
|
||||
}
|
||||
|
||||
function openSecretDialog(title: string, value: string, expiresAt: string): void {
|
||||
clearSecretTimer()
|
||||
secretDialog.title = title
|
||||
secretDialog.value = value
|
||||
secretDialog.expiresAt = expiresAt
|
||||
countdown.value = 60
|
||||
secretDialog.visible = true
|
||||
secretTimer = window.setInterval(() => {
|
||||
countdown.value -= 1
|
||||
if (countdown.value <= 0) closeSecretDialog()
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
function closeSecretDialog(): void {
|
||||
secretDialog.visible = false
|
||||
}
|
||||
|
||||
function onSecretClosed(): void {
|
||||
clearSecretTimer()
|
||||
secretDialog.value = ''
|
||||
secretDialog.expiresAt = ''
|
||||
secretDialog.title = ''
|
||||
countdown.value = 60
|
||||
}
|
||||
|
||||
async function copySecret(): Promise<void> {
|
||||
if (!secretDialog.value) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(secretDialog.value)
|
||||
ElMessage.success('已复制到剪贴板')
|
||||
} catch {
|
||||
ElMessage.warning('浏览器不允许自动复制,请手动选择密钥文本后复制')
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 轮换密钥 ------------------------------ */
|
||||
|
||||
const rotate = reactive({
|
||||
visible: false,
|
||||
row: null as AppInfo | null,
|
||||
graceHours: 24,
|
||||
submitting: false,
|
||||
})
|
||||
|
||||
function openRotate(row: AppInfo): void {
|
||||
rotate.row = row
|
||||
rotate.graceHours = 24
|
||||
rotate.visible = true
|
||||
}
|
||||
|
||||
function handleGraceChange(value: string | number | boolean): void {
|
||||
const hours = Number(value)
|
||||
rotate.graceHours = hours === 0 || hours === 72 ? hours : 24
|
||||
}
|
||||
|
||||
async function submitRotate(): Promise<void> {
|
||||
const row = rotate.row
|
||||
if (!row) return
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '轮换应用密钥',
|
||||
message: `将为「${row.appName}(${row.appCode})」生成新密钥,旧密钥在宽限期 ${
|
||||
rotate.graceHours === 0 ? '(立即失效)' : `${rotate.graceHours} 小时`
|
||||
}内仍可用。是否继续?`,
|
||||
confirmText: '确认轮换',
|
||||
type: 'warning',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('轮换应用密钥')
|
||||
if (!totp) return
|
||||
|
||||
rotate.submitting = true
|
||||
try {
|
||||
const result = await appApi.rotateSecret(row.appCode, rotate.graceHours)
|
||||
rotate.visible = false
|
||||
await loadApps()
|
||||
openSecretDialog('新密钥已生成', result.clientSecret, result.expiresAt)
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
rotate.submitting = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRevokePrev(row: AppInfo): Promise<void> {
|
||||
const confirmed = await confirmAction({
|
||||
title: '回收旧密钥',
|
||||
message: `回收后「${row.appName}」的旧密钥立即失效,仍在宽限期内的旧客户端将无法继续访问。`,
|
||||
confirmText: '确认回收',
|
||||
type: 'warning',
|
||||
requireType: '确认回收',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('回收旧密钥')
|
||||
if (!totp) return
|
||||
|
||||
try {
|
||||
await appApi.revokePrevSecret(row.appCode)
|
||||
ElMessage.success('旧密钥已回收')
|
||||
await loadApps()
|
||||
} catch {
|
||||
// 非 silent 接口已由 http 层提示
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 启用 / 停用 ------------------------------ */
|
||||
|
||||
async function handleToggle(row: AppInfo): Promise<void> {
|
||||
const enable = row.enabled !== 1
|
||||
|
||||
if (enable) {
|
||||
const confirmed = await confirmAction({
|
||||
title: '启用应用',
|
||||
message: `启用后「${row.appName}」可重新申请 client token 并正常计费。`,
|
||||
confirmText: '确认启用',
|
||||
type: 'info',
|
||||
})
|
||||
if (!confirmed) return
|
||||
} else {
|
||||
const confirmed = await confirmAction({
|
||||
title: '停用应用',
|
||||
message: `停用「${row.appName}」会立即熔断该应用全部 client token,所有进行中的接入调用将失败。此操作不可自动恢复,请确认已完成业务切换。`,
|
||||
confirmText: '停用并熔断',
|
||||
type: 'warning',
|
||||
requireType: '确认停用',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('停用应用')
|
||||
if (!totp) return
|
||||
}
|
||||
|
||||
try {
|
||||
await appApi.toggle(row.appCode, enable ? 1 : 0)
|
||||
ElMessage.success(enable ? '应用已启用' : '应用已停用,全部 token 已熔断')
|
||||
await loadApps()
|
||||
} catch {
|
||||
// 非 silent 接口已由 http 层提示
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ Token 抽屉 ------------------------------ */
|
||||
|
||||
const tokenDrawer = reactive({
|
||||
visible: false,
|
||||
row: null as AppInfo | null,
|
||||
loading: false,
|
||||
error: '',
|
||||
list: [] as AppTokenInfo[],
|
||||
})
|
||||
|
||||
async function openTokens(row: AppInfo): Promise<void> {
|
||||
tokenDrawer.row = row
|
||||
tokenDrawer.visible = true
|
||||
tokenDrawer.list = []
|
||||
tokenDrawer.error = ''
|
||||
await loadTokens()
|
||||
}
|
||||
|
||||
async function loadTokens(): Promise<void> {
|
||||
const row = tokenDrawer.row
|
||||
if (!row) return
|
||||
tokenDrawer.loading = true
|
||||
tokenDrawer.error = ''
|
||||
try {
|
||||
tokenDrawer.list = await appApi.listTokens(row.appCode)
|
||||
} catch (error) {
|
||||
tokenDrawer.list = []
|
||||
tokenDrawer.error = userMessage(error as ApiError)
|
||||
} finally {
|
||||
tokenDrawer.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeAllTokens(): Promise<void> {
|
||||
const row = tokenDrawer.row
|
||||
if (!row) return
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '熔断全部 client token',
|
||||
message: `将撤销「${row.appName}」当前全部未撤销 token,所有客户端需重新获取 token。是否继续?`,
|
||||
confirmText: '确认熔断',
|
||||
type: 'warning',
|
||||
requireType: '确认熔断',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('熔断全部 token')
|
||||
if (!totp) return
|
||||
|
||||
try {
|
||||
const result = await appApi.revokeTokens(row.appCode)
|
||||
ElMessage.success(`已熔断 ${result.revoked} 个 token`)
|
||||
await loadTokens()
|
||||
} catch {
|
||||
// 非 silent 接口已由 http 层提示
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeOneToken(token: AppTokenInfo): Promise<void> {
|
||||
const row = tokenDrawer.row
|
||||
if (!row) return
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '撤销 client token',
|
||||
message: `撤销 token「${token.tokenPrefix}」后,持有该 token 的客户端需重新获取凭证。`,
|
||||
confirmText: '确认撤销',
|
||||
type: 'warning',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
try {
|
||||
await appApi.revokeTokens(row.appCode, token.id)
|
||||
ElMessage.success('token 已撤销')
|
||||
await loadTokens()
|
||||
} catch {
|
||||
// 非 silent 接口已由 http 层提示
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadApps()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearSecretTimer()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="接入应用" desc="应用密钥、回调域名白名单与 client token 生命周期管理">
|
||||
<el-button :loading="loading" @click="loadApps">
|
||||
<el-icon style="margin-right: 4px"><Refresh /></el-icon>刷新
|
||||
</el-button>
|
||||
<el-button v-perm="PERM.appManage" type="primary" @click="openCreate">
|
||||
<el-icon style="margin-right: 4px"><Plus /></el-icon>新建应用
|
||||
</el-button>
|
||||
</PageHeader>
|
||||
|
||||
<div class="notice info" style="margin-bottom: 16px">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<div>
|
||||
client_secret 仅以哈希形式存储,明文只在创建/轮换成功时展示一次;client token 默认 15 分钟 TTL;
|
||||
应用一旦停用即熔断全部 token,恢复启用后客户端必须重新申请。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="listError" class="notice danger" style="margin-bottom: 16px">{{ listError }}</div>
|
||||
|
||||
<div class="card">
|
||||
<el-table v-loading="loading" :data="apps" row-key="appCode" stripe>
|
||||
<el-table-column prop="appCode" label="app_code" width="150" fixed>
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.appCode }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="appName" label="应用名称" min-width="130" show-overflow-tooltip />
|
||||
<el-table-column label="回调域名白名单" min-width="220">
|
||||
<template #default="{ row }">
|
||||
<div class="host-tags">
|
||||
<el-tag v-for="host in hostList(row.allowedRedirectHosts)" :key="host" size="small" type="info" effect="plain">
|
||||
{{ host }}
|
||||
</el-tag>
|
||||
<span v-if="!hostList(row.allowedRedirectHosts).length" class="muted">—</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="webhookUrl" min-width="180" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.webhookUrl" class="mono">{{ row.webhookUrl }}</span>
|
||||
<span v-else class="muted">未配置</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="Token TTL" width="120">
|
||||
<template #default="{ row }">
|
||||
<div class="num">{{ row.tokenTtlSeconds }} 秒</div>
|
||||
<div class="small muted">≈ {{ Math.round(row.tokenTtlSeconds / 60) }} 分钟</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.enabled === 1 ? 'success' : 'info'" size="small" effect="light">
|
||||
{{ row.enabled === 1 ? '已启用' : '已停用' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="密钥状态" min-width="180">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-if="row.hasPrevSecret" type="warning" size="small" effect="light">轮换宽限期</el-tag>
|
||||
<el-tag v-else type="success" size="small" effect="plain">当前密钥有效</el-tag>
|
||||
<div v-if="row.hasPrevSecret && row.secretExpiresAt" class="small muted">
|
||||
旧密钥至 {{ formatDateTime(row.secretExpiresAt) }}(剩余 {{ remainText(row.secretExpiresAt) }})
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账户数" width="90" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ row.accountCount }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="今日金额" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="money">{{ formatCent(row.todayAmountCent) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="创建时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="270" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button v-perm="PERM.appManage" link type="primary" @click="openEdit(row)">编辑</el-button>
|
||||
<el-button v-perm="PERM.appManage" link type="primary" @click="openRotate(row)">轮换密钥</el-button>
|
||||
<el-button
|
||||
v-if="row.hasPrevSecret"
|
||||
v-perm="PERM.appManage"
|
||||
link
|
||||
type="warning"
|
||||
@click="handleRevokePrev(row)"
|
||||
>
|
||||
回收旧密钥
|
||||
</el-button>
|
||||
<el-button link type="primary" @click="openTokens(row)">Client Token</el-button>
|
||||
<el-button
|
||||
v-perm="PERM.appManage"
|
||||
link
|
||||
:type="row.enabled === 1 ? 'danger' : 'success'"
|
||||
@click="handleToggle(row)"
|
||||
>
|
||||
{{ row.enabled === 1 ? '停用' : '启用' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<el-empty description="暂无接入应用" :image-size="90" />
|
||||
</template>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<!-- 新建 / 编辑 -->
|
||||
<el-dialog
|
||||
v-model="formVisible"
|
||||
:title="isEdit ? '编辑应用' : '新建应用'"
|
||||
width="620px"
|
||||
:close-on-click-modal="false"
|
||||
@closed="resetForm"
|
||||
>
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
|
||||
<el-form-item label="app_code" prop="appCode">
|
||||
<el-input
|
||||
v-model="form.appCode"
|
||||
:disabled="isEdit"
|
||||
maxlength="32"
|
||||
placeholder="3~32 位小写字母、数字或短横线"
|
||||
/>
|
||||
<div v-if="isEdit" class="small muted">app_code 创建后不可修改</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="应用名称" prop="appName">
|
||||
<el-input v-model="form.appName" maxlength="64" placeholder="用于订单、对账展示" />
|
||||
</el-form-item>
|
||||
<el-form-item label="跳转域名白名单" prop="allowedRedirectHosts">
|
||||
<el-input
|
||||
v-model="form.allowedRedirectHosts"
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
placeholder="多个域名用英文逗号分隔,例如:app.example.com,pay.example.com"
|
||||
/>
|
||||
<div class="small muted">仅允许精确主机名,禁止通配符(*)与 IP 直连</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="webhookUrl" prop="webhookUrl">
|
||||
<el-input v-model="form.webhookUrl" placeholder="可留空;填写时必须为 https:// 地址" />
|
||||
<div class="small muted">用于到账、退款等事件通知,失败会进入重试队列</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="Token 有效期" prop="tokenTtlSeconds">
|
||||
<div style="display: flex; align-items: center; gap: 10px; width: 100%">
|
||||
<el-input-number
|
||||
v-model="form.tokenTtlSeconds"
|
||||
:min="60"
|
||||
:max="86400"
|
||||
:step="60"
|
||||
controls-position="right"
|
||||
style="width: 180px"
|
||||
/>
|
||||
<span class="small muted">秒(≈ {{ Math.round(form.tokenTtlSeconds / 60) }} 分钟,范围 60~86400)</span>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="formVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="submitForm">
|
||||
{{ isEdit ? '保存修改' : '创建并生成密钥' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 轮换密钥 -->
|
||||
<el-dialog v-model="rotate.visible" title="轮换应用密钥" width="560px" :close-on-click-modal="false">
|
||||
<div class="notice warn" style="margin-bottom: 14px">
|
||||
轮换后新密钥立即生效,旧密钥在所选宽限期内仍可使用;宽限期结束请及时回收旧密钥。
|
||||
</div>
|
||||
<el-form label-width="120px">
|
||||
<el-form-item label="旧密钥宽限期">
|
||||
<el-radio-group :model-value="rotate.graceHours" @change="handleGraceChange">
|
||||
<el-radio-button :value="0">立即失效</el-radio-button>
|
||||
<el-radio-button :value="24">24 小时</el-radio-button>
|
||||
<el-radio-button :value="72">72 小时</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="目标应用">
|
||||
<span class="mono">{{ rotate.row?.appCode }}</span>
|
||||
<span class="muted" style="margin-left: 8px">{{ rotate.row?.appName }}</span>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="rotate.visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="rotate.submitting" @click="submitRotate">确认轮换</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 一次性密钥 -->
|
||||
<el-dialog
|
||||
v-model="secretDialog.visible"
|
||||
:title="secretDialog.title"
|
||||
width="640px"
|
||||
:close-on-click-modal="false"
|
||||
@closed="onSecretClosed"
|
||||
>
|
||||
<div class="notice danger" style="margin-bottom: 14px">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<div>关闭后无法再次查看,请立即写入应用密钥管理系统,切勿通过聊天工具明文传递。</div>
|
||||
</div>
|
||||
<div class="secret-box mono">{{ secretDialog.value }}</div>
|
||||
<div class="secret-meta">
|
||||
<span v-if="secretDialog.expiresAt" class="small muted">
|
||||
旧密钥宽限至 {{ formatDateTime(secretDialog.expiresAt) }}(剩余 {{ remainText(secretDialog.expiresAt) }})
|
||||
</span>
|
||||
<span class="small money-out">窗口将在 {{ countdown }} 秒后自动关闭并清空</span>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="copySecret">
|
||||
<el-icon style="margin-right: 4px"><CopyDocument /></el-icon>复制密钥
|
||||
</el-button>
|
||||
<el-button type="primary" @click="closeSecretDialog">我已保存,立即关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- Token 抽屉 -->
|
||||
<el-drawer v-model="tokenDrawer.visible" size="760px" :with-header="true">
|
||||
<template #header>
|
||||
<div>
|
||||
<div style="font-size: 16px; font-weight: 600">client token 列表</div>
|
||||
<div class="small muted">
|
||||
{{ tokenDrawer.row?.appName }} · <span class="mono">{{ tokenDrawer.row?.appCode }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="notice warn" style="margin-bottom: 14px">
|
||||
服务端仅存储 token 哈希,列表只展示前缀。熔断后客户端须重新获取 token,此操作不可撤销。
|
||||
</div>
|
||||
|
||||
<div v-if="tokenDrawer.error" class="notice danger" style="margin-bottom: 14px">
|
||||
{{ tokenDrawer.error }}
|
||||
</div>
|
||||
|
||||
<div class="filter-bar">
|
||||
<el-button :loading="tokenDrawer.loading" size="small" @click="loadTokens">刷新</el-button>
|
||||
<div class="spacer" />
|
||||
<el-button
|
||||
v-perm="PERM.appManage"
|
||||
type="danger"
|
||||
size="small"
|
||||
plain
|
||||
:disabled="!tokenDrawer.list.some(item => !item.revokedAt)"
|
||||
@click="revokeAllTokens"
|
||||
>
|
||||
熔断全部
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<el-table v-loading="tokenDrawer.loading" :data="tokenDrawer.list" size="small" stripe>
|
||||
<el-table-column label="token 前缀" width="150">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.tokenPrefix }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="过期时间" width="190">
|
||||
<template #default="{ row }">
|
||||
<div>{{ formatDateTime(row.expiresAt) }}</div>
|
||||
<div class="small muted">剩余 {{ remainText(row.expiresAt) }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="issuedIp" label="签发 IP" width="130">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.issuedIp || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="签发时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="160">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-if="row.revokedAt" type="info" size="small">已于 {{ formatDateTime(row.revokedAt) }} 撤销</el-tag>
|
||||
<el-tag v-else type="success" size="small" effect="plain">有效</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
v-perm="PERM.appManage"
|
||||
link
|
||||
type="danger"
|
||||
:disabled="Boolean(row.revokedAt)"
|
||||
@click="revokeOneToken(row)"
|
||||
>
|
||||
撤销
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<el-empty description="该应用暂无 client token 记录" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.host-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.secret-box {
|
||||
background: #0f172a;
|
||||
color: #d7e3f4;
|
||||
border-radius: 8px;
|
||||
padding: 14px 16px;
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
word-break: break-all;
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
.secret-meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,440 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import StatCard from '@/components/StatCard.vue'
|
||||
import EChart from '@/components/EChart.vue'
|
||||
import { dashboardApi } from '@/api/system'
|
||||
import type { AppDistribution, DashboardSummary, TrendPoint } from '@/types'
|
||||
import { formatCent, formatPoints } from '@/utils/money'
|
||||
import { userMessage, type ApiError } from '@/utils/http'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const summary = ref<DashboardSummary | null>(null)
|
||||
const summaryLoading = ref(false)
|
||||
const summaryError = ref('')
|
||||
|
||||
const trend = ref<TrendPoint[]>([])
|
||||
const trendLoading = ref(false)
|
||||
const trendError = ref('')
|
||||
const trendDays = ref(7)
|
||||
|
||||
const distribution = ref<AppDistribution[]>([])
|
||||
const distributionLoading = ref(false)
|
||||
const distributionError = ref('')
|
||||
|
||||
const loading = computed(() => summaryLoading.value || trendLoading.value || distributionLoading.value)
|
||||
|
||||
async function loadSummary(): Promise<void> {
|
||||
summaryLoading.value = true
|
||||
summaryError.value = ''
|
||||
try {
|
||||
summary.value = await dashboardApi.summary()
|
||||
} catch (error) {
|
||||
summary.value = null
|
||||
summaryError.value = userMessage(error as ApiError)
|
||||
} finally {
|
||||
summaryLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTrend(): Promise<void> {
|
||||
trendLoading.value = true
|
||||
trendError.value = ''
|
||||
try {
|
||||
trend.value = await dashboardApi.trend()
|
||||
} catch (error) {
|
||||
trend.value = []
|
||||
trendError.value = userMessage(error as ApiError)
|
||||
} finally {
|
||||
trendLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDistribution(): Promise<void> {
|
||||
distributionLoading.value = true
|
||||
distributionError.value = ''
|
||||
try {
|
||||
distribution.value = await dashboardApi.distribution()
|
||||
} catch (error) {
|
||||
distribution.value = []
|
||||
distributionError.value = userMessage(error as ApiError)
|
||||
} finally {
|
||||
distributionLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 三个接口并行,单个失败只影响所属区块 */
|
||||
async function loadAll(): Promise<void> {
|
||||
await Promise.all([loadSummary(), loadTrend(), loadDistribution()])
|
||||
}
|
||||
|
||||
interface StatItem {
|
||||
label: string
|
||||
value: string | number
|
||||
sub?: string
|
||||
tone?: 'default' | 'success' | 'warning' | 'danger' | 'primary'
|
||||
icon?: string
|
||||
}
|
||||
|
||||
const stats = computed<StatItem[]>(() => {
|
||||
const s = summary.value
|
||||
return [
|
||||
{
|
||||
label: '今日到账金额',
|
||||
value: s ? formatCent(s.todayAmountCent) : '—',
|
||||
sub: s ? `已到账 ${s.todayOrderCount} 笔` : undefined,
|
||||
tone: 'success',
|
||||
icon: 'Money',
|
||||
},
|
||||
{
|
||||
label: '今日订单数',
|
||||
value: s ? s.todayOrderCount : '—',
|
||||
sub: '今日确认到账的订单笔数',
|
||||
icon: 'Tickets',
|
||||
},
|
||||
{
|
||||
label: '待确认订单',
|
||||
value: s ? `${s.pendingOrderCount} 笔` : '—',
|
||||
sub: s ? `待确认金额 ${formatCent(s.pendingAmountCent)}` : undefined,
|
||||
tone: s && s.pendingOrderCount > 0 ? 'warning' : 'default',
|
||||
icon: 'Clock',
|
||||
},
|
||||
{
|
||||
label: '待复核退款',
|
||||
value: s ? `${s.pendingRefundCount} 笔` : '—',
|
||||
sub: '需第二人复核后完成退款',
|
||||
tone: s && s.pendingRefundCount > 0 ? 'warning' : 'default',
|
||||
icon: 'RefreshLeft',
|
||||
},
|
||||
{
|
||||
label: '今日消耗点数',
|
||||
value: s ? formatPoints(s.todayConsumedPoints) : '—',
|
||||
sub: '今日扣费流水合计',
|
||||
icon: 'Coin',
|
||||
},
|
||||
{
|
||||
label: '钱包总余额点数',
|
||||
value: s ? formatPoints(s.totalBalancePoints) : '—',
|
||||
sub: '全部应用钱包余额合计',
|
||||
tone: 'primary',
|
||||
icon: 'Wallet',
|
||||
},
|
||||
{
|
||||
label: 'DEAD Webhook',
|
||||
value: s ? s.deadWebhookCount : '—',
|
||||
sub: '投递失败,需人工重放',
|
||||
tone: s && s.deadWebhookCount > 0 ? 'danger' : 'default',
|
||||
icon: 'Promotion',
|
||||
},
|
||||
{
|
||||
label: '对账差异报告',
|
||||
value: s ? s.diffReportCount : '—',
|
||||
sub: '状态为 DIFF 的对账报告',
|
||||
tone: s && s.diffReportCount > 0 ? 'danger' : 'default',
|
||||
icon: 'DocumentChecked',
|
||||
},
|
||||
]
|
||||
})
|
||||
|
||||
interface TodoItem {
|
||||
key: string
|
||||
label: string
|
||||
desc: string
|
||||
count: number
|
||||
path: string
|
||||
tone: 'warning' | 'danger' | 'primary'
|
||||
}
|
||||
|
||||
const todoItems = computed<TodoItem[]>(() => {
|
||||
const s = summary.value
|
||||
return [
|
||||
{
|
||||
key: 'orders',
|
||||
label: '待确认订单',
|
||||
desc: '核对银行回单后确认到账,达到阈值须第二人复核',
|
||||
count: s?.pendingOrderCount ?? 0,
|
||||
path: '/orders?status=PENDING',
|
||||
tone: 'warning',
|
||||
},
|
||||
{
|
||||
key: 'refunds',
|
||||
label: '待复核退款',
|
||||
desc: '退款单已完成发起,等待第二人复核',
|
||||
count: s?.pendingRefundCount ?? 0,
|
||||
path: '/refunds?status=PENDING',
|
||||
tone: 'warning',
|
||||
},
|
||||
{
|
||||
key: 'webhooks',
|
||||
label: '投递失败 Webhook',
|
||||
desc: 'DEAD 状态事件不再自动重试,需人工重放',
|
||||
count: s?.deadWebhookCount ?? 0,
|
||||
path: '/webhooks?status=DEAD',
|
||||
tone: 'danger',
|
||||
},
|
||||
{
|
||||
key: 'reconcile',
|
||||
label: '对账差异',
|
||||
desc: '资金与点数账实不符的报告,需逐条核对',
|
||||
count: s?.diffReportCount ?? 0,
|
||||
path: '/reconcile',
|
||||
tone: 'danger',
|
||||
},
|
||||
]
|
||||
})
|
||||
|
||||
function go(path: string): void {
|
||||
void router.push(path)
|
||||
}
|
||||
|
||||
const trendRows = computed(() => trend.value.slice(-trendDays.value))
|
||||
|
||||
function handleTrendDays(value: string | number | boolean): void {
|
||||
trendDays.value = Number(value) === 14 ? 14 : 7
|
||||
}
|
||||
|
||||
function trendTooltip(params: unknown): string {
|
||||
const list = params as Array<{ axisValue?: string; marker?: string; seriesName?: string; value?: number }>
|
||||
if (!list.length) return ''
|
||||
const head = `<div style="font-weight:600;margin-bottom:4px">${list[0].axisValue ?? ''}</div>`
|
||||
const body = list
|
||||
.map(item => {
|
||||
const value = Number(item.value ?? 0)
|
||||
let text = ''
|
||||
if (item.seriesName === '到账金额(元)') text = formatCent(Math.round(value * 100))
|
||||
else if (item.seriesName === '消耗点数') text = `${formatPoints(value)} 点`
|
||||
else text = `${formatPoints(value)} 笔`
|
||||
return `<div>${item.marker ?? ''}${item.seriesName}:${text}</div>`
|
||||
})
|
||||
.join('')
|
||||
return head + body
|
||||
}
|
||||
|
||||
const trendOption = computed<EChartsOption>(() => {
|
||||
const rows = trendRows.value
|
||||
return {
|
||||
color: ['#1d5bdb', '#0f9d70', '#c47d0a'],
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: trendTooltip },
|
||||
legend: { data: ['到账金额(元)', '消耗点数', '订单数'], top: 0, right: 0, itemWidth: 14, itemHeight: 8 },
|
||||
grid: { left: 56, right: 56, top: 44, bottom: 28 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map(row => row.date.slice(5)),
|
||||
axisTick: { show: false },
|
||||
axisLine: { lineStyle: { color: '#e5eaf2' } },
|
||||
axisLabel: { color: '#5b6a80' },
|
||||
},
|
||||
yAxis: [
|
||||
{
|
||||
type: 'value',
|
||||
name: '元',
|
||||
nameTextStyle: { color: '#8a97a8' },
|
||||
axisLabel: { color: '#5b6a80' },
|
||||
splitLine: { lineStyle: { color: '#eef1f6' } },
|
||||
},
|
||||
{
|
||||
type: 'value',
|
||||
name: '点数/笔',
|
||||
nameTextStyle: { color: '#8a97a8' },
|
||||
axisLabel: { color: '#5b6a80' },
|
||||
splitLine: { show: false },
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{
|
||||
name: '到账金额(元)',
|
||||
type: 'bar',
|
||||
barMaxWidth: 22,
|
||||
yAxisIndex: 0,
|
||||
itemStyle: { borderRadius: [4, 4, 0, 0] },
|
||||
data: rows.map(row => Number((row.amountCent / 100).toFixed(2))),
|
||||
},
|
||||
{
|
||||
name: '消耗点数',
|
||||
type: 'line',
|
||||
smooth: true,
|
||||
symbolSize: 6,
|
||||
yAxisIndex: 1,
|
||||
data: rows.map(row => row.points),
|
||||
},
|
||||
{
|
||||
name: '订单数',
|
||||
type: 'line',
|
||||
smooth: true,
|
||||
symbolSize: 6,
|
||||
yAxisIndex: 1,
|
||||
data: rows.map(row => row.orderCount),
|
||||
},
|
||||
],
|
||||
}
|
||||
})
|
||||
|
||||
function pieTooltip(params: unknown): string {
|
||||
const item = params as { name?: string; value?: number; percent?: number }
|
||||
return `${item.name ?? ''}<br/>金额:${formatCent(Number(item.value ?? 0))}<br/>占比:${item.percent ?? 0}%`
|
||||
}
|
||||
|
||||
const distributionRows = computed(() => distribution.value.filter(item => item.amountCent > 0))
|
||||
|
||||
const distributionOption = computed<EChartsOption>(() => ({
|
||||
color: ['#1d5bdb', '#0f9d70', '#c47d0a', '#7a5af8', '#c0392b', '#64748b', '#c8a45c'],
|
||||
tooltip: { trigger: 'item', formatter: pieTooltip },
|
||||
legend: { bottom: 0, left: 'center', itemWidth: 12, itemHeight: 8, textStyle: { color: '#5b6a80' } },
|
||||
series: [
|
||||
{
|
||||
name: '应用到账金额',
|
||||
type: 'pie',
|
||||
radius: ['42%', '66%'],
|
||||
center: ['50%', '44%'],
|
||||
avoidLabelOverlap: true,
|
||||
itemStyle: { borderColor: '#fff', borderWidth: 2 },
|
||||
label: { formatter: '{b}\n{d}%', color: '#5b6a80', fontSize: 11 },
|
||||
labelLine: { length: 8, length2: 8 },
|
||||
data: distributionRows.value.map(item => ({
|
||||
name: item.appName || item.appCode,
|
||||
value: item.amountCent,
|
||||
})),
|
||||
},
|
||||
],
|
||||
}))
|
||||
|
||||
onMounted(() => {
|
||||
void loadAll()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="资金看板" desc="今日资金、待办与近 14 日趋势一屏总览">
|
||||
<el-button :loading="loading" @click="loadAll">
|
||||
<el-icon style="margin-right: 4px"><Refresh /></el-icon>刷新数据
|
||||
</el-button>
|
||||
</PageHeader>
|
||||
|
||||
<div v-if="summaryError" class="notice danger" style="margin-bottom: 16px">
|
||||
概览数据加载失败:{{ summaryError }}。其余区块可独立刷新查看。
|
||||
</div>
|
||||
<div v-else-if="summary" class="notice info" style="margin-bottom: 16px">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<div>
|
||||
双人复核阈值:<strong>{{ formatCent(summary.dualControlThresholdCent) }}</strong>。
|
||||
单笔金额达到该阈值须第二人复核后才可确认到账,复核人不得与操作人为同一人。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-loading="summaryLoading" class="stat-grid">
|
||||
<StatCard
|
||||
v-for="item in stats"
|
||||
:key="item.label"
|
||||
:label="item.label"
|
||||
:value="item.value"
|
||||
:sub="item.sub"
|
||||
:tone="item.tone"
|
||||
:icon="item.icon"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-loading="summaryLoading" class="card">
|
||||
<div class="card-title">
|
||||
<span>待办中心</span>
|
||||
<span class="small muted">合计 {{ todoItems.reduce((sum, item) => sum + item.count, 0) }} 项</span>
|
||||
</div>
|
||||
<div class="todo-grid">
|
||||
<div v-for="item in todoItems" :key="item.key" class="todo-item">
|
||||
<div class="todo-main">
|
||||
<div class="todo-label">
|
||||
<span>{{ item.label }}</span>
|
||||
<el-badge v-if="item.count > 0" :value="item.count" :max="99" :type="item.tone === 'danger' ? 'danger' : 'warning'" />
|
||||
</div>
|
||||
<div class="small muted">{{ item.desc }}</div>
|
||||
</div>
|
||||
<div class="todo-action">
|
||||
<span v-if="item.count === 0" class="muted small">无</span>
|
||||
<el-button v-else link type="primary" @click="go(item.path)">去处理</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-row :gutter="16" style="margin-top: 16px">
|
||||
<el-col :xs="24" :lg="15">
|
||||
<div v-loading="trendLoading" class="card chart-card">
|
||||
<div class="card-title">
|
||||
<span>资金趋势</span>
|
||||
<el-radio-group :model-value="trendDays" size="small" @change="handleTrendDays">
|
||||
<el-radio-button :value="7">近 7 日</el-radio-button>
|
||||
<el-radio-button :value="14">近 14 日</el-radio-button>
|
||||
</el-radio-group>
|
||||
</div>
|
||||
<div v-if="trendError" class="notice danger">{{ trendError }}</div>
|
||||
<el-empty
|
||||
v-else-if="!trendLoading && !trendRows.length"
|
||||
description="暂无趋势数据"
|
||||
:image-size="80"
|
||||
/>
|
||||
<EChart v-else :option="trendOption" height="320px" />
|
||||
</div>
|
||||
</el-col>
|
||||
|
||||
<el-col :xs="24" :lg="9">
|
||||
<div v-loading="distributionLoading" class="card chart-card">
|
||||
<div class="card-title">
|
||||
<span>应用金额占比</span>
|
||||
<span class="small muted">近 30 日已到账</span>
|
||||
</div>
|
||||
<div v-if="distributionError" class="notice danger">{{ distributionError }}</div>
|
||||
<template v-else>
|
||||
<el-empty
|
||||
v-if="!distributionLoading && !distributionRows.length"
|
||||
description="近 30 日暂无到账数据"
|
||||
:image-size="80"
|
||||
/>
|
||||
<EChart v-else :option="distributionOption" height="320px" />
|
||||
</template>
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.todo-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.todo-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--fin-border);
|
||||
border-radius: 8px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
.todo-main {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.todo-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.todo-action {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,139 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ROLE_LABEL } from '@/constants'
|
||||
import { HOME_BY_ROLE } from '@/router/menu'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = useUserStore()
|
||||
|
||||
function queryText(value: unknown): string {
|
||||
if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : ''
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
const from = computed(() => queryText(route.query.from))
|
||||
const home = computed(() => {
|
||||
const role = store.role
|
||||
return role ? HOME_BY_ROLE[role] : '/dashboard'
|
||||
})
|
||||
|
||||
function goHome(): void {
|
||||
router.replace(home.value)
|
||||
}
|
||||
|
||||
function handleLogout(): void {
|
||||
store.logout()
|
||||
router.replace('/login')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="error-page">
|
||||
<div class="card error-card">
|
||||
<div class="error-icon">
|
||||
<el-icon><Lock /></el-icon>
|
||||
</div>
|
||||
<div class="error-code">403</div>
|
||||
<h1>无权访问该页面</h1>
|
||||
<p class="muted error-desc">
|
||||
当前账号没有该页面的访问权限。系统采用三角色职责分离,权限由服务端校验;如确需访问,请联系超级管理员授权。
|
||||
</p>
|
||||
|
||||
<div v-if="from" class="from-box small">
|
||||
<span class="muted">请求地址:</span>
|
||||
<span class="mono">{{ from }}</span>
|
||||
</div>
|
||||
|
||||
<div class="current-role small muted">
|
||||
当前身份:{{ store.role ? ROLE_LABEL[store.role] : '未登录' }}
|
||||
</div>
|
||||
|
||||
<div class="error-actions">
|
||||
<el-button type="primary" @click="goHome">返回首页</el-button>
|
||||
<el-button @click="handleLogout">退出登录</el-button>
|
||||
</div>
|
||||
|
||||
<div class="small muted error-foot">
|
||||
所有越权访问尝试都会被记录到审计日志。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.error-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px 16px;
|
||||
background: var(--fin-bg);
|
||||
}
|
||||
|
||||
.error-card {
|
||||
width: 100%;
|
||||
max-width: 520px;
|
||||
padding: 36px 34px 30px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error-icon {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
margin: 0 auto 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 16px;
|
||||
background: #fdf1f0;
|
||||
color: var(--el-color-danger);
|
||||
font-size: 30px;
|
||||
}
|
||||
|
||||
.error-code {
|
||||
font-size: 42px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 4px;
|
||||
color: var(--fin-text);
|
||||
}
|
||||
|
||||
.error-card h1 {
|
||||
margin: 4px 0 12px;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.error-desc {
|
||||
margin: 0 0 18px;
|
||||
font-size: 13px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.from-box {
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 10px;
|
||||
border: 1px solid var(--fin-border);
|
||||
border-radius: 8px;
|
||||
background: #f8fafc;
|
||||
word-break: break-all;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.current-role {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.error-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.error-foot {
|
||||
margin-top: 18px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,122 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ROLE_LABEL } from '@/constants'
|
||||
import { HOME_BY_ROLE } from '@/router/menu'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
const router = useRouter()
|
||||
const store = useUserStore()
|
||||
|
||||
const home = computed(() => {
|
||||
const role = store.role
|
||||
return role ? HOME_BY_ROLE[role] : '/dashboard'
|
||||
})
|
||||
|
||||
function goHome(): void {
|
||||
router.replace(home.value)
|
||||
}
|
||||
|
||||
function goBack(): void {
|
||||
const back = router.options.history.state.back
|
||||
if (typeof back === 'string' && back) {
|
||||
router.back()
|
||||
} else {
|
||||
goHome()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="error-page">
|
||||
<div class="card error-card">
|
||||
<div class="error-icon">
|
||||
<el-icon><QuestionFilled /></el-icon>
|
||||
</div>
|
||||
<div class="error-code">404</div>
|
||||
<h1>页面不存在</h1>
|
||||
<p class="muted error-desc">
|
||||
您访问的页面可能已被移除、地址输入有误,或链接已经失效。请核对地址后重试。
|
||||
</p>
|
||||
|
||||
<div class="current-role small muted">
|
||||
当前身份:{{ store.role ? ROLE_LABEL[store.role] : '未登录' }}
|
||||
</div>
|
||||
|
||||
<div class="error-actions">
|
||||
<el-button type="primary" @click="goHome">返回首页</el-button>
|
||||
<el-button @click="goBack">返回上一页</el-button>
|
||||
</div>
|
||||
|
||||
<div class="small muted error-foot">
|
||||
如从业务系统跳转进入,请返回原系统重新发起访问。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.error-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px 16px;
|
||||
background: var(--fin-bg);
|
||||
}
|
||||
|
||||
.error-card {
|
||||
width: 100%;
|
||||
max-width: 520px;
|
||||
padding: 36px 34px 30px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error-icon {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
margin: 0 auto 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 16px;
|
||||
background: #f0f5ff;
|
||||
color: var(--el-color-primary);
|
||||
font-size: 30px;
|
||||
}
|
||||
|
||||
.error-code {
|
||||
font-size: 42px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 4px;
|
||||
color: var(--fin-text);
|
||||
}
|
||||
|
||||
.error-card h1 {
|
||||
margin: 4px 0 12px;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.error-desc {
|
||||
margin: 0 0 10px;
|
||||
font-size: 13px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.current-role {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.error-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.error-foot {
|
||||
margin-top: 18px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,523 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, reactive, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import type { FormInstance, FormRules, InputInstance } from 'element-plus'
|
||||
import type { Role } from '@/types'
|
||||
import { APP_TITLE, ROLE_LABEL } from '@/constants'
|
||||
import { HOME_BY_ROLE } from '@/router/menu'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { ApiError, userMessage } from '@/utils/http'
|
||||
|
||||
interface DemoAccount {
|
||||
role: Role
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = useUserStore()
|
||||
|
||||
const formRef = ref<FormInstance>()
|
||||
const passwordRef = ref<InputInstance>()
|
||||
const form = reactive({
|
||||
username: '',
|
||||
password: '',
|
||||
totp: '',
|
||||
})
|
||||
const loading = ref(false)
|
||||
const errorText = ref('')
|
||||
|
||||
const rules: FormRules = {
|
||||
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
|
||||
totp: [
|
||||
{ required: true, message: '请输入 6 位动态口令', trigger: 'blur' },
|
||||
{ pattern: /^\d{6}$/, message: '动态口令必须为 6 位数字', trigger: 'blur' },
|
||||
],
|
||||
}
|
||||
|
||||
/** 演示账号:仅演示环境使用,生产环境必须使用个人账号 */
|
||||
const DEMO_ACCOUNTS: DemoAccount[] = [
|
||||
{ role: 'SUPER_ADMIN', username: 'admin', password: 'Super@Fin2026' },
|
||||
{ role: 'FINANCE', username: 'finance', password: 'Fin@2026Fund' },
|
||||
{ role: 'AUDITOR', username: 'auditor', password: 'Audit@2026View' },
|
||||
]
|
||||
|
||||
function queryText(value: unknown): string {
|
||||
if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : ''
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
/** 会话超时退出提示:由后端/布局跳转时携带 reason=expired */
|
||||
const expiredTip = computed(() => {
|
||||
if (queryText(route.query.reason) !== 'expired') return ''
|
||||
return queryText(route.query.message) || '会话已超时退出,请重新登录。'
|
||||
})
|
||||
|
||||
/** 站内跳转校验:必须以单个 / 开头,禁止 // 协议相对地址与站外地址 */
|
||||
function safeRedirect(value: unknown): string | null {
|
||||
const text = queryText(value)
|
||||
if (!text.startsWith('/') || text.startsWith('//')) return null
|
||||
return text
|
||||
}
|
||||
|
||||
function handleTotpInput(value: string): void {
|
||||
form.totp = value.replace(/\D/g, '').slice(0, 6)
|
||||
}
|
||||
|
||||
async function fillDemo(account: DemoAccount): Promise<void> {
|
||||
form.username = account.username
|
||||
form.password = account.password
|
||||
form.totp = '123456'
|
||||
errorText.value = ''
|
||||
await nextTick()
|
||||
passwordRef.value?.focus()
|
||||
}
|
||||
|
||||
async function handleLogin(): Promise<void> {
|
||||
if (loading.value || !formRef.value) return
|
||||
const valid = await formRef.value.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
loading.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
const result = await store.login({
|
||||
username: form.username.trim(),
|
||||
password: form.password,
|
||||
totp: form.totp,
|
||||
})
|
||||
|
||||
// 首次登录或密码被重置:必须先修改密码
|
||||
if (result.admin.mustChangePassword === 1) {
|
||||
await router.replace('/password')
|
||||
return
|
||||
}
|
||||
|
||||
const redirect = safeRedirect(route.query.redirect)
|
||||
const home = HOME_BY_ROLE[result.admin.role] || '/dashboard'
|
||||
await router.replace(redirect || home)
|
||||
} catch (error) {
|
||||
const message = userMessage(error as ApiError)
|
||||
errorText.value = message
|
||||
// 失败后清空敏感输入并回到密码框,避免密码残留
|
||||
form.password = ''
|
||||
form.totp = ''
|
||||
await nextTick()
|
||||
passwordRef.value?.focus()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="login-page">
|
||||
<section class="brand-panel">
|
||||
<div class="brand-head">
|
||||
<span class="brand-logo">F</span>
|
||||
<div>
|
||||
<div class="brand-name">{{ APP_TITLE }}</div>
|
||||
<div class="brand-sub">中央计费平台</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="brand-body">
|
||||
<div class="gold-line" />
|
||||
<h1>资金权威<br />全量审计</h1>
|
||||
<p class="brand-desc">
|
||||
面向多业务系统的统一收银、点数钱包与对账留痕平台。所有资金操作双人复核,全流程可追溯。
|
||||
</p>
|
||||
<ul class="brand-list">
|
||||
<li><el-icon><CircleCheck /></el-icon>双因子身份验证</li>
|
||||
<li><el-icon><CircleCheck /></el-icon>三角色职责分离</li>
|
||||
<li><el-icon><CircleCheck /></el-icon>等保基线 · 内网部署</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="brand-foot">仅限授权人员访问 · 操作全程留痕</div>
|
||||
</section>
|
||||
|
||||
<section class="login-side">
|
||||
<div class="login-wrap">
|
||||
<div class="card login-card">
|
||||
<h2>管理员登录</h2>
|
||||
<p class="muted small login-desc">请使用账号密码 + 身份验证器动态口令完成双因子验证。</p>
|
||||
|
||||
<div v-if="expiredTip" class="notice warn login-notice">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>{{ expiredTip }}</span>
|
||||
</div>
|
||||
<div v-if="errorText" class="notice danger login-notice" role="alert">
|
||||
<el-icon><CircleClose /></el-icon>
|
||||
<span>{{ errorText }}</span>
|
||||
</div>
|
||||
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" @submit.prevent="handleLogin">
|
||||
<el-form-item label="用户名" prop="username">
|
||||
<el-input v-model="form.username" size="large" placeholder="请输入用户名" autocomplete="username">
|
||||
<template #prefix>
|
||||
<el-icon><User /></el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="密码" prop="password">
|
||||
<el-input
|
||||
ref="passwordRef"
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
show-password
|
||||
size="large"
|
||||
placeholder="请输入密码"
|
||||
autocomplete="current-password"
|
||||
>
|
||||
<template #prefix>
|
||||
<el-icon><Lock /></el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="动态口令(TOTP)" prop="totp">
|
||||
<el-input
|
||||
v-model="form.totp"
|
||||
size="large"
|
||||
:maxlength="6"
|
||||
inputmode="numeric"
|
||||
autocomplete="one-time-code"
|
||||
placeholder="6 位数字动态码"
|
||||
@input="handleTotpInput"
|
||||
>
|
||||
<template #prefix>
|
||||
<el-icon><Key /></el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-button class="login-submit" type="primary" size="large" native-type="submit" :loading="loading">
|
||||
登录
|
||||
</el-button>
|
||||
</el-form>
|
||||
|
||||
<div class="login-hint small muted">
|
||||
连续 5 次失败将锁定账号 15 分钟;登录后 30 分钟无操作自动退出。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card demo-card">
|
||||
<div class="card-title">
|
||||
<span>演示账号</span>
|
||||
<el-tag size="small" type="info" effect="plain">点击填充</el-tag>
|
||||
</div>
|
||||
<div class="demo-list">
|
||||
<div
|
||||
v-for="item in DEMO_ACCOUNTS"
|
||||
:key="item.username"
|
||||
class="demo-item"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
@click="fillDemo(item)"
|
||||
@keydown.enter="fillDemo(item)"
|
||||
>
|
||||
<div class="demo-main">
|
||||
<span class="demo-role">{{ ROLE_LABEL[item.role] }}</span>
|
||||
<span class="demo-user mono">{{ item.username }}</span>
|
||||
</div>
|
||||
<span class="demo-password mono">{{ item.password }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="small muted">
|
||||
演示动态码统一为 <span class="mono">123456</span>。以上账号仅用于演示环境,生产环境请使用个人账号与真实动态口令。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card security-card">
|
||||
<div class="card-title">安全说明</div>
|
||||
<ul class="security-list small">
|
||||
<li><el-icon><Lock /></el-icon><span>双因子认证:账号密码 + 6 位 TOTP 动态口令。</span></li>
|
||||
<li><el-icon><WarningFilled /></el-icon><span>连续 5 次失败锁定 15 分钟,防止暴力破解。</span></li>
|
||||
<li><el-icon><Clock /></el-icon><span>30 分钟空闲自动退出,会话仅保存在当前标签页。</span></li>
|
||||
<li><el-icon><Document /></el-icon><span>全量操作审计,登录与资金操作均可追溯。</span></li>
|
||||
<li><el-icon><Monitor /></el-icon><span>生产环境仅内网访问,不暴露公网入口。</span></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.login-page {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(420px, 46%) 1fr;
|
||||
background: var(--fin-bg);
|
||||
}
|
||||
|
||||
.brand-panel {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
padding: 40px 48px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
color: #e6edf9;
|
||||
background: radial-gradient(circle at 20% 15%, #1b2b4a 0, #0d1728 55%, #0a1220 100%);
|
||||
}
|
||||
|
||||
.brand-panel::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -120px;
|
||||
right: -140px;
|
||||
width: 420px;
|
||||
height: 420px;
|
||||
border: 1px solid rgba(200, 164, 92, 0.18);
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.brand-panel::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -260px;
|
||||
left: -220px;
|
||||
width: 560px;
|
||||
height: 560px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.brand-head {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.brand-logo {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border-radius: 11px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
color: #101828;
|
||||
background: linear-gradient(135deg, #c8a45c, #a8813c);
|
||||
}
|
||||
|
||||
.brand-name {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.brand-sub {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
letter-spacing: 3px;
|
||||
color: #9fb0c9;
|
||||
}
|
||||
|
||||
.brand-body {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
max-width: 460px;
|
||||
margin: auto 0;
|
||||
}
|
||||
|
||||
.gold-line {
|
||||
width: 52px;
|
||||
height: 3px;
|
||||
margin-bottom: 26px;
|
||||
background: linear-gradient(90deg, #c8a45c, transparent);
|
||||
}
|
||||
|
||||
.brand-body h1 {
|
||||
margin: 0 0 18px;
|
||||
font-size: 38px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.brand-desc {
|
||||
margin: 0 0 26px;
|
||||
font-size: 14px;
|
||||
line-height: 1.9;
|
||||
color: #9fb0c9;
|
||||
}
|
||||
|
||||
.brand-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
font-size: 14px;
|
||||
color: #cdd9ea;
|
||||
}
|
||||
|
||||
.brand-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.brand-list .el-icon {
|
||||
color: #c8a45c;
|
||||
}
|
||||
|
||||
.brand-foot {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
font-size: 12px;
|
||||
letter-spacing: 1px;
|
||||
color: #5f7392;
|
||||
}
|
||||
|
||||
.login-side {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding: 40px 32px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.login-wrap {
|
||||
width: 100%;
|
||||
max-width: 430px;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
padding: 26px 26px 22px;
|
||||
}
|
||||
|
||||
.login-card h2 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.login-desc {
|
||||
margin: 0 0 18px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.login-notice {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.login-submit {
|
||||
width: 100%;
|
||||
margin-top: 6px;
|
||||
letter-spacing: 4px;
|
||||
}
|
||||
|
||||
.login-hint {
|
||||
margin-top: 14px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.demo-card {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.demo-list {
|
||||
margin-bottom: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.demo-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--fin-border);
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s, background 0.15s;
|
||||
}
|
||||
|
||||
.demo-item:hover {
|
||||
border-color: var(--el-color-primary);
|
||||
background: #f7faff;
|
||||
}
|
||||
|
||||
.demo-item:focus-visible {
|
||||
outline: 2px solid var(--el-color-primary-light-5);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.demo-main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.demo-role {
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
background: #eef3fe;
|
||||
color: var(--fin-text-2);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.demo-user {
|
||||
color: var(--fin-text);
|
||||
}
|
||||
|
||||
.demo-password {
|
||||
color: var(--fin-text-3);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.security-card {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.security-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
color: var(--fin-text-2);
|
||||
}
|
||||
|
||||
.security-list li {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 7px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.security-list .el-icon {
|
||||
flex: 0 0 auto;
|
||||
margin-top: 2px;
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.login-page {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.brand-panel {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.login-side {
|
||||
padding: 24px 16px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,686 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import {
|
||||
appApi,
|
||||
orderApi,
|
||||
type Approver,
|
||||
type CancelPayload,
|
||||
type ConfirmPayload,
|
||||
type OrderDetail,
|
||||
type OrderQuery,
|
||||
} from '@/api/core'
|
||||
import { ORDER_STATUS, ORDER_STATUS_OPTIONS, ORDER_TYPE_LABEL, PAY_METHOD_LABEL, REFUND_STATUS } from '@/constants'
|
||||
import { formatCent, formatPoints } from '@/utils/money'
|
||||
import { formatDateTime, remainText, toLocalString } from '@/utils/format'
|
||||
import { askTotp, confirmAction } from '@/utils/confirm'
|
||||
import { maskVoucher } from '@/utils/mask'
|
||||
import { userMessage, type ApiError } from '@/utils/http'
|
||||
import type { CsvColumn } from '@/utils/export'
|
||||
import type { AppInfo, OrderInfo, OrderStatus, OrderType, PayMethod, RefundStatus } from '@/types'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import ExportButton from '@/components/ExportButton.vue'
|
||||
|
||||
interface OrderFilters {
|
||||
appCode: string
|
||||
status: string
|
||||
orderType: string
|
||||
keyword: string
|
||||
from: string
|
||||
to: string
|
||||
}
|
||||
|
||||
const ORDER_TYPE_OPTIONS = (Object.keys(ORDER_TYPE_LABEL) as OrderType[]).map(value => ({
|
||||
value,
|
||||
label: ORDER_TYPE_LABEL[value],
|
||||
}))
|
||||
|
||||
/** 表格插槽中的 row 为 any,统一用带类型的映射函数取展示文案,避免隐式 any 索引 */
|
||||
function orderTypeText(type: OrderType): string {
|
||||
return ORDER_TYPE_LABEL[type]
|
||||
}
|
||||
|
||||
function payMethodText(method: PayMethod): string {
|
||||
return PAY_METHOD_LABEL[method]
|
||||
}
|
||||
|
||||
function orderStatusMeta(status: OrderStatus) {
|
||||
return ORDER_STATUS[status]
|
||||
}
|
||||
|
||||
function refundStatusMeta(status: RefundStatus) {
|
||||
return REFUND_STATUS[status]
|
||||
}
|
||||
|
||||
const route = useRoute()
|
||||
const store = useUserStore()
|
||||
|
||||
function queryText(value: unknown): string {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
const STATUS_VALUES = ORDER_STATUS_OPTIONS.map(item => item.value as string)
|
||||
const initStatus = queryText(route.query.status)
|
||||
|
||||
const filters = reactive<OrderFilters>({
|
||||
appCode: queryText(route.query.appCode),
|
||||
status: STATUS_VALUES.includes(initStatus) ? initStatus : '',
|
||||
orderType: '',
|
||||
keyword: '',
|
||||
from: '',
|
||||
to: '',
|
||||
})
|
||||
|
||||
const appOptions = ref<AppInfo[]>([])
|
||||
const rows = ref<OrderInfo[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const loading = ref(false)
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
try {
|
||||
appOptions.value = await appApi.list()
|
||||
} catch {
|
||||
appOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
function buildFilter(): OrderQuery {
|
||||
const query: OrderQuery = {}
|
||||
if (filters.appCode) query.appCode = filters.appCode
|
||||
if (filters.status) query.status = filters.status
|
||||
if (filters.orderType) query.orderType = filters.orderType
|
||||
const keyword = filters.keyword.trim()
|
||||
if (keyword) query.keyword = keyword
|
||||
if (filters.from) query.from = filters.from
|
||||
if (filters.to) query.to = filters.to
|
||||
return query
|
||||
}
|
||||
|
||||
async function loadOrders(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await orderApi.list({ ...buildFilter(), page: page.value, pageSize: pageSize.value })
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch {
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSearch(): void {
|
||||
if (filters.from && filters.to && filters.from > filters.to) {
|
||||
ElMessage.warning('开始日期不能晚于结束日期')
|
||||
return
|
||||
}
|
||||
page.value = 1
|
||||
void loadOrders()
|
||||
}
|
||||
|
||||
function handleReset(): void {
|
||||
filters.appCode = ''
|
||||
filters.status = ''
|
||||
filters.orderType = ''
|
||||
filters.keyword = ''
|
||||
filters.from = ''
|
||||
filters.to = ''
|
||||
page.value = 1
|
||||
void loadOrders()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void Promise.all([loadApps(), loadOrders()])
|
||||
})
|
||||
|
||||
function isExpired(expireAt: string): boolean {
|
||||
const diff = new Date(String(expireAt).replace(' ', 'T')).getTime() - Date.now()
|
||||
return Number.isFinite(diff) && diff <= 0
|
||||
}
|
||||
|
||||
/* ----------------------------- 订单详情 ----------------------------- */
|
||||
|
||||
const detailVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<OrderDetail | null>(null)
|
||||
|
||||
async function openDetail(row: OrderInfo): Promise<void> {
|
||||
detailVisible.value = true
|
||||
detail.value = null
|
||||
detailLoading.value = true
|
||||
try {
|
||||
detail.value = await orderApi.detail(row.id)
|
||||
} catch {
|
||||
detail.value = null
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- 确认到账 ----------------------------- */
|
||||
|
||||
const confirmVisible = ref(false)
|
||||
const confirmSubmitting = ref(false)
|
||||
const confirmOrder = ref<OrderInfo | null>(null)
|
||||
const approvers = ref<Approver[]>([])
|
||||
const approversLoading = ref(false)
|
||||
|
||||
const confirmForm = reactive({
|
||||
voucherNo: '',
|
||||
receiveAt: toLocalString(new Date()),
|
||||
secondApproverId: undefined as number | undefined,
|
||||
})
|
||||
|
||||
/** 复核人不得是本人,前端过滤一次(服务端会二次校验) */
|
||||
const approverOptions = computed(() => approvers.value.filter(item => item.id !== store.admin?.id))
|
||||
|
||||
async function loadApprovers(): Promise<void> {
|
||||
approversLoading.value = true
|
||||
try {
|
||||
approvers.value = await orderApi.approvers()
|
||||
} catch {
|
||||
approvers.value = []
|
||||
} finally {
|
||||
approversLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function openConfirm(row: OrderInfo): Promise<void> {
|
||||
confirmOrder.value = row
|
||||
confirmForm.voucherNo = ''
|
||||
confirmForm.receiveAt = toLocalString(new Date())
|
||||
confirmForm.secondApproverId = undefined
|
||||
confirmVisible.value = true
|
||||
if (row.needDualControl) await loadApprovers()
|
||||
}
|
||||
|
||||
async function submitConfirm(): Promise<void> {
|
||||
const order = confirmOrder.value
|
||||
if (!order) return
|
||||
const voucherNo = confirmForm.voucherNo.trim()
|
||||
if (voucherNo.length < 6) {
|
||||
ElMessage.warning('请填写银行回单/转账凭证号(不少于 6 位)')
|
||||
return
|
||||
}
|
||||
if (!confirmForm.receiveAt) {
|
||||
ElMessage.warning('请选择到账时间')
|
||||
return
|
||||
}
|
||||
if (order.needDualControl && !confirmForm.secondApproverId) {
|
||||
ElMessage.warning('该订单金额达到双人复核阈值,必须选择第二复核人')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '确认到账',
|
||||
message: `订单 ${order.outTradeNo}(${formatCent(order.amountCent)})确认后将写入现金台账、点数流水并触发 webhook 通知,是否继续?`,
|
||||
confirmText: '确认到账',
|
||||
requireType: '确认到账',
|
||||
type: 'warning',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('确认到账')
|
||||
if (!totp) return
|
||||
|
||||
const payload: ConfirmPayload = { voucherNo, receiveAt: confirmForm.receiveAt, totp }
|
||||
if (confirmForm.secondApproverId) payload.secondApproverId = confirmForm.secondApproverId
|
||||
|
||||
confirmSubmitting.value = true
|
||||
try {
|
||||
const result = await orderApi.confirm(order.id, payload)
|
||||
ElMessage.success(`确认成功,已入账 ${formatPoints(result.pointsGained)} 点`)
|
||||
confirmVisible.value = false
|
||||
await loadOrders()
|
||||
} catch (err) {
|
||||
ElMessage.error(userMessage(err as ApiError))
|
||||
} finally {
|
||||
confirmSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- 关闭订单 ----------------------------- */
|
||||
|
||||
const cancelVisible = ref(false)
|
||||
const cancelSubmitting = ref(false)
|
||||
const cancelOrder = ref<OrderInfo | null>(null)
|
||||
const cancelForm = reactive({ reason: '' })
|
||||
|
||||
function openCancel(row: OrderInfo): void {
|
||||
cancelOrder.value = row
|
||||
cancelForm.reason = ''
|
||||
cancelVisible.value = true
|
||||
}
|
||||
|
||||
async function submitCancel(): Promise<void> {
|
||||
const order = cancelOrder.value
|
||||
if (!order) return
|
||||
const reason = cancelForm.reason.trim()
|
||||
if (reason.length < 5) {
|
||||
ElMessage.warning('请填写关单原因(不少于 5 个字)')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '关闭订单',
|
||||
message: `订单 ${order.outTradeNo}(${formatCent(order.amountCent)})关闭后不可恢复,且不会入账,是否继续?`,
|
||||
confirmText: '确认关单',
|
||||
requireType: '确认关单',
|
||||
type: 'error',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('关闭订单')
|
||||
if (!totp) return
|
||||
|
||||
const payload: CancelPayload = { reason, totp }
|
||||
|
||||
cancelSubmitting.value = true
|
||||
try {
|
||||
await orderApi.cancel(order.id, payload)
|
||||
ElMessage.success('订单已关闭')
|
||||
cancelVisible.value = false
|
||||
await loadOrders()
|
||||
} catch (err) {
|
||||
ElMessage.error(userMessage(err as ApiError))
|
||||
} finally {
|
||||
cancelSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- 导出 ----------------------------- */
|
||||
|
||||
function exportRow(order: OrderInfo): Record<string, any> {
|
||||
return {
|
||||
outTradeNo: order.outTradeNo,
|
||||
app: `${order.appName}(${order.appCode})`,
|
||||
user: `${order.businessUserId} / ${order.usernameSnapshot}`,
|
||||
orderType: ORDER_TYPE_LABEL[order.orderType],
|
||||
amountYuan: formatCent(order.amountCent, false),
|
||||
points: order.pointsGained,
|
||||
status: ORDER_STATUS[order.status].label,
|
||||
createTime: formatDateTime(order.createTime),
|
||||
}
|
||||
}
|
||||
|
||||
const exportColumns: CsvColumn<Record<string, any>>[] = [
|
||||
{ label: '订单号', value: row => row.outTradeNo },
|
||||
{ label: '应用', value: row => row.app },
|
||||
{ label: '业务用户', value: row => row.user },
|
||||
{ label: '类型', value: row => row.orderType },
|
||||
{ label: '金额(元)', value: row => row.amountYuan },
|
||||
{ label: '点数', value: row => row.points },
|
||||
{ label: '状态', value: row => row.status },
|
||||
{ label: '创建时间', value: row => row.createTime },
|
||||
]
|
||||
|
||||
async function fetchExportRows(): Promise<Record<string, any>[]> {
|
||||
const list = await orderApi.export(buildFilter())
|
||||
return list.map(exportRow)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="充值订单" desc="线下充值订单的确认到账、关单与导出;确认到账会同时写入现金台账、点数流水与 webhook。">
|
||||
<ExportButton
|
||||
v-perm="'fin:export'"
|
||||
filename="充值订单"
|
||||
:columns="exportColumns"
|
||||
:fetcher="fetchExportRows"
|
||||
label="导出订单"
|
||||
/>
|
||||
</PageHeader>
|
||||
|
||||
<div class="notice info">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<span>
|
||||
确认到账属于资金入账动作,会同时写入现金台账、点数流水并触发 webhook;
|
||||
金额达到应用策略阈值的订单必须由另一名管理员复核后才可入账。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<el-select v-model="filters.appCode" placeholder="全部应用" clearable style="width: 180px">
|
||||
<el-option v-for="app in appOptions" :key="app.appCode" :label="app.appName" :value="app.appCode" />
|
||||
</el-select>
|
||||
<el-select v-model="filters.status" placeholder="全部状态" clearable style="width: 130px">
|
||||
<el-option v-for="item in ORDER_STATUS_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<el-select v-model="filters.orderType" placeholder="全部类型" clearable style="width: 150px">
|
||||
<el-option v-for="item in ORDER_TYPE_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="filters.keyword"
|
||||
placeholder="订单号 / 用户ID / 用户名"
|
||||
clearable
|
||||
style="width: 220px"
|
||||
@keyup.enter="handleSearch"
|
||||
/>
|
||||
<el-date-picker
|
||||
v-model="filters.from"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
placeholder="开始日期"
|
||||
style="width: 150px"
|
||||
/>
|
||||
<span class="muted">至</span>
|
||||
<el-date-picker
|
||||
v-model="filters.to"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
placeholder="结束日期"
|
||||
style="width: 150px"
|
||||
/>
|
||||
<el-button type="primary" @click="handleSearch">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
</div>
|
||||
|
||||
<el-table :data="rows" v-loading="loading" row-key="id" border stripe empty-text="暂无订单">
|
||||
<el-table-column label="订单号" min-width="190">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.outTradeNo }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="应用" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.appName }}</div>
|
||||
<div class="mono muted small">{{ row.appCode }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="业务用户" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<div class="mono">{{ row.businessUserId }}</div>
|
||||
<div class="muted small">{{ row.usernameSnapshot }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="类型" width="130">
|
||||
<template #default="{ row }">{{ orderTypeText(row.orderType) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="支付方式" width="110">
|
||||
<template #default="{ row }">{{ payMethodText(row.payMethod) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="金额" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num amount">{{ formatCent(row.amountCent) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="可得点数" width="110" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ formatPoints(row.pointsGained) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="orderStatusMeta(row.status).tag" effect="light">{{ orderStatusMeta(row.status).label }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="双人复核" width="110">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-if="row.needDualControl" type="warning" effect="plain">需复核</el-tag>
|
||||
<span v-else class="muted">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="创建时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="过期时间" width="140">
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.status === 'PENDING'" :class="{ expired: isExpired(row.expiresAt) }">
|
||||
{{ remainText(row.expiresAt) }}
|
||||
</span>
|
||||
<span v-else class="muted">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="190" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="openDetail(row)">详情</el-button>
|
||||
<el-button
|
||||
v-if="row.status === 'PENDING'"
|
||||
v-perm="'fin:recharge:confirm'"
|
||||
link
|
||||
type="success"
|
||||
@click="openConfirm(row)"
|
||||
>
|
||||
确认到账
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="row.status === 'PENDING'"
|
||||
v-perm="'fin:order:cancel'"
|
||||
link
|
||||
type="danger"
|
||||
@click="openCancel(row)"
|
||||
>
|
||||
关单
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page"
|
||||
v-model:page-size="pageSize"
|
||||
background
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
:total="total"
|
||||
@size-change="handleSearch"
|
||||
@current-change="loadOrders"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-drawer v-model="detailVisible" title="订单详情" size="760px" destroy-on-close>
|
||||
<div v-loading="detailLoading" class="detail-body">
|
||||
<template v-if="detail">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="订单号">
|
||||
<span class="mono">{{ detail.order.outTradeNo }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="状态">
|
||||
<el-tag :type="ORDER_STATUS[detail.order.status].tag" effect="light">
|
||||
{{ ORDER_STATUS[detail.order.status].label }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="应用">{{ detail.order.appName }}({{ detail.order.appCode }})</el-descriptions-item>
|
||||
<el-descriptions-item label="业务用户">
|
||||
<span class="mono">{{ detail.order.businessUserId }}</span> / {{ detail.order.usernameSnapshot }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="类型">{{ ORDER_TYPE_LABEL[detail.order.orderType] }}</el-descriptions-item>
|
||||
<el-descriptions-item label="支付方式">{{ PAY_METHOD_LABEL[detail.order.payMethod] }}</el-descriptions-item>
|
||||
<el-descriptions-item label="订单金额">{{ formatCent(detail.order.amountCent) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="可得点数">{{ formatPoints(detail.order.pointsGained) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="已退金额">{{ formatCent(detail.order.refundedAmountCent) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="现金实收">{{ formatCent(detail.order.cashInCent) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="现金退回">{{ formatCent(detail.order.cashOutCent) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="双人复核">
|
||||
<el-tag v-if="detail.order.needDualControl" type="warning" effect="plain">需复核</el-tag>
|
||||
<span v-else class="muted">不需要</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="确认人">{{ detail.order.confirmedByAdminName || '—' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="复核人">{{ detail.order.secondApproverName || '—' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="创建时间">{{ formatDateTime(detail.order.createTime) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="支付时间">{{ formatDateTime(detail.order.paidAt) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="过期时间">{{ formatDateTime(detail.order.expiresAt) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="备注">{{ detail.order.remark || '—' }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div class="card-title detail-title">退款记录</div>
|
||||
<el-table :data="detail.refunds" border size="small" empty-text="暂无退款记录">
|
||||
<el-table-column label="退款单号" width="110">
|
||||
<template #default="{ row }"><span class="mono">#{{ row.id }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="退款金额" width="130" align="right">
|
||||
<template #default="{ row }"><span class="num">{{ formatCent(row.amountCent) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="扣回点数" width="100" align="right">
|
||||
<template #default="{ row }"><span class="num">{{ formatPoints(row.pointsDeducted) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="refundStatusMeta(row.status).tag" effect="light">
|
||||
{{ refundStatusMeta(row.status).label }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="发起人" width="120">
|
||||
<template #default="{ row }">{{ row.operatorAdminName }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="凭证号" min-width="140">
|
||||
<template #default="{ row }"><span class="mono">{{ maskVoucher(row.voucherNo) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="card-title detail-title">现金流水</div>
|
||||
<el-table :data="detail.cashFlows" border size="small" empty-text="暂无现金流水">
|
||||
<el-table-column label="流水号" width="100">
|
||||
<template #default="{ row }"><span class="mono">#{{ row.id }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="方向" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.direction === 'IN' ? 'success' : 'danger'" effect="plain">
|
||||
{{ row.direction === 'IN' ? '收款' : '退款' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="金额" width="130" align="right">
|
||||
<template #default="{ row }"><span class="num">{{ formatCent(row.amountCent) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="到账时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.receivedAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="凭证号" min-width="140">
|
||||
<template #default="{ row }"><span class="mono">{{ maskVoucher(row.voucherNo) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="备注" min-width="140">
|
||||
<template #default="{ row }">{{ row.remark || '—' }}</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</template>
|
||||
<el-empty v-else-if="!detailLoading" description="订单详情加载失败,请关闭后重试" />
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="detailVisible = false">关闭</el-button>
|
||||
</template>
|
||||
</el-drawer>
|
||||
|
||||
<el-dialog
|
||||
v-model="confirmVisible"
|
||||
:title="confirmOrder ? `确认到账 · ${confirmOrder.outTradeNo}` : '确认到账'"
|
||||
width="540px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
>
|
||||
<div v-if="confirmOrder" class="notice warn dialog-notice">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>
|
||||
订单金额 {{ formatCent(confirmOrder.amountCent) }},可得点数
|
||||
{{ formatPoints(confirmOrder.pointsGained) }}。确认后立即入账并触发 webhook。
|
||||
</span>
|
||||
</div>
|
||||
<el-form label-width="100px">
|
||||
<el-form-item label="凭证号" required>
|
||||
<el-input v-model="confirmForm.voucherNo" maxlength="32" placeholder="银行回单/转账凭证号(不少于 6 位)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="到账时间" required>
|
||||
<el-date-picker
|
||||
v-model="confirmForm.receiveAt"
|
||||
type="datetime"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
placeholder="选择到账时间"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="confirmOrder?.needDualControl" label="复核人" required>
|
||||
<el-select
|
||||
v-model="confirmForm.secondApproverId"
|
||||
placeholder="请选择第二复核人"
|
||||
:loading="approversLoading"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in approverOptions"
|
||||
:key="item.id"
|
||||
:label="`${item.username}(${item.role})`"
|
||||
:value="item.id"
|
||||
/>
|
||||
</el-select>
|
||||
<span v-if="!approversLoading && !approverOptions.length" class="muted small field-hint">
|
||||
暂无可用复核人(不可选择本人),请联系管理员确认后再入账
|
||||
</span>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="confirmVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="confirmSubmitting" @click="submitConfirm">确认到账</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
v-model="cancelVisible"
|
||||
:title="cancelOrder ? `关闭订单 · ${cancelOrder.outTradeNo}` : '关闭订单'"
|
||||
width="520px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
>
|
||||
<div class="notice danger dialog-notice">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>关单后订单不可恢复、不会入账,操作会写入审计日志。</span>
|
||||
</div>
|
||||
<el-form label-width="100px">
|
||||
<el-form-item label="关单原因" required>
|
||||
<el-input
|
||||
v-model="cancelForm.reason"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
maxlength="200"
|
||||
show-word-limit
|
||||
placeholder="请填写关单原因(不少于 5 个字)"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="cancelVisible = false">取消</el-button>
|
||||
<el-button type="danger" :loading="cancelSubmitting" @click="submitCancel">关闭订单</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.expired {
|
||||
color: var(--el-color-danger);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.amount {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.detail-body {
|
||||
min-height: 200px;
|
||||
}
|
||||
|
||||
.detail-title {
|
||||
margin: 18px 0 10px;
|
||||
}
|
||||
|
||||
.dialog-notice {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,354 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { FormInstance, FormRules } from 'element-plus'
|
||||
import { APP_TITLE } from '@/constants'
|
||||
import { HOME_BY_ROLE } from '@/router/menu'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { ApiError, userMessage } from '@/utils/http'
|
||||
import { checkPassword } from '@/utils/validate'
|
||||
|
||||
const router = useRouter()
|
||||
const store = useUserStore()
|
||||
|
||||
const formRef = ref<FormInstance>()
|
||||
const loading = ref(false)
|
||||
|
||||
const form = reactive({
|
||||
oldPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
})
|
||||
|
||||
const pwdCheck = computed(() => checkPassword(form.newPassword))
|
||||
const forced = computed(() => store.mustChangePassword)
|
||||
|
||||
const strengthColor = computed(() => {
|
||||
if (pwdCheck.value.score >= 100) return '#0f9d70'
|
||||
if (pwdCheck.value.score >= 83) return '#1d5bdb'
|
||||
if (pwdCheck.value.score >= 66) return '#c47d0a'
|
||||
return '#c0392b'
|
||||
})
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
if (!form.oldPassword || !form.newPassword || !form.confirmPassword) return false
|
||||
if (!pwdCheck.value.valid) return false
|
||||
if (form.newPassword !== form.confirmPassword) return false
|
||||
return form.newPassword !== form.oldPassword
|
||||
})
|
||||
|
||||
function validateNewPassword(_rule: unknown, value: string, callback: (error?: string | Error) => void): void {
|
||||
const password = value || ''
|
||||
if (!password) {
|
||||
callback(new Error('请输入新密码'))
|
||||
return
|
||||
}
|
||||
if (!checkPassword(password).valid) {
|
||||
callback(new Error('新密码需满足全部 6 条规则'))
|
||||
return
|
||||
}
|
||||
if (password === form.oldPassword) {
|
||||
callback(new Error('新密码不得与原密码相同'))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
}
|
||||
|
||||
function validateConfirm(_rule: unknown, value: string, callback: (error?: string | Error) => void): void {
|
||||
if (!value) {
|
||||
callback(new Error('请再次输入新密码'))
|
||||
return
|
||||
}
|
||||
if (value !== form.newPassword) {
|
||||
callback(new Error('两次输入的新密码不一致'))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
}
|
||||
|
||||
const rules: FormRules = {
|
||||
oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
|
||||
newPassword: [{ validator: validateNewPassword, trigger: 'blur' }],
|
||||
confirmPassword: [{ validator: validateConfirm, trigger: 'blur' }],
|
||||
}
|
||||
|
||||
async function handleSubmit(): Promise<void> {
|
||||
if (loading.value || !formRef.value) return
|
||||
const valid = await formRef.value.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
const wasForced = forced.value
|
||||
loading.value = true
|
||||
try {
|
||||
await store.changePassword(form.oldPassword, form.newPassword)
|
||||
ElMessage.success('密码修改成功')
|
||||
|
||||
const role = store.role
|
||||
if (wasForced) {
|
||||
await router.replace(role ? HOME_BY_ROLE[role] : '/dashboard')
|
||||
return
|
||||
}
|
||||
|
||||
// 主动改密:优先回到上一页,没有可回退的站内页面则回看板
|
||||
const back = router.options.history.state.back
|
||||
if (typeof back === 'string' && back && back !== '/login') {
|
||||
router.back()
|
||||
} else {
|
||||
await router.replace('/dashboard')
|
||||
}
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleLogout(): void {
|
||||
store.logout()
|
||||
router.replace('/login')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="pwd-page">
|
||||
<header class="pwd-top">
|
||||
<div class="brand">
|
||||
<span class="logo">F</span>
|
||||
<div>
|
||||
<div class="brand-name">{{ APP_TITLE }}</div>
|
||||
<div class="brand-sub">中央计费平台</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-button text class="logout-btn" @click="handleLogout">
|
||||
<el-icon><SwitchButton /></el-icon>
|
||||
退出登录
|
||||
</el-button>
|
||||
</header>
|
||||
|
||||
<main class="pwd-main">
|
||||
<div class="card pwd-card">
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h2>修改登录密码</h2>
|
||||
<p class="desc">首次登录或密码重置后必须修改密码,且不得与最近 3 次使用过的密码相同。</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<el-tag size="small" effect="plain" type="info">{{ store.displayName || '当前账号' }}</el-tag>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="notice info pwd-notice">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<span>新密码不少于 12 位,需同时包含大写字母、小写字母、数字与特殊符号,且不含空格与中文。</span>
|
||||
</div>
|
||||
<div v-if="forced" class="notice warn pwd-notice">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>当前为首次登录或密码已重置,修改成功前无法访问其他页面。</span>
|
||||
</div>
|
||||
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" @submit.prevent="handleSubmit">
|
||||
<el-form-item label="原密码" prop="oldPassword">
|
||||
<el-input
|
||||
v-model="form.oldPassword"
|
||||
type="password"
|
||||
show-password
|
||||
size="large"
|
||||
placeholder="请输入当前密码"
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="新密码" prop="newPassword">
|
||||
<el-input
|
||||
v-model="form.newPassword"
|
||||
type="password"
|
||||
show-password
|
||||
size="large"
|
||||
placeholder="请输入新密码"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<div class="strength">
|
||||
<el-progress
|
||||
:percentage="pwdCheck.score"
|
||||
:color="strengthColor"
|
||||
:show-text="false"
|
||||
:stroke-width="8"
|
||||
/>
|
||||
<div class="strength-text small">
|
||||
<span>密码强度:<strong :style="{ color: strengthColor }">{{ pwdCheck.levelText }}</strong></span>
|
||||
<span class="muted">{{ pwdCheck.score }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rule-grid">
|
||||
<div
|
||||
v-for="rule in pwdCheck.rules"
|
||||
:key="rule.key"
|
||||
class="rule"
|
||||
:class="rule.ok ? 'ok' : 'fail'"
|
||||
>
|
||||
<el-icon>
|
||||
<CircleCheck v-if="rule.ok" />
|
||||
<CircleClose v-else />
|
||||
</el-icon>
|
||||
<span>{{ rule.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-form-item label="确认新密码" prop="confirmPassword">
|
||||
<el-input
|
||||
v-model="form.confirmPassword"
|
||||
type="password"
|
||||
show-password
|
||||
size="large"
|
||||
placeholder="请再次输入新密码"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<div class="pwd-actions">
|
||||
<el-button type="primary" size="large" native-type="submit" :loading="loading" :disabled="!canSubmit">
|
||||
确认修改
|
||||
</el-button>
|
||||
<el-button size="large" @click="handleLogout">退出登录</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
|
||||
<div class="small muted pwd-foot">
|
||||
修改密码会记录审计日志;如非本人操作,请立即退出登录并联系超级管理员。
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.pwd-page {
|
||||
min-height: 100vh;
|
||||
background: var(--fin-bg);
|
||||
}
|
||||
|
||||
.pwd-top {
|
||||
height: 64px;
|
||||
padding: 0 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background: var(--fin-sidebar);
|
||||
color: #e6edf9;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 9px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
font-weight: 800;
|
||||
color: #101828;
|
||||
background: linear-gradient(135deg, #c8a45c, #a8813c);
|
||||
}
|
||||
|
||||
.brand-name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
|
||||
.brand-sub {
|
||||
margin-top: 2px;
|
||||
font-size: 11px;
|
||||
letter-spacing: 2px;
|
||||
color: var(--fin-sidebar-text);
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
color: #cdd9ea;
|
||||
}
|
||||
|
||||
.pwd-main {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 32px 16px 48px;
|
||||
}
|
||||
|
||||
.pwd-card {
|
||||
width: 100%;
|
||||
max-width: 620px;
|
||||
}
|
||||
|
||||
.pwd-notice {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.strength {
|
||||
margin: -4px 0 10px;
|
||||
}
|
||||
|
||||
.strength-text {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 6px;
|
||||
color: var(--fin-text-2);
|
||||
}
|
||||
|
||||
.rule-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 6px 14px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.rule {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.rule.ok {
|
||||
color: var(--el-color-success);
|
||||
}
|
||||
|
||||
.rule.fail {
|
||||
color: var(--fin-text-3);
|
||||
}
|
||||
|
||||
.pwd-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.pwd-foot {
|
||||
margin-top: 14px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.rule-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.pwd-top {
|
||||
padding: 0 16px;
|
||||
}
|
||||
|
||||
.pwd-main {
|
||||
padding: 20px 12px 32px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,829 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { payApi } from '@/api/pay'
|
||||
import type { PayCreatePayload, PayPreviewQuery, PayStatus } from '@/api/pay'
|
||||
import type { OrderStatus, PayOrder, PayPreview } from '@/types'
|
||||
import { ORDER_STATUS, ORDER_TYPE_LABEL, APP_TITLE } from '@/constants'
|
||||
import { ApiError, userMessage } from '@/utils/http'
|
||||
import { confirmAction } from '@/utils/confirm'
|
||||
import { formatCent, formatPoints, yuanInputToCent } from '@/utils/money'
|
||||
import { formatDateTime, remainText } from '@/utils/format'
|
||||
import { isSafeRedirectHost, newIdempotencyKey } from '@/utils/validate'
|
||||
|
||||
interface DemoApp {
|
||||
appCode: string
|
||||
appName: string
|
||||
}
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
function queryText(value: unknown): string {
|
||||
if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : ''
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
const appCode = ref(queryText(route.query.appCode))
|
||||
const ticket = ref(queryText(route.query.ticket))
|
||||
const redirectUri = ref(queryText(route.query.redirectUri))
|
||||
/** 无凭证进入时为演示模式 */
|
||||
const demoMode = ref(!appCode.value || !ticket.value)
|
||||
|
||||
const preview = ref<PayPreview | null>(null)
|
||||
const previewLoading = ref(false)
|
||||
const previewError = ref('')
|
||||
const ticketInvalid = ref(false)
|
||||
const remainTick = ref(Date.now())
|
||||
|
||||
const order = ref<PayOrder | null>(null)
|
||||
const orderLoading = ref(false)
|
||||
const orderError = ref('')
|
||||
|
||||
const statusInfo = ref<PayStatus | null>(null)
|
||||
const statusLoading = ref(false)
|
||||
const pollCount = ref(0)
|
||||
const POLL_LIMIT = 20
|
||||
|
||||
const amountYuan = ref('')
|
||||
const QUICK_AMOUNTS: number[] = [100, 500, 1000, 5000]
|
||||
const MAX_AMOUNT_CENT = 50000 * 100
|
||||
|
||||
const DEMO_APPS: DemoApp[] = [
|
||||
{ appCode: 'litho-sim', appName: '光刻仿真平台' },
|
||||
{ appCode: 'libs-platform', appName: 'LIBS 显微检测数据中台' },
|
||||
]
|
||||
const demoAppCode = ref('litho-sim')
|
||||
const demoLoading = ref(false)
|
||||
const demoError = ref('')
|
||||
|
||||
let remainTimer = 0
|
||||
let pollTimer = 0
|
||||
let pollInFlight = false
|
||||
|
||||
const ticketRemain = computed(() => {
|
||||
// 依赖 remainTick,保证剩余时间每 30 秒重新计算
|
||||
void remainTick.value
|
||||
return preview.value ? remainText(preview.value.ticketExpiresAt) : '—'
|
||||
})
|
||||
const ticketExpired = computed(() => ticketRemain.value === '已过期')
|
||||
|
||||
const minAmountCent = computed(() => preview.value?.minAmountCent || 100)
|
||||
const rechargeCent = computed(() => yuanInputToCent(amountYuan.value))
|
||||
const expectedPoints = computed(() => {
|
||||
const cent = rechargeCent.value
|
||||
if (!cent || !preview.value) return 0
|
||||
return Math.floor((cent / 100) * preview.value.pointsPerYuan)
|
||||
})
|
||||
const amountError = computed(() => {
|
||||
const text = amountYuan.value.trim()
|
||||
if (!text) return ''
|
||||
const cent = rechargeCent.value
|
||||
if (!cent) return '金额格式不正确,仅支持最多两位小数的正数'
|
||||
if (cent < minAmountCent.value) return `最低充值 ${formatCent(minAmountCent.value, false)} 元`
|
||||
if (cent > MAX_AMOUNT_CENT) return '单次充值金额不得超过 50000 元'
|
||||
return ''
|
||||
})
|
||||
|
||||
const vipPlans = computed(() => preview.value?.plans ?? [])
|
||||
|
||||
const orderStatus = computed<OrderStatus>(() => statusInfo.value?.status || order.value?.status || 'PENDING')
|
||||
const statusMeta = computed(() => ORDER_STATUS[orderStatus.value])
|
||||
const isPaid = computed(() => orderStatus.value === 'PAID')
|
||||
const isClosed = computed(() => orderStatus.value === 'CANCELLED' || orderStatus.value === 'REFUNDED')
|
||||
const pollExhausted = computed(() => pollCount.value >= POLL_LIMIT && !isPaid.value && !isClosed.value)
|
||||
|
||||
/** 返回业务系统:仅接受后端下发的 http/https 地址,且主机必须是合法域名,防止协议注入与 IP 直连 */
|
||||
const payRedirectUri = computed(() => {
|
||||
const uri = order.value?.redirectUri || redirectUri.value
|
||||
if (!uri) return ''
|
||||
try {
|
||||
const parsed = new URL(uri)
|
||||
const protocolOk = parsed.protocol === 'https:' || parsed.protocol === 'http:'
|
||||
return protocolOk && isSafeRedirectHost(parsed.hostname) ? uri : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* 下单幂等键:同一次下单的重试必须复用同一个键,服务端据此返回首次结果;
|
||||
* 下单参数变化或下单成功后重新生成,避免把上一笔订单结果错误复用。
|
||||
*/
|
||||
let idempotencyKey = ''
|
||||
let idempotencySignature = ''
|
||||
|
||||
function ensureIdempotencyKey(signature: string): string {
|
||||
if (!idempotencyKey || idempotencySignature !== signature) {
|
||||
idempotencyKey = newIdempotencyKey('pay')
|
||||
idempotencySignature = signature
|
||||
}
|
||||
return idempotencyKey
|
||||
}
|
||||
|
||||
function resetIdempotencyKey(): void {
|
||||
idempotencyKey = ''
|
||||
idempotencySignature = ''
|
||||
}
|
||||
|
||||
function stopPolling(): void {
|
||||
if (pollTimer) {
|
||||
window.clearInterval(pollTimer)
|
||||
pollTimer = 0
|
||||
}
|
||||
}
|
||||
|
||||
function markTicketInvalid(): void {
|
||||
ticketInvalid.value = true
|
||||
preview.value = null
|
||||
previewError.value = '凭证无效、已过期或已被使用,请返回业务系统重新发起。'
|
||||
stopPolling()
|
||||
}
|
||||
|
||||
function handleFailure(error: unknown, scope: 'preview' | 'order' | 'demo'): void {
|
||||
const err = error as ApiError
|
||||
const message = userMessage(err)
|
||||
if (err.code === 7001) {
|
||||
markTicketInvalid()
|
||||
ElMessage.error(message)
|
||||
return
|
||||
}
|
||||
if (scope === 'preview') {
|
||||
preview.value = null
|
||||
previewError.value = message
|
||||
}
|
||||
if (scope === 'order') orderError.value = message
|
||||
if (scope === 'demo') demoError.value = message
|
||||
ElMessage.error(message)
|
||||
}
|
||||
|
||||
async function loadPreview(): Promise<void> {
|
||||
if (!appCode.value || !ticket.value) return
|
||||
previewLoading.value = true
|
||||
previewError.value = ''
|
||||
ticketInvalid.value = false
|
||||
try {
|
||||
const query: PayPreviewQuery = { appCode: appCode.value, ticket: ticket.value }
|
||||
if (redirectUri.value) query.redirectUri = redirectUri.value
|
||||
preview.value = await payApi.preview(query)
|
||||
amountYuan.value = ''
|
||||
orderError.value = ''
|
||||
} catch (error) {
|
||||
handleFailure(error, 'preview')
|
||||
} finally {
|
||||
previewLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function generateDemoTicket(): Promise<void> {
|
||||
if (demoLoading.value) return
|
||||
demoLoading.value = true
|
||||
demoError.value = ''
|
||||
try {
|
||||
const data = await payApi.demoTicket(demoAppCode.value)
|
||||
appCode.value = data.appCode
|
||||
ticket.value = data.ticket
|
||||
redirectUri.value = data.redirectUri
|
||||
demoMode.value = true
|
||||
order.value = null
|
||||
statusInfo.value = null
|
||||
pollCount.value = 0
|
||||
stopPolling()
|
||||
await loadPreview()
|
||||
} catch (error) {
|
||||
handleFailure(error, 'demo')
|
||||
} finally {
|
||||
demoLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function pickAmount(value: number): void {
|
||||
amountYuan.value = String(value)
|
||||
}
|
||||
|
||||
async function submitRecharge(): Promise<void> {
|
||||
if (!preview.value || orderLoading.value || order.value) return
|
||||
const cent = rechargeCent.value
|
||||
if (!cent) {
|
||||
ElMessage.error('请输入充值金额')
|
||||
return
|
||||
}
|
||||
if (amountError.value) {
|
||||
ElMessage.error(amountError.value)
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '确认充值下单',
|
||||
message: `应用「${preview.value.appName}」,业务用户「${preview.value.usernameSnapshot}」,充值金额 ${formatCent(cent)},预计到账 ${formatPoints(expectedPoints.value)} 点。下单后凭证立即失效,请按收款信息线下转账。`,
|
||||
confirmText: '确认下单',
|
||||
type: 'warning',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
orderLoading.value = true
|
||||
orderError.value = ''
|
||||
try {
|
||||
const payload: PayCreatePayload = {
|
||||
appCode: appCode.value,
|
||||
ticket: ticket.value,
|
||||
orderType: 'recharge',
|
||||
amountCent: cent,
|
||||
idempotencyKey: ensureIdempotencyKey(`${appCode.value}|${ticket.value}|recharge|${cent}`),
|
||||
}
|
||||
if (redirectUri.value) payload.redirectUri = redirectUri.value
|
||||
order.value = await payApi.createOrder(payload)
|
||||
resetIdempotencyKey()
|
||||
statusInfo.value = null
|
||||
pollCount.value = 0
|
||||
startPolling()
|
||||
} catch (error) {
|
||||
handleFailure(error, 'order')
|
||||
} finally {
|
||||
orderLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitVip(plan: PayPreview['plans'][number]): Promise<void> {
|
||||
if (!preview.value || orderLoading.value || order.value) return
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '确认开通 VIP',
|
||||
message: `确认为「${preview.value.usernameSnapshot}」开通「${plan.planName}」,金额 ${formatCent(plan.priceCent)},有效期 ${plan.durationDays} 天。下单后凭证立即失效。`,
|
||||
confirmText: '确认下单',
|
||||
type: 'warning',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
orderLoading.value = true
|
||||
orderError.value = ''
|
||||
try {
|
||||
const payload: PayCreatePayload = {
|
||||
appCode: appCode.value,
|
||||
ticket: ticket.value,
|
||||
orderType: 'vip',
|
||||
planCode: plan.planCode,
|
||||
idempotencyKey: ensureIdempotencyKey(`${appCode.value}|${ticket.value}|vip|${plan.planCode}`),
|
||||
}
|
||||
if (redirectUri.value) payload.redirectUri = redirectUri.value
|
||||
order.value = await payApi.createOrder(payload)
|
||||
resetIdempotencyKey()
|
||||
statusInfo.value = null
|
||||
pollCount.value = 0
|
||||
startPolling()
|
||||
} catch (error) {
|
||||
handleFailure(error, 'order')
|
||||
} finally {
|
||||
orderLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshStatus(auto = false, force = false): Promise<void> {
|
||||
if (!order.value || pollInFlight || isPaid.value || isClosed.value) return
|
||||
if (!force && pollCount.value >= POLL_LIMIT) {
|
||||
stopPolling()
|
||||
return
|
||||
}
|
||||
|
||||
pollInFlight = true
|
||||
statusLoading.value = true
|
||||
pollCount.value = Math.min(pollCount.value + 1, POLL_LIMIT)
|
||||
try {
|
||||
const result = await payApi.status(order.value.outTradeNo)
|
||||
statusInfo.value = result
|
||||
if (order.value) {
|
||||
order.value.status = result.status
|
||||
order.value.expiresAt = result.expiresAt
|
||||
order.value.amountCent = result.amountCent
|
||||
order.value.pointsGained = result.pointsGained
|
||||
}
|
||||
if (result.status === 'PAID' || result.status === 'CANCELLED' || result.status === 'REFUNDED') {
|
||||
stopPolling()
|
||||
} else if (pollCount.value >= POLL_LIMIT) {
|
||||
stopPolling()
|
||||
}
|
||||
} catch (error) {
|
||||
if (auto) {
|
||||
if (pollCount.value >= POLL_LIMIT) stopPolling()
|
||||
} else {
|
||||
const message = userMessage(error as ApiError)
|
||||
orderError.value = message
|
||||
ElMessage.error(message)
|
||||
}
|
||||
} finally {
|
||||
statusLoading.value = false
|
||||
pollInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
function startPolling(): void {
|
||||
stopPolling()
|
||||
void refreshStatus()
|
||||
pollTimer = window.setInterval(() => {
|
||||
void refreshStatus(true)
|
||||
}, 15000)
|
||||
}
|
||||
|
||||
function manualRefresh(): void {
|
||||
void refreshStatus(false, true)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (appCode.value && ticket.value) {
|
||||
void loadPreview()
|
||||
}
|
||||
remainTimer = window.setInterval(() => {
|
||||
remainTick.value = Date.now()
|
||||
}, 30000)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (remainTimer) {
|
||||
window.clearInterval(remainTimer)
|
||||
remainTimer = 0
|
||||
}
|
||||
stopPolling()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="pay-page">
|
||||
<header class="pay-top">
|
||||
<div class="brand">
|
||||
<span class="logo">F</span>
|
||||
<div>
|
||||
<div class="brand-name">{{ APP_TITLE }} · 中央计费平台</div>
|
||||
<div class="brand-sub">自助收银台</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="top-tags">
|
||||
<el-tag effect="dark" type="warning" round>一次性凭证</el-tag>
|
||||
<el-tag effect="plain" round>内网部署</el-tag>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="pay-main">
|
||||
<div class="card intro">
|
||||
<div class="card-title">收银台</div>
|
||||
<p class="muted small intro-desc">
|
||||
请核对应用与业务用户信息后完成点数充值或 VIP 开通。下单后凭证立即失效,转账请以订单页展示的收款信息为准。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<el-skeleton v-if="previewLoading" class="card" :rows="6" animated />
|
||||
|
||||
<template v-else>
|
||||
<div v-if="!preview && demoMode && !previewError" class="card demo-card">
|
||||
<div class="card-title">
|
||||
<span>演示入口</span>
|
||||
<el-tag size="small" type="info" effect="plain">仅演示环境</el-tag>
|
||||
</div>
|
||||
<p class="muted small demo-desc">
|
||||
演示环境可直接签发一次性凭证;生产环境由业务系统签发 ticket,有效期 5 分钟且只能使用一次。
|
||||
</p>
|
||||
<div class="filter-bar">
|
||||
<el-select v-model="demoAppCode" placeholder="选择应用" style="width: 280px">
|
||||
<el-option
|
||||
v-for="app in DEMO_APPS"
|
||||
:key="app.appCode"
|
||||
:label="`${app.appName}(${app.appCode})`"
|
||||
:value="app.appCode"
|
||||
/>
|
||||
</el-select>
|
||||
<el-button type="primary" :loading="demoLoading" @click="generateDemoTicket">
|
||||
生成演示凭证并继续
|
||||
</el-button>
|
||||
</div>
|
||||
<div v-if="demoError" class="notice danger small demo-notice">{{ demoError }}</div>
|
||||
<div class="notice info small">
|
||||
演示凭证会随机绑定所选应用下的一位业务用户,便于体验充值、VIP 开通与支付状态查询。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="previewError" class="notice danger error-box">
|
||||
<el-icon><CircleClose /></el-icon>
|
||||
<div class="error-body">
|
||||
<div>{{ previewError }}</div>
|
||||
<div class="small error-sub">凭证为一次性使用,请勿刷新页面或重复提交。</div>
|
||||
</div>
|
||||
<div class="spacer" />
|
||||
<el-button v-if="ticketInvalid" type="primary" plain :loading="demoLoading" @click="generateDemoTicket">
|
||||
重新生成演示凭证
|
||||
</el-button>
|
||||
<el-button v-else @click="loadPreview">重试</el-button>
|
||||
</div>
|
||||
|
||||
<el-empty
|
||||
v-if="!preview && !previewError && !demoMode"
|
||||
class="card"
|
||||
description="缺少收银凭证,请从业务系统重新发起"
|
||||
/>
|
||||
|
||||
<template v-if="preview">
|
||||
<div class="card preview-card">
|
||||
<div class="card-title">
|
||||
<span>{{ preview.appName }}</span>
|
||||
<el-tag v-if="preview.vip" type="warning" effect="light">VIP</el-tag>
|
||||
<el-tag v-else type="info" effect="plain">普通用户</el-tag>
|
||||
</div>
|
||||
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="业务用户">{{ preview.usernameSnapshot }}</el-descriptions-item>
|
||||
<el-descriptions-item label="业务用户 ID">
|
||||
<span class="mono">{{ preview.businessUserId }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="当前点数余额">
|
||||
<span class="num money">{{ formatPoints(preview.balance) }}</span> 点
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="兑率">1 元 = {{ preview.pointsPerYuan }} 点</el-descriptions-item>
|
||||
<el-descriptions-item label="VIP 状态">
|
||||
<template v-if="preview.vip">
|
||||
{{ preview.vip.planName }} · 至 {{ formatDateTime(preview.vip.vipUntil) }}
|
||||
<span class="muted small">
|
||||
(免扣权益:{{ preview.vip.freeDeduction === 1 ? '包含' : '不包含' }})
|
||||
</span>
|
||||
</template>
|
||||
<span v-else class="muted">未开通</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="凭证剩余有效期">
|
||||
<el-tag :type="ticketExpired ? 'danger' : 'success'" effect="plain">{{ ticketRemain }}</el-tag>
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div class="small muted ticket-note">
|
||||
凭证已通过校验,仅本次使用有效,凭证内容不在页面中展示;剩余时间每 30 秒刷新。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="ticketExpired" class="notice danger expired-box">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>凭证已过期,无法继续下单,请返回业务系统重新发起。</span>
|
||||
</div>
|
||||
|
||||
<template v-if="!order">
|
||||
<div class="card">
|
||||
<div class="card-title">点数充值</div>
|
||||
<div class="recharge-row">
|
||||
<el-input v-model="amountYuan" class="amount-input" placeholder="输入充值金额" :maxlength="12">
|
||||
<template #append>元</template>
|
||||
</el-input>
|
||||
<el-button
|
||||
v-for="item in QUICK_AMOUNTS"
|
||||
:key="item"
|
||||
size="small"
|
||||
@click="pickAmount(item)"
|
||||
>
|
||||
¥ {{ item }}
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="small muted hint">
|
||||
最低 {{ formatCent(minAmountCent, false) }} 元,最高 50000 元,金额最多两位小数。
|
||||
</div>
|
||||
<div v-if="amountError" class="small amount-error">{{ amountError }}</div>
|
||||
<div class="amount-summary">
|
||||
预计到账
|
||||
<span class="num money">{{ formatPoints(expectedPoints) }}</span> 点
|
||||
<span class="muted small">(按 1 元 = {{ preview.pointsPerYuan }} 点计算,向下取整)</span>
|
||||
</div>
|
||||
<el-button
|
||||
type="primary"
|
||||
size="large"
|
||||
:loading="orderLoading"
|
||||
:disabled="!rechargeCent || Boolean(amountError) || ticketExpired"
|
||||
@click="submitRecharge"
|
||||
>
|
||||
确认充值并生成订单
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">VIP 开通 / 续费</div>
|
||||
<el-table v-if="vipPlans.length" :data="vipPlans" size="small" border>
|
||||
<el-table-column prop="planName" label="档位" min-width="170" />
|
||||
<el-table-column label="时长" width="110">
|
||||
<template #default="{ row }">{{ row.durationDays }} 天</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="价格" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num money">{{ formatCent(row.priceCent) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="免扣权益" width="110" align="center">
|
||||
<template #default="{ row }">{{ row.freeDeduction === 1 ? '包含' : '不包含' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="140" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
type="primary"
|
||||
link
|
||||
:loading="orderLoading"
|
||||
:disabled="ticketExpired"
|
||||
@click="submitVip(row)"
|
||||
>
|
||||
选择并下单
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else description="该应用暂无可用的 VIP 档位" :image-size="80" />
|
||||
<div class="small muted vip-note">
|
||||
VIP 订单金额以档位定价为准,开通后按应用策略享受免扣权益。
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="order" class="card order-card">
|
||||
<div class="card-title">
|
||||
<span>订单已创建</span>
|
||||
<el-tag :type="statusMeta.tag" effect="light">{{ statusMeta.label }}</el-tag>
|
||||
</div>
|
||||
|
||||
<el-result
|
||||
v-if="isPaid"
|
||||
icon="success"
|
||||
title="支付已确认,点数已到账"
|
||||
:sub-title="`订单号 ${order.outTradeNo}`"
|
||||
/>
|
||||
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="订单号">
|
||||
<span class="mono">{{ order.outTradeNo }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="订单类型">{{ ORDER_TYPE_LABEL[order.orderType] }}</el-descriptions-item>
|
||||
<el-descriptions-item label="订单金额">
|
||||
<span class="num money">{{ formatCent(order.amountCent) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="到账点数">
|
||||
<span v-if="order.pointsGained > 0" class="num money">
|
||||
{{ formatPoints(order.pointsGained) }} 点
|
||||
</span>
|
||||
<span v-else class="muted">—</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="有效期至">{{ formatDateTime(order.expiresAt) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="下单时间">{{ formatDateTime(order.createTime) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="支付确认时间">
|
||||
{{ formatDateTime(statusInfo?.paidAt) }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="自动查询进度">{{ pollCount }} / {{ POLL_LIMIT }} 次</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div class="payee">
|
||||
<div class="payee-title">收款账户信息</div>
|
||||
<div class="payee-grid">
|
||||
<div>
|
||||
<div class="muted small">户名</div>
|
||||
<div>{{ order.payee.accountName }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="muted small">开户行</div>
|
||||
<div>{{ order.payee.bankName }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="muted small">账号</div>
|
||||
<div class="mono">{{ order.payee.accountNo }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="small muted payee-note">
|
||||
收款信息仅用于本次转账展示,请勿记录、截图外传;线下转账后由财务确认到账。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="orderError" class="notice danger small order-error">{{ orderError }}</div>
|
||||
|
||||
<div v-if="isClosed" class="notice warn small order-notice">
|
||||
订单已{{ statusMeta.label }},请返回业务系统重新发起。
|
||||
</div>
|
||||
<div v-else-if="pollExhausted" class="notice warn small order-notice">
|
||||
已达到自动查询上限(20 次),可点击「刷新支付状态」手动查询。
|
||||
</div>
|
||||
|
||||
<div class="order-actions">
|
||||
<el-button
|
||||
:loading="statusLoading"
|
||||
:disabled="isPaid || isClosed"
|
||||
@click="manualRefresh"
|
||||
>
|
||||
<el-icon><Refresh /></el-icon>
|
||||
刷新支付状态
|
||||
</el-button>
|
||||
<a v-if="payRedirectUri" :href="payRedirectUri" target="_self" class="back-link">
|
||||
<el-button type="primary" plain>返回业务系统</el-button>
|
||||
</a>
|
||||
</div>
|
||||
<div v-if="payRedirectUri" class="small muted redirect-note">
|
||||
跳转地址由业务系统下单时下发,并经过域名格式校验;不合法或非域名的地址不会展示。
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="notice info security-note">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<div>
|
||||
<div>本页不收集银行卡号、支付密码与短信验证码;ticket 为一次性凭证,只能使用一次。</div>
|
||||
<div>凭证仅在进入本页时从业务系统携带的链接读取,不写入浏览器本地存储;请勿转发当前页面链接。</div>
|
||||
<div>返回业务系统的跳转地址会做域名格式校验,非合法域名不会渲染为可点击链接。</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.pay-page {
|
||||
min-height: 100vh;
|
||||
background: var(--fin-bg);
|
||||
}
|
||||
|
||||
.pay-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 18px 28px;
|
||||
background: radial-gradient(circle at 15% 0, #1b2b4a 0, #0d1728 60%, #0a1220 100%);
|
||||
color: #e6edf9;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 19px;
|
||||
font-weight: 800;
|
||||
color: #101828;
|
||||
background: linear-gradient(135deg, #c8a45c, #a8813c);
|
||||
}
|
||||
|
||||
.brand-name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.brand-sub {
|
||||
margin-top: 2px;
|
||||
font-size: 11px;
|
||||
letter-spacing: 2px;
|
||||
color: var(--fin-sidebar-text);
|
||||
}
|
||||
|
||||
.top-tags {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.pay-main {
|
||||
width: 100%;
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
padding: 22px 16px 44px;
|
||||
}
|
||||
|
||||
.intro-desc {
|
||||
margin: 0;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.demo-desc {
|
||||
margin: 0 0 14px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.demo-notice {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.error-box {
|
||||
margin-top: 16px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.error-body {
|
||||
flex: 1;
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
.error-box .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.error-sub {
|
||||
margin-top: 4px;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.ticket-note {
|
||||
margin-top: 10px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.expired-box {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.recharge-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.amount-input {
|
||||
width: 230px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.amount-error {
|
||||
margin-top: 6px;
|
||||
color: var(--el-color-danger);
|
||||
}
|
||||
|
||||
.amount-summary {
|
||||
margin: 14px 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.vip-note {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.payee {
|
||||
margin-top: 16px;
|
||||
padding: 14px 16px;
|
||||
border: 1px dashed var(--fin-border-strong);
|
||||
border-radius: 8px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.payee-title {
|
||||
margin-bottom: 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.payee-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 10px 16px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.payee-note {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.order-error,
|
||||
.order-notice {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.order-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.back-link {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.redirect-note {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.security-note {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.pay-top {
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.pay-main {
|
||||
padding: 16px 12px 32px;
|
||||
}
|
||||
|
||||
.payee-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,441 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { pricingApi } from '@/api/settings'
|
||||
import type { AppPolicy, PricingItem } from '@/types'
|
||||
import { formatCent, formatPoints, parsePositiveInt } from '@/utils/money'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { askTotp, confirmAction } from '@/utils/confirm'
|
||||
import { userMessage } from '@/utils/http'
|
||||
import type { ApiError } from '@/utils/http'
|
||||
|
||||
interface RateForm {
|
||||
appCode: string
|
||||
appName: string
|
||||
pointsPerYuan: string
|
||||
enabled: number
|
||||
}
|
||||
|
||||
interface PolicyForm {
|
||||
appCode: string
|
||||
appName: string
|
||||
minCost: string
|
||||
maxPointsPerCharge: string
|
||||
vipExempt: number
|
||||
failedStrategy: 'none' | 'actual'
|
||||
thresholdYuan: string
|
||||
}
|
||||
|
||||
const pricing = ref<PricingItem[]>([])
|
||||
const policies = ref<AppPolicy[]>([])
|
||||
const loading = ref(false)
|
||||
|
||||
const rateDialogVisible = ref(false)
|
||||
const rateSubmitting = ref(false)
|
||||
const rateFormRef = ref<FormInstance>()
|
||||
const rateForm = reactive<RateForm>({
|
||||
appCode: '',
|
||||
appName: '',
|
||||
pointsPerYuan: '',
|
||||
enabled: 1,
|
||||
})
|
||||
|
||||
const policyDialogVisible = ref(false)
|
||||
const policySubmitting = ref(false)
|
||||
const policyFormRef = ref<FormInstance>()
|
||||
const policyForm = reactive<PolicyForm>({
|
||||
appCode: '',
|
||||
appName: '',
|
||||
minCost: '0',
|
||||
maxPointsPerCharge: '1',
|
||||
vipExempt: 0,
|
||||
failedStrategy: 'none',
|
||||
thresholdYuan: '0.00',
|
||||
})
|
||||
|
||||
const FAILED_STRATEGY_LABEL: Record<AppPolicy['failedStrategy'], string> = {
|
||||
none: '不扣费',
|
||||
actual: '按实际扣费',
|
||||
}
|
||||
|
||||
/** 非负整数点数(保底消费允许 0) */
|
||||
function parseNonNegativeInt(input: unknown): number | null {
|
||||
const text = String(input ?? '').trim()
|
||||
if (!/^\d{1,9}$/.test(text)) return null
|
||||
const value = Number(text)
|
||||
return Number.isInteger(value) && value >= 0 ? value : null
|
||||
}
|
||||
|
||||
/** 阈值按「元」输入转分,允许 0(0 元表示阈值为 0 分) */
|
||||
function parseThresholdCent(input: unknown): number | null {
|
||||
const text = String(input ?? '').trim()
|
||||
if (!/^\d{1,9}(\.\d{1,2})?$/.test(text)) return null
|
||||
const cent = Math.round(Number(text) * 100)
|
||||
return Number.isInteger(cent) && cent >= 0 ? cent : null
|
||||
}
|
||||
|
||||
function validateRate(_rule: unknown, value: unknown, callback: (error?: string | Error) => void): void {
|
||||
if (parsePositiveInt(value) === null) {
|
||||
callback(new Error('兑率必须为正整数(1 元可兑换的点数)'))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
}
|
||||
|
||||
function validateMinCost(_rule: unknown, value: unknown, callback: (error?: string | Error) => void): void {
|
||||
if (parseNonNegativeInt(value) === null) {
|
||||
callback(new Error('保底消费必须为不小于 0 的整数点数'))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
}
|
||||
|
||||
function validateMaxPoints(_rule: unknown, value: unknown, callback: (error?: string | Error) => void): void {
|
||||
const maxPoints = parsePositiveInt(value)
|
||||
if (maxPoints === null) {
|
||||
callback(new Error('单次扣费上限必须为正整数点数'))
|
||||
return
|
||||
}
|
||||
const minCost = parseNonNegativeInt(policyForm.minCost) ?? 0
|
||||
if (maxPoints < Math.max(1, minCost)) {
|
||||
callback(new Error('单次扣费上限不得小于保底消费'))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
}
|
||||
|
||||
function validateThreshold(_rule: unknown, value: unknown, callback: (error?: string | Error) => void): void {
|
||||
if (parseThresholdCent(value) === null) {
|
||||
callback(new Error('请输入正确的阈值金额(元,最多两位小数,且不小于 0)'))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
}
|
||||
|
||||
const rateRules: FormRules = {
|
||||
pointsPerYuan: [{ validator: validateRate, trigger: 'blur' }],
|
||||
}
|
||||
|
||||
const policyRules: FormRules = {
|
||||
minCost: [{ validator: validateMinCost, trigger: 'blur' }],
|
||||
maxPointsPerCharge: [{ validator: validateMaxPoints, trigger: 'blur' }],
|
||||
thresholdYuan: [{ validator: validateThreshold, trigger: 'blur' }],
|
||||
}
|
||||
|
||||
async function loadData(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const [rateList, policyList] = await Promise.all([pricingApi.list(), pricingApi.policies()])
|
||||
pricing.value = rateList
|
||||
policies.value = policyList
|
||||
} catch {
|
||||
pricing.value = []
|
||||
policies.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openRate(row: PricingItem): void {
|
||||
Object.assign(rateForm, {
|
||||
appCode: row.appCode,
|
||||
appName: row.appName,
|
||||
pointsPerYuan: String(row.pointsPerYuan),
|
||||
enabled: row.enabled,
|
||||
})
|
||||
rateDialogVisible.value = true
|
||||
void nextTick(() => rateFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
async function submitRate(): Promise<void> {
|
||||
const formEl = rateFormRef.value
|
||||
if (!formEl) return
|
||||
let valid = false
|
||||
try {
|
||||
valid = await formEl.validate()
|
||||
} catch {
|
||||
valid = false
|
||||
}
|
||||
if (!valid) return
|
||||
|
||||
const pointsPerYuan = parsePositiveInt(rateForm.pointsPerYuan)
|
||||
if (pointsPerYuan === null) {
|
||||
ElMessage.error('兑率必须为正整数')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '确认修改兑率',
|
||||
message: `将应用「${rateForm.appName}」的兑率修改为 1 元 = ${formatPoints(
|
||||
pointsPerYuan,
|
||||
)} 点,变更需二次验证并写入审计日志,确认继续?`,
|
||||
requireType: '确认修改兑率',
|
||||
confirmText: '确认修改兑率',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('修改兑率')
|
||||
if (!totp) return
|
||||
|
||||
rateSubmitting.value = true
|
||||
try {
|
||||
await pricingApi.save(rateForm.appCode, {
|
||||
pointsPerYuan,
|
||||
enabled: rateForm.enabled,
|
||||
totp,
|
||||
})
|
||||
ElMessage.success('兑率已更新')
|
||||
rateDialogVisible.value = false
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
rateSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openPolicy(row: AppPolicy): void {
|
||||
Object.assign(policyForm, {
|
||||
appCode: row.appCode,
|
||||
appName: row.appName,
|
||||
minCost: String(row.minCost),
|
||||
maxPointsPerCharge: String(row.maxPointsPerCharge),
|
||||
vipExempt: row.vipExempt,
|
||||
failedStrategy: row.failedStrategy,
|
||||
thresholdYuan: (row.dualControlThresholdCent / 100).toFixed(2),
|
||||
})
|
||||
policyDialogVisible.value = true
|
||||
void nextTick(() => policyFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
async function submitPolicy(): Promise<void> {
|
||||
const formEl = policyFormRef.value
|
||||
if (!formEl) return
|
||||
let valid = false
|
||||
try {
|
||||
valid = await formEl.validate()
|
||||
} catch {
|
||||
valid = false
|
||||
}
|
||||
if (!valid) return
|
||||
|
||||
const minCost = parseNonNegativeInt(policyForm.minCost)
|
||||
const maxPointsPerCharge = parsePositiveInt(policyForm.maxPointsPerCharge)
|
||||
const dualControlThresholdCent = parseThresholdCent(policyForm.thresholdYuan)
|
||||
if (minCost === null || maxPointsPerCharge === null || dualControlThresholdCent === null) {
|
||||
ElMessage.error('请检查扣费策略数值输入')
|
||||
return
|
||||
}
|
||||
if (maxPointsPerCharge < Math.max(1, minCost)) {
|
||||
ElMessage.error('单次扣费上限不得小于保底消费')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '确认修改策略',
|
||||
message: `将应用「${policyForm.appName}」的扣费策略变更为:保底 ${formatPoints(
|
||||
minCost,
|
||||
)} 点、单次上限 ${formatPoints(maxPointsPerCharge)} 点、VIP 免扣 ${
|
||||
policyForm.vipExempt === 1 ? '开启' : '关闭'
|
||||
}、失败策略「${FAILED_STRATEGY_LABEL[policyForm.failedStrategy]}」、双人复核阈值 ${formatCent(
|
||||
dualControlThresholdCent,
|
||||
)},确认继续?`,
|
||||
requireType: '确认修改策略',
|
||||
confirmText: '确认修改策略',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('修改扣费策略')
|
||||
if (!totp) return
|
||||
|
||||
policySubmitting.value = true
|
||||
try {
|
||||
await pricingApi.savePolicy(policyForm.appCode, {
|
||||
minCost,
|
||||
maxPointsPerCharge,
|
||||
vipExempt: policyForm.vipExempt,
|
||||
failedStrategy: policyForm.failedStrategy,
|
||||
dualControlThresholdCent,
|
||||
totp,
|
||||
})
|
||||
ElMessage.success('扣费策略已更新')
|
||||
policyDialogVisible.value = false
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
policySubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadData()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader
|
||||
title="兑率与扣费策略"
|
||||
desc="按应用维护点数兑率与扣费策略;所有变更必须通过 TOTP 二次验证并写入审计日志。"
|
||||
/>
|
||||
|
||||
<div class="notice warn" style="margin-bottom: 16px">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<div>
|
||||
兑率与扣费策略变更属于资金敏感操作,必须 TOTP 二次验证并留痕审计。双人复核阈值同时作用于充值到账确认与退款审核,
|
||||
调整前请与财务复核流程对齐,避免出现单人即可完成大额资金操作的缺口。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">
|
||||
<span>① 兑率配置</span>
|
||||
<span class="small muted">1 元可兑换的点数,充值入账与退款扣回均按此兑率计算</span>
|
||||
</div>
|
||||
<el-table v-loading="loading" :data="pricing" border empty-text="暂无兑率配置">
|
||||
<el-table-column prop="appName" label="应用" min-width="140" />
|
||||
<el-table-column label="1 元可兑换点数" min-width="150" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ formatPoints(row.pointsPerYuan) }} 点</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="启用状态" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.enabled === 1 ? 'success' : 'info'" effect="plain">
|
||||
{{ row.enabled === 1 ? '启用' : '停用' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="更新时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.updateTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button v-perm="'fin:pricing:edit'" link type="primary" @click="openRate(row)">
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">
|
||||
<span>② 扣费策略</span>
|
||||
<span class="small muted">保底消费、单次上限与失败扣费口径共同决定扣费结果</span>
|
||||
</div>
|
||||
<el-table v-loading="loading" :data="policies" border empty-text="暂无扣费策略">
|
||||
<el-table-column prop="appName" label="应用" min-width="140" />
|
||||
<el-table-column label="保底消费(点)" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ formatPoints(row.minCost) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="单次扣费上限(点)" width="160" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ formatPoints(row.maxPointsPerCharge) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="VIP 免扣" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.vipExempt === 1 ? 'success' : 'info'" effect="plain">
|
||||
{{ row.vipExempt === 1 ? '免扣' : '关闭' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="失败扣费策略" width="130" align="center">
|
||||
<template #default="{ row }">
|
||||
{{ FAILED_STRATEGY_LABEL[row.failedStrategy as AppPolicy['failedStrategy']] }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="双人复核阈值" width="150" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="money">{{ formatCent(row.dualControlThresholdCent) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="更新时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.updateTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button v-perm="'fin:pricing:edit'" link type="primary" @click="openPolicy(row)">
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<el-dialog
|
||||
v-model="rateDialogVisible"
|
||||
title="修改兑率"
|
||||
width="520px"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-form ref="rateFormRef" :model="rateForm" :rules="rateRules" label-width="130px">
|
||||
<el-form-item label="应用">
|
||||
<span>{{ rateForm.appName }}({{ rateForm.appCode }})</span>
|
||||
</el-form-item>
|
||||
<el-form-item label="兑率" prop="pointsPerYuan">
|
||||
<el-input v-model="rateForm.pointsPerYuan" placeholder="请输入正整数点数">
|
||||
<template #append>点 / 元</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="启用状态">
|
||||
<el-switch v-model="rateForm.enabled" :active-value="1" :inactive-value="0" />
|
||||
<span class="small muted" style="margin-left: 10px">停用后该应用充值兑率不生效</span>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="rateDialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="rateSubmitting" @click="submitRate">
|
||||
保存
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
v-model="policyDialogVisible"
|
||||
title="修改扣费策略"
|
||||
width="560px"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-form ref="policyFormRef" :model="policyForm" :rules="policyRules" label-width="150px">
|
||||
<el-form-item label="应用">
|
||||
<span>{{ policyForm.appName }}({{ policyForm.appCode }})</span>
|
||||
</el-form-item>
|
||||
<el-form-item label="保底消费(点)" prop="minCost">
|
||||
<el-input v-model="policyForm.minCost" placeholder="不小于 0 的整数" />
|
||||
</el-form-item>
|
||||
<el-form-item label="单次扣费上限(点)" prop="maxPointsPerCharge">
|
||||
<el-input v-model="policyForm.maxPointsPerCharge" placeholder="正整数,且不小于保底消费" />
|
||||
</el-form-item>
|
||||
<el-form-item label="VIP 免扣">
|
||||
<el-switch v-model="policyForm.vipExempt" :active-value="1" :inactive-value="0" />
|
||||
<span class="small muted" style="margin-left: 10px">
|
||||
需与「VIP 档位」中的免扣费档位同时开启才生效
|
||||
</span>
|
||||
</el-form-item>
|
||||
<el-form-item label="失败扣费策略">
|
||||
<el-radio-group v-model="policyForm.failedStrategy">
|
||||
<el-radio value="none">不扣费</el-radio>
|
||||
<el-radio value="actual">按实际扣费</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="双人复核阈值(元)" prop="thresholdYuan">
|
||||
<el-input v-model="policyForm.thresholdYuan" placeholder="如 500.00,可为 0">
|
||||
<template #append>元</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="policyDialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="policySubmitting" @click="submitPolicy">
|
||||
保存
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,350 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { appApi } from '@/api/core'
|
||||
import { reconcileApi } from '@/api/settings'
|
||||
import { PERM } from '@/constants'
|
||||
import type { AppInfo, ReconcileDiff, ReconcileReport } from '@/types'
|
||||
import { formatCent, formatPoints } from '@/utils/money'
|
||||
import { defaultRange, formatDateTime } from '@/utils/format'
|
||||
|
||||
const LEVEL_LABEL: Record<ReconcileDiff['level'], string> = {
|
||||
ORDER: '订单级',
|
||||
SUBJECT: '账户级',
|
||||
APP: '应用级',
|
||||
}
|
||||
|
||||
const apps = ref<AppInfo[]>([])
|
||||
const reports = ref<ReconcileReport[]>([])
|
||||
const loading = ref(false)
|
||||
const running = ref(false)
|
||||
|
||||
const runAppCode = ref('')
|
||||
const range = ref<[string, string] | null>(defaultRange(7))
|
||||
|
||||
const drawerVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<ReconcileReport | null>(null)
|
||||
|
||||
const cashInGap = computed(() =>
|
||||
detail.value ? detail.value.cashInCent - detail.value.cashPaidOrderCent : 0,
|
||||
)
|
||||
const cashOutGap = computed(() =>
|
||||
detail.value ? detail.value.cashOutCent - detail.value.cashRefundedCent : 0,
|
||||
)
|
||||
|
||||
function diffTone(value: number): string {
|
||||
return value === 0 ? 'money-in' : 'money-out'
|
||||
}
|
||||
|
||||
/** 差异明细单位:订单级为金额(分→元),账户级 / 应用级为点数 */
|
||||
function formatDetailValue(level: ReconcileDiff['level'], value: number): string {
|
||||
return level === 'ORDER' ? formatCent(value) : formatPoints(value)
|
||||
}
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
try {
|
||||
apps.value = await appApi.list()
|
||||
if (!runAppCode.value && apps.value.length > 0) {
|
||||
const firstEnabled = apps.value.find(item => item.enabled === 1) ?? apps.value[0]
|
||||
runAppCode.value = firstEnabled.appCode
|
||||
}
|
||||
} catch {
|
||||
apps.value = []
|
||||
}
|
||||
}
|
||||
|
||||
async function loadReports(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
reports.value = await reconcileApi.reports()
|
||||
} catch {
|
||||
reports.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function runReconcile(): Promise<void> {
|
||||
if (!runAppCode.value) {
|
||||
ElMessage.warning('请选择接入应用')
|
||||
return
|
||||
}
|
||||
if (!range.value || range.value.length !== 2) {
|
||||
ElMessage.warning('请选择对账日期范围')
|
||||
return
|
||||
}
|
||||
const [windowStart, windowEnd] = range.value
|
||||
|
||||
running.value = true
|
||||
try {
|
||||
const report = await reconcileApi.run({ appCode: runAppCode.value, windowStart, windowEnd })
|
||||
ElMessage.success(
|
||||
report.status === 'BALANCED'
|
||||
? `对账完成:${report.id} 账实相符`
|
||||
: `对账完成:${report.id} 存在差异,请人工核对`,
|
||||
)
|
||||
await loadReports()
|
||||
await viewReport(report.id)
|
||||
} catch {
|
||||
// 非静默接口,错误提示由 http 层统一处理
|
||||
} finally {
|
||||
running.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function viewReport(id: string): Promise<void> {
|
||||
drawerVisible.value = true
|
||||
detail.value = null
|
||||
detailLoading.value = true
|
||||
try {
|
||||
detail.value = await reconcileApi.detail(id)
|
||||
} catch {
|
||||
drawerVisible.value = false
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadApps()
|
||||
await loadReports()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader
|
||||
title="对账中心"
|
||||
desc="按应用与时间窗口执行现金侧、点数侧对账,差异需人工核对并留存处理记录。"
|
||||
/>
|
||||
|
||||
<div class="notice info" style="margin-bottom: 16px">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<div>
|
||||
现金侧与点数侧需分开核对:现金侧比对资金流水与订单/退款,点数侧比对钱包余额与流水累计。对账只负责发现差异,
|
||||
不会自动修复;确认差异后必须人工处理并在审计日志中留存处理记录。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">运行对账</div>
|
||||
<div class="filter-bar">
|
||||
<el-select v-model="runAppCode" placeholder="请选择接入应用" style="width: 200px">
|
||||
<el-option
|
||||
v-for="app in apps"
|
||||
:key="app.appCode"
|
||||
:label="`${app.appName}(${app.appCode})`"
|
||||
:value="app.appCode"
|
||||
/>
|
||||
</el-select>
|
||||
<el-date-picker
|
||||
v-model="range"
|
||||
type="daterange"
|
||||
value-format="YYYY-MM-DD"
|
||||
range-separator="至"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
:unlink-panels="true"
|
||||
style="width: 280px"
|
||||
/>
|
||||
<el-button v-perm="PERM.reconcileRun" type="primary" :loading="running" @click="runReconcile">
|
||||
<el-icon><DocumentChecked /></el-icon>
|
||||
执行对账
|
||||
</el-button>
|
||||
<span class="small muted">默认统计近 7 天,窗口按自然日闭区间计算</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">
|
||||
<span>对账报告</span>
|
||||
<span class="small muted">共 {{ reports.length }} 份报告</span>
|
||||
</div>
|
||||
<el-table v-loading="loading" :data="reports" border empty-text="暂无对账报告">
|
||||
<el-table-column label="报告 ID" width="160">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.id }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="appName" label="应用" min-width="130" />
|
||||
<el-table-column label="窗口" width="200">
|
||||
<template #default="{ row }">{{ row.windowStart }} 至 {{ row.windowEnd }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="快照时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.snapshotAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="现金侧差异" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="money" :class="diffTone(row.cashDiffCent)">
|
||||
{{ formatCent(row.cashDiffCent) }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="点数侧差异" width="120" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="money" :class="diffTone(row.pointsDiff)">
|
||||
{{ formatPoints(row.pointsDiff) }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="断链数" width="90" align="right">
|
||||
<template #default="{ row }">
|
||||
<span :class="row.brokenChains > 0 ? 'money-out' : ''">{{ row.brokenChains }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="差异条数" width="100" align="right">
|
||||
<template #default="{ row }">
|
||||
<span :class="row.diffCount > 0 ? 'money-out' : ''">{{ row.diffCount }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="100" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.status === 'BALANCED' ? 'success' : 'danger'" effect="plain">
|
||||
{{ row.status }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="createdBy" label="创建人" width="110" />
|
||||
<el-table-column label="创建时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="80" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="viewReport(row.id)">查看</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<el-drawer v-model="drawerVisible" title="对账报告详情" size="880px">
|
||||
<div v-loading="detailLoading">
|
||||
<template v-if="detail">
|
||||
<div v-if="detail.status === 'DIFF'" class="notice danger" style="margin-bottom: 16px">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<div>
|
||||
存在差异,需人工核对并留存处理记录。系统不会自动修复差异,核对完成后请在审计日志中留存处理说明。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-section">
|
||||
<div class="card-title">报告概览</div>
|
||||
<el-descriptions :column="2" border size="small">
|
||||
<el-descriptions-item label="报告 ID">
|
||||
<span class="mono">{{ detail.id }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="应用">
|
||||
{{ detail.appName }}({{ detail.appCode }})
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="对账窗口">
|
||||
{{ detail.windowStart }} 至 {{ detail.windowEnd }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="快照时间">
|
||||
{{ formatDateTime(detail.snapshotAt) }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="状态">
|
||||
<el-tag :type="detail.status === 'BALANCED' ? 'success' : 'danger'" effect="plain">
|
||||
{{ detail.status }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="创建人">{{ detail.createdBy }}</el-descriptions-item>
|
||||
<el-descriptions-item label="断链账户数">{{ detail.brokenChains }}</el-descriptions-item>
|
||||
<el-descriptions-item label="差异条数">{{ detail.diffCount }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</div>
|
||||
|
||||
<div class="detail-section">
|
||||
<div class="card-title">现金侧核对</div>
|
||||
<el-descriptions :column="2" border size="small">
|
||||
<el-descriptions-item label="现金流入合计">
|
||||
<span class="money">{{ formatCent(detail.cashInCent) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="已支付订单金额">
|
||||
<span class="money">{{ formatCent(detail.cashPaidOrderCent) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="流入差额">
|
||||
<span class="money" :class="diffTone(cashInGap)">{{ formatCent(cashInGap) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="现金流出合计">
|
||||
<span class="money">{{ formatCent(detail.cashOutCent) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="已完成退款金额">
|
||||
<span class="money">{{ formatCent(detail.cashRefundedCent) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="流出差额">
|
||||
<span class="money" :class="diffTone(cashOutGap)">{{ formatCent(cashOutGap) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="现金侧差异">
|
||||
<span class="money" :class="diffTone(detail.cashDiffCent)">
|
||||
{{ formatCent(detail.cashDiffCent) }}
|
||||
</span>
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</div>
|
||||
|
||||
<div class="detail-section">
|
||||
<div class="card-title">点数侧核对</div>
|
||||
<el-descriptions :column="2" border size="small">
|
||||
<el-descriptions-item label="钱包余额合计">
|
||||
<span class="num">{{ formatPoints(detail.walletSum) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="流水累计应得">
|
||||
<span class="num">{{ formatPoints(detail.computedSum) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="点数侧差异">
|
||||
<span class="num" :class="diffTone(detail.pointsDiff)">{{ formatPoints(detail.pointsDiff) }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="断链账户数">{{ detail.brokenChains }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</div>
|
||||
|
||||
<div class="detail-section">
|
||||
<div class="card-title">差异明细</div>
|
||||
<el-table :data="detail.details" border size="small" empty-text="无差异明细">
|
||||
<el-table-column label="层级" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" :type="row.level === 'APP' ? 'warning' : 'info'">
|
||||
{{ LEVEL_LABEL[row.level as ReconcileDiff['level']] }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="对象" min-width="120">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.target }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="期望值" width="140" align="right">
|
||||
<template #default="{ row }">
|
||||
{{ formatDetailValue(row.level as ReconcileDiff['level'], row.expected) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="实际值" width="140" align="right">
|
||||
<template #default="{ row }">
|
||||
{{ formatDetailValue(row.level as ReconcileDiff['level'], row.actual) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="差异" width="140" align="right">
|
||||
<template #default="{ row }">
|
||||
<span :class="diffTone(row.diff)">
|
||||
{{ formatDetailValue(row.level as ReconcileDiff['level'], row.diff) }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="reason" label="原因说明" min-width="240" show-overflow-tooltip />
|
||||
</el-table>
|
||||
<p class="small muted" style="margin: 10px 0 0">
|
||||
单位说明:订单级为金额(分→元展示),账户级 / 应用级为点数;差异 = 实际值 − 期望值。
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.detail-section + .detail-section {
|
||||
margin-top: 18px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,601 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import {
|
||||
appApi,
|
||||
orderApi,
|
||||
refundApi,
|
||||
type RefundCreatePayload,
|
||||
type RefundQuery,
|
||||
type RefundReviewPayload,
|
||||
} from '@/api/core'
|
||||
import { REFUND_STATUS } from '@/constants'
|
||||
import { formatCent, formatPoints, yuanInputToCent } from '@/utils/money'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { askTotp, confirmAction } from '@/utils/confirm'
|
||||
import { userMessage, type ApiError } from '@/utils/http'
|
||||
import { maskVoucher } from '@/utils/mask'
|
||||
import { newIdempotencyKey } from '@/utils/validate'
|
||||
import type { AppInfo, OrderInfo, RefundInfo, RefundStatus } from '@/types'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
|
||||
interface RefundFilters {
|
||||
appCode: string
|
||||
status: string
|
||||
keyword: string
|
||||
from: string
|
||||
to: string
|
||||
}
|
||||
|
||||
const REFUND_STATUS_OPTIONS = (Object.keys(REFUND_STATUS) as RefundStatus[]).map(value => ({
|
||||
value,
|
||||
label: REFUND_STATUS[value].label,
|
||||
}))
|
||||
|
||||
/** 表格插槽中的 row 为 any,统一用带类型的映射函数取展示文案,避免隐式 any 索引 */
|
||||
function refundStatusMeta(status: RefundStatus) {
|
||||
return REFUND_STATUS[status]
|
||||
}
|
||||
|
||||
const route = useRoute()
|
||||
const store = useUserStore()
|
||||
|
||||
function queryText(value: unknown): string {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
const STATUS_VALUES = REFUND_STATUS_OPTIONS.map(item => item.value as string)
|
||||
const initStatus = queryText(route.query.status)
|
||||
|
||||
const filters = reactive<RefundFilters>({
|
||||
appCode: queryText(route.query.appCode),
|
||||
status: STATUS_VALUES.includes(initStatus) ? initStatus : '',
|
||||
keyword: '',
|
||||
from: '',
|
||||
to: '',
|
||||
})
|
||||
|
||||
const appOptions = ref<AppInfo[]>([])
|
||||
const rows = ref<RefundInfo[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const loading = ref(false)
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
try {
|
||||
appOptions.value = await appApi.list()
|
||||
} catch {
|
||||
appOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
function buildFilter(): RefundQuery {
|
||||
const query: RefundQuery = {}
|
||||
if (filters.appCode) query.appCode = filters.appCode
|
||||
if (filters.status) query.status = filters.status
|
||||
const keyword = filters.keyword.trim()
|
||||
if (keyword) query.keyword = keyword
|
||||
if (filters.from) query.from = filters.from
|
||||
if (filters.to) query.to = filters.to
|
||||
return query
|
||||
}
|
||||
|
||||
async function loadRefunds(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await refundApi.list({ ...buildFilter(), page: page.value, pageSize: pageSize.value })
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch {
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSearch(): void {
|
||||
if (filters.from && filters.to && filters.from > filters.to) {
|
||||
ElMessage.warning('开始日期不能晚于结束日期')
|
||||
return
|
||||
}
|
||||
page.value = 1
|
||||
void loadRefunds()
|
||||
}
|
||||
|
||||
function handleReset(): void {
|
||||
filters.appCode = ''
|
||||
filters.status = ''
|
||||
filters.keyword = ''
|
||||
filters.from = ''
|
||||
filters.to = ''
|
||||
page.value = 1
|
||||
void loadRefunds()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void Promise.all([loadApps(), loadRefunds()])
|
||||
})
|
||||
|
||||
/* ----------------------------- 发起退款 ----------------------------- */
|
||||
|
||||
const orderOptions = ref<OrderInfo[]>([])
|
||||
const orderLoading = ref(false)
|
||||
|
||||
const createVisible = ref(false)
|
||||
const createSubmitting = ref(false)
|
||||
const createForm = reactive({
|
||||
orderId: undefined as number | undefined,
|
||||
amountYuan: '',
|
||||
reason: '',
|
||||
voucherNo: '',
|
||||
idempotencyKey: '',
|
||||
})
|
||||
|
||||
const selectedOrder = computed(() => orderOptions.value.find(item => item.id === createForm.orderId) || null)
|
||||
|
||||
const maxRefundableCent = computed(() => {
|
||||
if (!selectedOrder.value) return 0
|
||||
return Math.max(0, selectedOrder.value.amountCent - selectedOrder.value.refundedAmountCent)
|
||||
})
|
||||
|
||||
function orderOptionLabel(order: OrderInfo): string {
|
||||
return `${order.outTradeNo} / ${formatCent(order.amountCent)} / ${order.usernameSnapshot}`
|
||||
}
|
||||
|
||||
async function searchOrders(keyword: string): Promise<void> {
|
||||
orderLoading.value = true
|
||||
try {
|
||||
const result = await orderApi.list({
|
||||
status: 'PAID',
|
||||
appCode: filters.appCode || undefined,
|
||||
pageSize: 100,
|
||||
keyword: keyword.trim() || undefined,
|
||||
})
|
||||
orderOptions.value = result.records
|
||||
// 可退订单较多时一次只能加载 100 条,必须提示用户改用订单号精确搜索,避免选错订单
|
||||
if (result.total > result.records.length) {
|
||||
ElMessage.warning(`可退订单共 ${result.total} 条,列表仅展示最近 100 条,请用订单号精确搜索`)
|
||||
}
|
||||
} catch {
|
||||
orderOptions.value = []
|
||||
} finally {
|
||||
orderLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function openCreate(): Promise<void> {
|
||||
createForm.orderId = undefined
|
||||
createForm.amountYuan = ''
|
||||
createForm.reason = ''
|
||||
createForm.voucherNo = ''
|
||||
createForm.idempotencyKey = newIdempotencyKey('refund')
|
||||
createVisible.value = true
|
||||
await searchOrders('')
|
||||
}
|
||||
|
||||
async function submitCreate(): Promise<void> {
|
||||
const order = selectedOrder.value
|
||||
if (!order) {
|
||||
ElMessage.warning('请选择需要退款的已到账订单')
|
||||
return
|
||||
}
|
||||
const amountCent = yuanInputToCent(createForm.amountYuan)
|
||||
if (amountCent === null) {
|
||||
ElMessage.warning('请输入正确的退款金额(元,最多两位小数且大于 0)')
|
||||
return
|
||||
}
|
||||
if (amountCent > maxRefundableCent.value) {
|
||||
ElMessage.warning(`退款金额不得超过可退上限 ${formatCent(maxRefundableCent.value)}`)
|
||||
return
|
||||
}
|
||||
const reason = createForm.reason.trim()
|
||||
if (reason.length < 5) {
|
||||
ElMessage.warning('请填写退款原因(不少于 5 个字)')
|
||||
return
|
||||
}
|
||||
const voucherNo = createForm.voucherNo.trim()
|
||||
if (voucherNo && voucherNo.length < 6) {
|
||||
ElMessage.warning('凭证号不少于 6 位,或留空待复核时补登')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '发起退款',
|
||||
message: `订单 ${order.outTradeNo} 退款 ${formatCent(amountCent)},将扣回用户点数并写入现金退款流水,是否继续?`,
|
||||
confirmText: '确认退款',
|
||||
requireType: '确认退款',
|
||||
type: 'warning',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('发起退款')
|
||||
if (!totp) return
|
||||
|
||||
const payload: RefundCreatePayload = {
|
||||
orderId: order.id,
|
||||
amountCent,
|
||||
reason,
|
||||
idempotencyKey: createForm.idempotencyKey,
|
||||
totp,
|
||||
}
|
||||
if (voucherNo) payload.voucherNo = voucherNo
|
||||
|
||||
createSubmitting.value = true
|
||||
try {
|
||||
const created = await refundApi.create(payload)
|
||||
if (created.status === 'PENDING') {
|
||||
ElMessage.warning('已提交,需另一名管理员复核')
|
||||
} else {
|
||||
ElMessage.success(`退款已完成,共扣回 ${formatPoints(created.pointsDeducted)} 点`)
|
||||
}
|
||||
createVisible.value = false
|
||||
await loadRefunds()
|
||||
} catch (err) {
|
||||
ElMessage.error(userMessage(err as ApiError))
|
||||
} finally {
|
||||
createSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- 退款复核 ----------------------------- */
|
||||
|
||||
const reviewVisible = ref(false)
|
||||
const reviewSubmitting = ref(false)
|
||||
const reviewTarget = ref<RefundInfo | null>(null)
|
||||
const reviewForm = reactive({
|
||||
action: 'approve' as 'approve' | 'reject',
|
||||
voucherNo: '',
|
||||
reason: '',
|
||||
})
|
||||
|
||||
function isSelfRefund(row: RefundInfo): boolean {
|
||||
return store.admin?.id === row.operatorAdminId
|
||||
}
|
||||
|
||||
function openReview(row: RefundInfo): void {
|
||||
if (isSelfRefund(row)) {
|
||||
ElMessage.warning('发起人不得复核')
|
||||
return
|
||||
}
|
||||
reviewTarget.value = row
|
||||
reviewForm.action = 'approve'
|
||||
reviewForm.voucherNo = ''
|
||||
reviewForm.reason = ''
|
||||
reviewVisible.value = true
|
||||
}
|
||||
|
||||
async function submitReview(): Promise<void> {
|
||||
const refund = reviewTarget.value
|
||||
if (!refund) return
|
||||
const approving = reviewForm.action === 'approve'
|
||||
const voucherNo = reviewForm.voucherNo.trim()
|
||||
const reason = reviewForm.reason.trim()
|
||||
|
||||
if (approving && voucherNo.length < 6) {
|
||||
ElMessage.warning('通过复核必须填写银行凭证号(不少于 6 位)')
|
||||
return
|
||||
}
|
||||
if (!approving && reason.length < 5) {
|
||||
ElMessage.warning('驳回必须填写原因(不少于 5 个字)')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: approving ? '复核通过退款' : '驳回退款',
|
||||
message: approving
|
||||
? `退款单 #${refund.id}(${formatCent(refund.amountCent)})通过后将扣回点数并登记现金退款,是否继续?`
|
||||
: `退款单 #${refund.id}(${formatCent(refund.amountCent)})驳回后不会扣回点数,是否继续?`,
|
||||
confirmText: approving ? '确认通过' : '确认驳回',
|
||||
requireType: approving ? '确认通过' : '确认驳回',
|
||||
type: approving ? 'warning' : 'error',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('复核退款')
|
||||
if (!totp) return
|
||||
|
||||
const payload: RefundReviewPayload = { action: reviewForm.action, totp }
|
||||
if (approving) {
|
||||
payload.voucherNo = voucherNo
|
||||
} else {
|
||||
payload.reason = reason
|
||||
}
|
||||
|
||||
reviewSubmitting.value = true
|
||||
try {
|
||||
await refundApi.review(refund.id, payload)
|
||||
ElMessage.success(approving ? '退款已复核通过' : '退款已驳回')
|
||||
reviewVisible.value = false
|
||||
await loadRefunds()
|
||||
} catch (err) {
|
||||
ElMessage.error(userMessage(err as ApiError))
|
||||
} finally {
|
||||
reviewSubmitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="退款单" desc="现金退款走双链路:点数回补扣回(REFUND_OUT)与现金退款流水;复核人不得与发起人相同。">
|
||||
<el-button v-perm="'fin:refund:create'" type="primary" @click="openCreate">
|
||||
<el-icon style="margin-right: 4px"><Plus /></el-icon>发起退款
|
||||
</el-button>
|
||||
</PageHeader>
|
||||
|
||||
<div class="notice info">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<span>
|
||||
退款分两条链路:点数按兑率扣回(REFUND_OUT)与现金退款出账;大额退款提交后进入待复核,
|
||||
复核人必须与发起人不同,前端生成的幂等键用于防止重复提交。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<el-select v-model="filters.appCode" placeholder="全部应用" clearable style="width: 180px">
|
||||
<el-option v-for="app in appOptions" :key="app.appCode" :label="app.appName" :value="app.appCode" />
|
||||
</el-select>
|
||||
<el-select v-model="filters.status" placeholder="全部状态" clearable style="width: 130px">
|
||||
<el-option v-for="item in REFUND_STATUS_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="filters.keyword"
|
||||
placeholder="订单号 / 凭证号"
|
||||
clearable
|
||||
style="width: 220px"
|
||||
@keyup.enter="handleSearch"
|
||||
/>
|
||||
<el-date-picker
|
||||
v-model="filters.from"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
placeholder="开始日期"
|
||||
style="width: 150px"
|
||||
/>
|
||||
<span class="muted">至</span>
|
||||
<el-date-picker
|
||||
v-model="filters.to"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
placeholder="结束日期"
|
||||
style="width: 150px"
|
||||
/>
|
||||
<el-button type="primary" @click="handleSearch">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
</div>
|
||||
|
||||
<el-table :data="rows" v-loading="loading" row-key="id" border stripe empty-text="暂无退款单">
|
||||
<el-table-column label="退款单号" width="110">
|
||||
<template #default="{ row }"><span class="mono">#{{ row.id }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="原订单号" min-width="190">
|
||||
<template #default="{ row }"><span class="mono">{{ row.outTradeNo }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="应用" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.appName }}</div>
|
||||
<div class="mono muted small">{{ row.appCode }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="业务用户" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<div class="mono">{{ row.businessUserId }}</div>
|
||||
<div class="muted small">{{ row.usernameSnapshot }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="退款金额" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num amount">{{ formatCent(row.amountCent) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="扣回点数" width="110" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ formatPoints(row.pointsDeducted) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="refundStatusMeta(row.status).tag" effect="light">{{ refundStatusMeta(row.status).label }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="发起人" width="120">
|
||||
<template #default="{ row }">{{ row.operatorAdminName }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="复核人" width="120">
|
||||
<template #default="{ row }">{{ row.reviewerAdminName || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="凭证号" width="140">
|
||||
<template #default="{ row }"><span class="mono">{{ maskVoucher(row.voucherNo) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="100" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-tooltip v-if="row.status === 'PENDING'" :content="'发起人不得复核'" :disabled="!isSelfRefund(row)">
|
||||
<span>
|
||||
<el-button
|
||||
v-perm="'fin:refund:review'"
|
||||
link
|
||||
type="primary"
|
||||
:disabled="isSelfRefund(row)"
|
||||
@click="openReview(row)"
|
||||
>
|
||||
复核
|
||||
</el-button>
|
||||
</span>
|
||||
</el-tooltip>
|
||||
<span v-else class="muted">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page"
|
||||
v-model:page-size="pageSize"
|
||||
background
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
:total="total"
|
||||
@size-change="handleSearch"
|
||||
@current-change="loadRefunds"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-dialog
|
||||
v-model="createVisible"
|
||||
title="发起退款"
|
||||
width="620px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
>
|
||||
<div class="notice warn dialog-notice">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>退款会扣回用户点数并登记现金退款流水,操作不可撤销,且会写入审计日志。</span>
|
||||
</div>
|
||||
<el-form label-width="110px">
|
||||
<el-form-item label="原订单" required>
|
||||
<el-select
|
||||
v-model="createForm.orderId"
|
||||
filterable
|
||||
remote
|
||||
clearable
|
||||
placeholder="按订单号/用户搜索已到账订单"
|
||||
:remote-method="searchOrders"
|
||||
:loading="orderLoading"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option
|
||||
v-for="order in orderOptions"
|
||||
:key="order.id"
|
||||
:label="orderOptionLabel(order)"
|
||||
:value="order.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="订单信息">
|
||||
<div v-if="selectedOrder" class="order-summary">
|
||||
<span>订单金额:<strong class="num">{{ formatCent(selectedOrder.amountCent) }}</strong></span>
|
||||
<span>已退金额:<strong class="num">{{ formatCent(selectedOrder.refundedAmountCent) }}</strong></span>
|
||||
<span>
|
||||
可退上限:<strong class="num">{{ formatCent(maxRefundableCent) }}</strong>
|
||||
</span>
|
||||
</div>
|
||||
<span v-else class="muted">请先选择原订单</span>
|
||||
</el-form-item>
|
||||
<el-form-item label="退款金额(元)" required>
|
||||
<el-input v-model="createForm.amountYuan" placeholder="例如 100.00" style="width: 220px" />
|
||||
<span v-if="selectedOrder" class="muted small field-hint">
|
||||
不得超过 {{ formatCent(maxRefundableCent) }}
|
||||
</span>
|
||||
</el-form-item>
|
||||
<el-form-item label="退款原因" required>
|
||||
<el-input
|
||||
v-model="createForm.reason"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
maxlength="200"
|
||||
show-word-limit
|
||||
placeholder="请填写退款原因(不少于 5 个字)"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="凭证号">
|
||||
<el-input v-model="createForm.voucherNo" maxlength="32" placeholder="可选,复核通过时仍必须登记(不少于 6 位)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="幂等键">
|
||||
<el-input :model-value="createForm.idempotencyKey" readonly>
|
||||
<template #append>只读</template>
|
||||
</el-input>
|
||||
<span class="muted small field-hint">由前端生成,用于防止重复提交</span>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div v-if="selectedOrder?.needDualControl" class="notice warn dialog-notice">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>该订单金额已达到双人复核阈值,大额退款提交后将进入待复核,需另一名管理员复核后才生效。</span>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="createVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="createSubmitting" @click="submitCreate">提交退款</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
v-model="reviewVisible"
|
||||
:title="reviewTarget ? `复核退款 · #${reviewTarget.id}` : '复核退款'"
|
||||
width="540px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
>
|
||||
<template v-if="reviewTarget">
|
||||
<div class="notice info dialog-notice">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<span>
|
||||
原订单 <span class="mono">{{ reviewTarget.outTradeNo }}</span>,退款
|
||||
{{ formatCent(reviewTarget.amountCent) }},发起人 {{ reviewTarget.operatorAdminName }}。
|
||||
</span>
|
||||
</div>
|
||||
<el-form label-width="100px">
|
||||
<el-form-item label="复核结果" required>
|
||||
<el-radio-group v-model="reviewForm.action">
|
||||
<el-radio value="approve">通过</el-radio>
|
||||
<el-radio value="reject">驳回</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="reviewForm.action === 'approve'" label="凭证号" required>
|
||||
<el-input v-model="reviewForm.voucherNo" maxlength="32" placeholder="银行凭证号(不少于 6 位)" />
|
||||
</el-form-item>
|
||||
<el-form-item v-else label="驳回原因" required>
|
||||
<el-input
|
||||
v-model="reviewForm.reason"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
maxlength="200"
|
||||
show-word-limit
|
||||
placeholder="请填写驳回原因(不少于 5 个字)"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</template>
|
||||
<template #footer>
|
||||
<el-button @click="reviewVisible = false">取消</el-button>
|
||||
<el-button
|
||||
:type="reviewForm.action === 'approve' ? 'primary' : 'danger'"
|
||||
:loading="reviewSubmitting"
|
||||
@click="submitReview"
|
||||
>
|
||||
{{ reviewForm.action === 'approve' ? '确认通过' : '确认驳回' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.amount {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.order-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
font-size: 13px;
|
||||
color: var(--fin-text-2);
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.dialog-notice {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,466 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { adminApi } from '@/api/system'
|
||||
import { PERM, ROLE_LABEL, ROLE_OPTIONS } from '@/constants'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { askTotp, confirmAction } from '@/utils/confirm'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { userMessage, type ApiError } from '@/utils/http'
|
||||
import type { AdminInfo, Role } from '@/types'
|
||||
|
||||
type TagType = 'info' | 'success' | 'warning' | 'danger'
|
||||
|
||||
const ROLE_TAG: Record<Role, TagType> = {
|
||||
SUPER_ADMIN: 'danger',
|
||||
FINANCE: 'success',
|
||||
AUDITOR: 'info',
|
||||
}
|
||||
|
||||
const store = useUserStore()
|
||||
|
||||
const admins = ref<AdminInfo[]>([])
|
||||
const loading = ref(false)
|
||||
const keyword = ref('')
|
||||
const roleFilter = ref<'' | Role>('')
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const togglingId = ref<number | null>(null)
|
||||
const roleSavingId = ref<number | null>(null)
|
||||
|
||||
const createVisible = ref(false)
|
||||
const createSubmitting = ref(false)
|
||||
const createForm = reactive<{ username: string; role: Role; totp: string }>({
|
||||
username: '',
|
||||
role: 'FINANCE',
|
||||
totp: '',
|
||||
})
|
||||
|
||||
const secretVisible = ref(false)
|
||||
const secret = reactive({ title: '', username: '', value: '', note: '' })
|
||||
const countdown = ref(60)
|
||||
let countdownTimer = 0
|
||||
|
||||
const filteredAdmins = computed(() =>
|
||||
admins.value.filter(item => {
|
||||
if (roleFilter.value && item.role !== roleFilter.value) return false
|
||||
const text = keyword.value.trim().toLowerCase()
|
||||
if (!text) return true
|
||||
return item.username.toLowerCase().includes(text)
|
||||
}),
|
||||
)
|
||||
|
||||
const total = computed(() => filteredAdmins.value.length)
|
||||
|
||||
const pagedAdmins = computed(() => {
|
||||
const start = (page.value - 1) * pageSize.value
|
||||
return filteredAdmins.value.slice(start, start + pageSize.value)
|
||||
})
|
||||
|
||||
function roleMeta(value: string): { label: string; tag: TagType } {
|
||||
return {
|
||||
label: ROLE_LABEL[value as Role] ?? value,
|
||||
tag: ROLE_TAG[value as Role] ?? 'info',
|
||||
}
|
||||
}
|
||||
|
||||
async function loadList(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
admins.value = await adminApi.list()
|
||||
const maxPage = Math.max(1, Math.ceil(filteredAdmins.value.length / pageSize.value))
|
||||
if (page.value > maxPage) page.value = maxPage
|
||||
} catch {
|
||||
// 错误提示已由请求层统一处理
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSizeChange(): void {
|
||||
page.value = 1
|
||||
}
|
||||
|
||||
watch([keyword, roleFilter], () => {
|
||||
page.value = 1
|
||||
})
|
||||
|
||||
function openCreate(): void {
|
||||
createForm.username = ''
|
||||
createForm.role = 'FINANCE'
|
||||
createForm.totp = ''
|
||||
createVisible.value = true
|
||||
}
|
||||
|
||||
function stopCountdown(): void {
|
||||
if (countdownTimer) {
|
||||
window.clearInterval(countdownTimer)
|
||||
countdownTimer = 0
|
||||
}
|
||||
}
|
||||
|
||||
function startCountdown(): void {
|
||||
stopCountdown()
|
||||
countdownTimer = window.setInterval(() => {
|
||||
countdown.value -= 1
|
||||
if (countdown.value <= 0) {
|
||||
stopCountdown()
|
||||
secretVisible.value = false
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
function showSecret(title: string, username: string, value: string, note: string): void {
|
||||
secret.title = title
|
||||
secret.username = username
|
||||
secret.value = value
|
||||
secret.note = note
|
||||
countdown.value = 60
|
||||
secretVisible.value = true
|
||||
startCountdown()
|
||||
}
|
||||
|
||||
function closeSecret(): void {
|
||||
secretVisible.value = false
|
||||
}
|
||||
|
||||
watch(secretVisible, visible => {
|
||||
if (!visible) {
|
||||
stopCountdown()
|
||||
secret.value = ''
|
||||
secret.username = ''
|
||||
}
|
||||
})
|
||||
|
||||
async function copySecret(): Promise<void> {
|
||||
if (!secret.value) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(secret.value)
|
||||
ElMessage.success('已复制到剪贴板,请粘贴到安全位置后立即删除')
|
||||
} catch {
|
||||
ElMessage.warning('复制失败,请手动选中文本复制')
|
||||
}
|
||||
}
|
||||
|
||||
async function submitCreate(): Promise<void> {
|
||||
const username = createForm.username.trim()
|
||||
if (!/^[a-z][a-z0-9_]{2,31}$/.test(username)) {
|
||||
ElMessage.warning('用户名需为 3~32 位小写字母、数字或下划线,且以小写字母开头')
|
||||
return
|
||||
}
|
||||
if (!/^\d{6}$/.test(createForm.totp)) {
|
||||
ElMessage.warning('请输入 6 位动态口令')
|
||||
return
|
||||
}
|
||||
|
||||
createSubmitting.value = true
|
||||
try {
|
||||
const result = await adminApi.create({ username, role: createForm.role, totp: createForm.totp })
|
||||
createVisible.value = false
|
||||
showSecret(
|
||||
'管理员创建成功',
|
||||
result.admin.username,
|
||||
result.initialPassword,
|
||||
'初始密码仅本次展示,关闭后无法再次查看;该账号首次登录时必须修改密码。',
|
||||
)
|
||||
await loadList()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
createSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggle(row: AdminInfo): Promise<void> {
|
||||
const enabled = row.isActive === 1 ? 0 : 1
|
||||
if (enabled === 0 && row.id === store.admin?.id) {
|
||||
ElMessage.warning('不能停用当前登录账号')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: enabled === 1 ? '启用管理员' : '停用管理员',
|
||||
message:
|
||||
enabled === 1
|
||||
? `启用「${row.username}」后其可立即恢复登录权限,是否继续?`
|
||||
: `停用「${row.username}」后其登录会话与权限将立即失效,是否继续?`,
|
||||
confirmText: enabled === 1 ? '确认启用' : '确认停用',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
togglingId.value = row.id
|
||||
try {
|
||||
const updated = await adminApi.toggle(row.id, enabled)
|
||||
row.isActive = updated.isActive
|
||||
ElMessage.success(enabled === 1 ? '已启用该管理员' : '已停用该管理员')
|
||||
} catch {
|
||||
// 失败原因(如最后一个超管不可停用)由请求层提示
|
||||
} finally {
|
||||
togglingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRoleChange(row: AdminInfo, role: string): Promise<void> {
|
||||
if (role === row.role) return
|
||||
|
||||
roleSavingId.value = row.id
|
||||
try {
|
||||
const updated = await adminApi.updateRole(row.id, { role: role as Role })
|
||||
row.role = updated.role
|
||||
ElMessage.success(`已将「${row.username}」角色调整为${roleMeta(updated.role).label}`)
|
||||
} catch {
|
||||
// 失败原因(如降级最后一名超管)由请求层提示,界面保持原角色不变
|
||||
} finally {
|
||||
roleSavingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function resetPassword(row: AdminInfo): Promise<void> {
|
||||
const confirmed = await confirmAction({
|
||||
title: '重置管理员密码',
|
||||
message: `将为「${row.username}」生成临时密码,原密码立即失效,对方下次登录必须修改密码。是否继续?`,
|
||||
confirmText: '重置密码',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('重置管理员密码')
|
||||
if (!totp) return
|
||||
|
||||
try {
|
||||
const result = await adminApi.resetPassword(row.id, totp)
|
||||
showSecret(
|
||||
'临时密码(仅显示一次)',
|
||||
row.username,
|
||||
result.tempPassword,
|
||||
'临时密码仅本次展示,关闭后无法再次查看;该账号首次登录时必须修改密码。',
|
||||
)
|
||||
await loadList()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
}
|
||||
}
|
||||
|
||||
async function resetTotp(row: AdminInfo): Promise<void> {
|
||||
const confirmed = await confirmAction({
|
||||
title: '重置动态口令',
|
||||
message: `将解绑「${row.username}」的身份验证器,对方下次登录需重新绑定。是否继续?`,
|
||||
confirmText: '重置 TOTP',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('重置管理员动态口令')
|
||||
if (!totp) return
|
||||
|
||||
try {
|
||||
const result = await adminApi.resetTotp(row.id, totp)
|
||||
ElMessage.success(result.message)
|
||||
await loadList()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadList)
|
||||
|
||||
onBeforeUnmount(stopCountdown)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="管理员" desc="后台账号、角色与双因子状态管理,所有变更全量审计。">
|
||||
<el-button v-perm="PERM.adminManage" type="primary" @click="openCreate">
|
||||
<el-icon style="margin-right: 4px"><Plus /></el-icon>新建管理员
|
||||
</el-button>
|
||||
</PageHeader>
|
||||
|
||||
<div class="notice info">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<span>
|
||||
三角色职责分离:超级管理员负责配置与账号,财务专员负责资金操作,审计员只读。
|
||||
系统必须保留至少一名启用状态的超级管理员;管理员的所有操作均全量写入审计日志。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-top: 16px">
|
||||
<div class="filter-bar">
|
||||
<el-input v-model="keyword" placeholder="搜索用户名" clearable style="width: 220px" />
|
||||
<el-select v-model="roleFilter" placeholder="全部角色" clearable style="width: 160px">
|
||||
<el-option v-for="option in ROLE_OPTIONS" :key="option.value" :label="option.label" :value="option.value" />
|
||||
</el-select>
|
||||
<div class="spacer" />
|
||||
<span class="muted small">共 {{ total }} 名管理员</span>
|
||||
</div>
|
||||
|
||||
<el-table v-loading="loading" :data="pagedAdmins" empty-text="暂无管理员" border>
|
||||
<el-table-column prop="id" label="ID" width="80" />
|
||||
<el-table-column label="用户名" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.username }}</span>
|
||||
<el-tag v-if="row.id === store.admin?.id" size="small" type="info" effect="plain" style="margin-left: 6px">
|
||||
当前
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="角色" width="130">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="roleMeta(row.role).tag" size="small" effect="light">{{ roleMeta(row.role).label }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="120">
|
||||
<template #default="{ row }">
|
||||
<el-switch
|
||||
v-perm="PERM.adminManage"
|
||||
:model-value="row.isActive === 1"
|
||||
:loading="togglingId === row.id"
|
||||
:disabled="row.id === store.admin?.id"
|
||||
@change="handleToggle(row)"
|
||||
/>
|
||||
<span class="muted small" style="margin-left: 6px">{{ row.isActive === 1 ? '启用' : '停用' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="TOTP 绑定" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.totpBound ? 'success' : 'warning'" size="small">
|
||||
{{ row.totpBound ? '已绑定' : '未绑定' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="失败次数" width="90" align="center">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ row.failedAttempts }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="锁定至" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.lockedUntil) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最后登录" min-width="180">
|
||||
<template #default="{ row }">
|
||||
<div>{{ formatDateTime(row.lastLoginAt) }}</div>
|
||||
<div class="muted small mono">{{ row.lastLoginIp || '—' }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="创建时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="260" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-dropdown
|
||||
v-perm="PERM.adminManage"
|
||||
trigger="click"
|
||||
@command="handleRoleChange(row, $event)"
|
||||
>
|
||||
<el-button link type="primary" :loading="roleSavingId === row.id">调整角色</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
v-for="option in ROLE_OPTIONS"
|
||||
:key="option.value"
|
||||
:command="option.value"
|
||||
:disabled="option.value === row.role"
|
||||
>
|
||||
{{ option.label }}
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<el-button v-perm="PERM.adminManage" link type="warning" @click="resetPassword(row)">重置密码</el-button>
|
||||
<el-button v-perm="PERM.adminManage" link type="info" @click="resetTotp(row)">重置 TOTP</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="total"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
layout="total, sizes, prev, pager, next"
|
||||
background
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="createVisible" title="新建管理员" width="480px" :close-on-click-modal="false">
|
||||
<div class="notice warn" style="margin-bottom: 16px">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>初始密码仅展示一次,请通过安全渠道交付;该账号首次登录时必须修改密码。</span>
|
||||
</div>
|
||||
<el-form label-width="88px">
|
||||
<el-form-item label="用户名" required>
|
||||
<el-input v-model="createForm.username" maxlength="32" placeholder="3~32 位小写字母、数字或下划线" />
|
||||
<div class="muted small">需以小写字母开头,仅允许 a-z、0-9 与下划线。</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="角色" required>
|
||||
<el-select v-model="createForm.role" style="width: 100%">
|
||||
<el-option
|
||||
v-for="option in ROLE_OPTIONS"
|
||||
:key="option.value"
|
||||
:label="option.label"
|
||||
:value="option.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="动态口令" required>
|
||||
<el-input v-model="createForm.totp" maxlength="6" placeholder="6 位数字动态码" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="createVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="createSubmitting" @click="submitCreate">创建账号</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
v-model="secretVisible"
|
||||
:title="secret.title"
|
||||
width="520px"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="false"
|
||||
:show-close="false"
|
||||
>
|
||||
<div class="notice danger">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>{{ secret.note }}</span>
|
||||
</div>
|
||||
<el-descriptions :column="1" border style="margin-top: 14px">
|
||||
<el-descriptions-item label="管理员">
|
||||
<span class="mono">{{ secret.username }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="一次性密码">
|
||||
<span class="secret-box mono">{{ secret.value }}</span>
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<p class="muted small">窗口将在 {{ countdown }} 秒后自动关闭,关闭后密码不可再次查看。</p>
|
||||
<template #footer>
|
||||
<el-button @click="copySecret">复制密码</el-button>
|
||||
<el-button type="primary" @click="closeSecret">我已保存,关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.notice .el-icon {
|
||||
margin-top: 2px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.el-form-item .muted.small {
|
||||
display: block;
|
||||
width: 100%;
|
||||
line-height: 1.6;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.secret-box {
|
||||
display: inline-block;
|
||||
padding: 4px 10px;
|
||||
border-radius: 6px;
|
||||
background: #0f172a;
|
||||
color: #d7e3f4;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,364 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import ExportButton from '@/components/ExportButton.vue'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { auditApi, type AuditQuery } from '@/api/system'
|
||||
import { PERM } from '@/constants'
|
||||
import { confirmAction } from '@/utils/confirm'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import type { CsvColumn } from '@/utils/export'
|
||||
import type { AuditLog, ChainVerifyResult } from '@/types'
|
||||
|
||||
type TagType = 'primary' | 'success' | 'info' | 'warning' | 'danger'
|
||||
|
||||
const ACTOR_TYPE_META: Record<AuditLog['actorType'], { label: string; tag: TagType }> = {
|
||||
ADMIN: { label: '管理员', tag: 'primary' },
|
||||
SYSTEM: { label: '系统', tag: 'info' },
|
||||
BIZ: { label: '业务方', tag: 'warning' },
|
||||
}
|
||||
|
||||
const RESULT_META: Record<AuditLog['result'], { label: string; tag: TagType }> = {
|
||||
SUCCESS: { label: '成功', tag: 'success' },
|
||||
FAILED: { label: '失败', tag: 'danger' },
|
||||
}
|
||||
|
||||
const RESULT_OPTIONS = [
|
||||
{ value: 'SUCCESS', label: '成功' },
|
||||
{ value: 'FAILED', label: '失败' },
|
||||
]
|
||||
|
||||
function actorTypeMeta(value: string): { label: string; tag: TagType } {
|
||||
return ACTOR_TYPE_META[value as AuditLog['actorType']] ?? { label: value, tag: 'info' }
|
||||
}
|
||||
|
||||
function resultMeta(value: string): { label: string; tag: TagType } {
|
||||
return RESULT_META[value as AuditLog['result']] ?? { label: value, tag: 'info' }
|
||||
}
|
||||
|
||||
function prettyJson(value: string | null | undefined): string {
|
||||
if (!value) return '无'
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(value), null, 2)
|
||||
} catch {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const rows = ref<AuditLog[]>([])
|
||||
const total = ref(0)
|
||||
const filters = reactive({
|
||||
actor: '',
|
||||
action: '',
|
||||
result: '',
|
||||
keyword: '',
|
||||
})
|
||||
const range = ref<string[] | null>(null)
|
||||
const page = reactive({ page: 1, pageSize: 20 })
|
||||
|
||||
const verifying = ref(false)
|
||||
const verifyResult = ref<ChainVerifyResult | null>(null)
|
||||
|
||||
const detailVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<AuditLog | null>(null)
|
||||
|
||||
/** 动作下拉项从当前页数据动态生成,便于快速按动作过滤 */
|
||||
const actionOptions = computed(() => {
|
||||
const map = new Map<string, string>()
|
||||
rows.value.forEach(row => {
|
||||
if (!map.has(row.action)) map.set(row.action, row.actionLabel)
|
||||
})
|
||||
return Array.from(map, ([value, label]) => ({ value, label: `${label}(${value})` }))
|
||||
})
|
||||
|
||||
const exportColumns: CsvColumn<Record<string, any>>[] = [
|
||||
{ label: '日志ID', value: row => row.id },
|
||||
{ label: '操作人', value: row => row.actorName },
|
||||
{ label: '操作人类型', value: row => row.actorType },
|
||||
{ label: '动作', value: row => row.actionLabel },
|
||||
{ label: '动作编码', value: row => row.action },
|
||||
{ label: '目标类型', value: row => row.targetType },
|
||||
{ label: '目标ID', value: row => row.targetId },
|
||||
{ label: '结果', value: row => row.result },
|
||||
{ label: 'IP', value: row => row.ip },
|
||||
{ label: '发生时间', value: row => row.createTime },
|
||||
{ label: '当前哈希', value: row => row.curHash },
|
||||
]
|
||||
|
||||
function buildQuery(): AuditQuery {
|
||||
return {
|
||||
page: page.page,
|
||||
pageSize: page.pageSize,
|
||||
actor: filters.actor.trim() || undefined,
|
||||
action: filters.action || undefined,
|
||||
result: filters.result || undefined,
|
||||
keyword: filters.keyword.trim() || undefined,
|
||||
from: range.value?.[0] || undefined,
|
||||
to: range.value?.[1] || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadList(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await auditApi.list(buildQuery())
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch {
|
||||
// 错误提示已由请求层统一处理
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function search(): void {
|
||||
page.page = 1
|
||||
void loadList()
|
||||
}
|
||||
|
||||
function resetFilters(): void {
|
||||
filters.actor = ''
|
||||
filters.action = ''
|
||||
filters.result = ''
|
||||
filters.keyword = ''
|
||||
range.value = null
|
||||
page.page = 1
|
||||
void loadList()
|
||||
}
|
||||
|
||||
function handleSizeChange(): void {
|
||||
page.page = 1
|
||||
void loadList()
|
||||
}
|
||||
|
||||
async function verifyChain(): Promise<void> {
|
||||
const confirmed = await confirmAction({
|
||||
title: '校验审计哈希链',
|
||||
message: '将按日志 ID 顺序逐条重算哈希并比对,只读不改数;校验行为本身也会写入审计日志。是否继续?',
|
||||
confirmText: '开始校验',
|
||||
type: 'info',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
verifying.value = true
|
||||
try {
|
||||
verifyResult.value = await auditApi.verify()
|
||||
} catch {
|
||||
verifyResult.value = null
|
||||
} finally {
|
||||
verifying.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function exportRows(): Promise<Record<string, any>[]> {
|
||||
return auditApi.export(buildQuery()).then(list => list as unknown as Record<string, any>[])
|
||||
}
|
||||
|
||||
async function openDetail(row: AuditLog): Promise<void> {
|
||||
detailVisible.value = true
|
||||
detail.value = null
|
||||
detailLoading.value = true
|
||||
try {
|
||||
detail.value = await auditApi.detail(row.id)
|
||||
} catch {
|
||||
detail.value = null
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadList)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="审计日志" desc="资金与账号操作的全量留痕,只追加、不可修改,支持哈希链校验。">
|
||||
<el-button v-perm="PERM.auditView" :loading="verifying" @click="verifyChain">
|
||||
<el-icon style="margin-right: 4px"><CircleCheck /></el-icon>校验哈希链
|
||||
</el-button>
|
||||
<ExportButton v-perm="PERM.export" filename="审计日志" :columns="exportColumns" :fetcher="exportRows" />
|
||||
</PageHeader>
|
||||
|
||||
<div class="notice info">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<span>
|
||||
审计日志只追加不可修改;后端使用 Elasticsearch 存储、Redis Stream 削峰异步落库。
|
||||
导出行为本身也会写入审计日志。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<el-alert
|
||||
v-if="verifyResult"
|
||||
:type="verifyResult.valid ? 'success' : 'error'"
|
||||
:closable="false"
|
||||
show-icon
|
||||
style="margin-top: 12px"
|
||||
>
|
||||
<template #title>{{ verifyResult.message }}</template>
|
||||
<div class="small">
|
||||
已校验 {{ verifyResult.checked }} 条日志;
|
||||
{{ verifyResult.valid ? '全部哈希链一致' : `首个断裂位置:日志 ID ${verifyResult.brokenAtId}` }};
|
||||
校验时间 {{ formatDateTime(verifyResult.checkedAt) }}
|
||||
</div>
|
||||
</el-alert>
|
||||
|
||||
<div class="card" style="margin-top: 16px">
|
||||
<div class="filter-bar">
|
||||
<el-input v-model="filters.actor" placeholder="操作人" clearable style="width: 160px" @keyup.enter="search" />
|
||||
<el-select v-model="filters.action" placeholder="全部动作" clearable filterable style="width: 220px">
|
||||
<el-option v-for="item in actionOptions" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<el-select v-model="filters.result" placeholder="全部结果" clearable style="width: 130px">
|
||||
<el-option v-for="item in RESULT_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="filters.keyword"
|
||||
placeholder="动作描述 / 目标类型 / 哈希"
|
||||
clearable
|
||||
style="width: 230px"
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
<el-date-picker
|
||||
v-model="range"
|
||||
type="daterange"
|
||||
value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
unlink-panels
|
||||
style="width: 260px"
|
||||
/>
|
||||
<el-button type="primary" @click="search">查询</el-button>
|
||||
<el-button @click="resetFilters">重置</el-button>
|
||||
<div class="spacer" />
|
||||
<span class="muted small">共 {{ total }} 条</span>
|
||||
</div>
|
||||
|
||||
<el-table v-loading="loading" :data="rows" empty-text="暂无审计日志" border>
|
||||
<el-table-column prop="id" label="ID" width="80" />
|
||||
<el-table-column label="操作人" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<span>{{ row.actorName }}</span>
|
||||
<el-tag
|
||||
:type="actorTypeMeta(row.actorType).tag"
|
||||
size="small"
|
||||
effect="plain"
|
||||
style="margin-left: 6px"
|
||||
>
|
||||
{{ actorTypeMeta(row.actorType).label }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="动作" min-width="190">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.actionLabel }}</div>
|
||||
<div class="mono muted small">{{ row.action }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="目标" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.targetType }}</span>
|
||||
<span v-if="row.targetId" class="muted"> #{{ row.targetId }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="结果" width="90">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="resultMeta(row.result).tag" size="small">{{ resultMeta(row.result).label }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="IP" width="130">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.ip }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="当前哈希" min-width="170">
|
||||
<template #default="{ row }">
|
||||
<el-tooltip :content="row.curHash" placement="top" effect="dark">
|
||||
<span class="hash">{{ row.curHash.slice(0, 12) }}…</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="openDetail(row)">详情</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page.page"
|
||||
v-model:page-size="page.pageSize"
|
||||
:total="total"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
layout="total, sizes, prev, pager, next"
|
||||
background
|
||||
@current-change="loadList"
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-drawer v-model="detailVisible" title="审计日志详情" size="640px">
|
||||
<div v-loading="detailLoading" style="min-height: 200px">
|
||||
<template v-if="detail">
|
||||
<el-descriptions :column="1" border>
|
||||
<el-descriptions-item label="日志 ID">{{ detail.id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="操作人">
|
||||
{{ detail.actorName }}({{ actorTypeMeta(detail.actorType).label }})
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="动作">
|
||||
{{ detail.actionLabel }} <span class="mono muted">{{ detail.action }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="目标">
|
||||
<span class="mono">{{ detail.targetType }}</span>
|
||||
<span v-if="detail.targetId" class="muted"> #{{ detail.targetId }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="结果">
|
||||
<el-tag :type="resultMeta(detail.result).tag" size="small">
|
||||
{{ resultMeta(detail.result).label }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="IP">
|
||||
<span class="mono">{{ detail.ip }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="User-Agent">{{ detail.ua || '—' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="发生时间">{{ formatDateTime(detail.createTime) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="上一条哈希">
|
||||
<span class="hash">{{ detail.prevHash || '—' }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="当前哈希">
|
||||
<span class="hash">{{ detail.curHash }}</span>
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<h4 class="json-title">变更前</h4>
|
||||
<pre class="code-block">{{ prettyJson(detail.beforeJson) }}</pre>
|
||||
<h4 class="json-title">变更后</h4>
|
||||
<pre class="code-block">{{ prettyJson(detail.afterJson) }}</pre>
|
||||
|
||||
<div class="notice warn" style="margin-top: 16px">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>审计日志采用哈希链串联,任一条记录的哈希被篡改都会导致后续全部记录校验失败。</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.notice .el-icon {
|
||||
margin-top: 2px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.json-title {
|
||||
margin: 18px 0 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,278 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { configApi } from '@/api/settings'
|
||||
import { PERM } from '@/constants'
|
||||
import { confirmAction } from '@/utils/confirm'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { userMessage, type ApiError } from '@/utils/http'
|
||||
import type { ConfigItem } from '@/types'
|
||||
|
||||
const RISK_OPTIONS = [
|
||||
{ value: 'HIGH', label: '高风险' },
|
||||
{ value: 'NORMAL', label: '普通' },
|
||||
]
|
||||
|
||||
const RISK_LABEL: Record<ConfigItem['risk'], string> = {
|
||||
HIGH: '高风险',
|
||||
NORMAL: '普通',
|
||||
}
|
||||
|
||||
/** 密钥类参数不得在前端回显,统一以占位符展示 */
|
||||
const SENSITIVE_KEY = /(^|\.)(secret|password|token|api_key|private_key)$/i
|
||||
|
||||
const configs = ref<ConfigItem[]>([])
|
||||
const loading = ref(false)
|
||||
const keyword = ref('')
|
||||
const riskFilter = ref<'' | ConfigItem['risk']>('')
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
|
||||
const editVisible = ref(false)
|
||||
const editing = ref<ConfigItem | null>(null)
|
||||
const saving = ref(false)
|
||||
const form = reactive({ value: '', reason: '', totp: '' })
|
||||
|
||||
const filteredConfigs = computed(() =>
|
||||
configs.value.filter(item => {
|
||||
if (riskFilter.value && item.risk !== riskFilter.value) return false
|
||||
const text = keyword.value.trim().toLowerCase()
|
||||
if (!text) return true
|
||||
return item.configKey.toLowerCase().includes(text) || item.description.toLowerCase().includes(text)
|
||||
}),
|
||||
)
|
||||
|
||||
const total = computed(() => filteredConfigs.value.length)
|
||||
|
||||
const pagedConfigs = computed(() => {
|
||||
const start = (page.value - 1) * pageSize.value
|
||||
return filteredConfigs.value.slice(start, start + pageSize.value)
|
||||
})
|
||||
|
||||
function displayValue(item: ConfigItem): string {
|
||||
return SENSITIVE_KEY.test(item.configKey) ? '<REDACTED>' : item.configValue
|
||||
}
|
||||
|
||||
function riskLabel(value: string): string {
|
||||
return RISK_LABEL[value as ConfigItem['risk']] ?? value
|
||||
}
|
||||
|
||||
async function loadList(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
configs.value = await configApi.list()
|
||||
const maxPage = Math.max(1, Math.ceil(filteredConfigs.value.length / pageSize.value))
|
||||
if (page.value > maxPage) page.value = maxPage
|
||||
} catch {
|
||||
// 错误提示已由请求层统一处理
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSizeChange(): void {
|
||||
page.value = 1
|
||||
}
|
||||
|
||||
watch([keyword, riskFilter], () => {
|
||||
page.value = 1
|
||||
})
|
||||
|
||||
function openEdit(row: ConfigItem): void {
|
||||
editing.value = row
|
||||
form.value = row.configValue
|
||||
form.reason = ''
|
||||
form.totp = ''
|
||||
editVisible.value = true
|
||||
}
|
||||
|
||||
function validateForm(): boolean {
|
||||
if (!editing.value) return false
|
||||
const value = form.value.trim()
|
||||
if (!value) {
|
||||
ElMessage.warning('配置值不能为空')
|
||||
return false
|
||||
}
|
||||
if (value.length > 255) {
|
||||
ElMessage.warning('配置值不能超过 255 个字符')
|
||||
return false
|
||||
}
|
||||
if (editing.value.configKey === 'pii.mask.enabled' && !['0', '1'].includes(value)) {
|
||||
ElMessage.warning('该开关仅允许 0 或 1')
|
||||
return false
|
||||
}
|
||||
if (form.reason.trim().length < 5) {
|
||||
ElMessage.warning('请填写变更原因(不少于 5 个字)')
|
||||
return false
|
||||
}
|
||||
if (!/^\d{6}$/.test(form.totp)) {
|
||||
ElMessage.warning('请输入 6 位动态口令')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function submitEdit(): Promise<void> {
|
||||
if (!editing.value || !validateForm()) return
|
||||
const item = editing.value
|
||||
const value = form.value.trim()
|
||||
|
||||
const confirmed = await confirmAction({
|
||||
title: '修改全局参数',
|
||||
message: `将把「${item.configKey}」由 ${displayValue(item)} 改为 ${value}。全局参数影响所有接入应用,变更需二次确认。`,
|
||||
requireType: '确认修改配置',
|
||||
confirmText: '提交修改',
|
||||
inputHint: '请输入「确认修改配置」',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
await configApi.update(item.configKey, { value, reason: form.reason.trim(), totp: form.totp })
|
||||
ElMessage.success('配置已更新,变更已写入审计日志')
|
||||
editVisible.value = false
|
||||
await loadList()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadList)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="全局参数" desc="平台级运行参数,影响所有接入应用的计费、风控与安全策略。" />
|
||||
|
||||
<div class="notice warn">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>
|
||||
全局参数影响所有接入应用,变更需动态口令(TOTP)、变更原因并全量写入审计日志;
|
||||
生产环境密钥类参数不得在前端展示,如出现仅显示 <REDACTED>。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-top: 16px">
|
||||
<div class="filter-bar">
|
||||
<el-input v-model="keyword" placeholder="搜索配置键 / 说明" clearable style="width: 240px" />
|
||||
<el-select v-model="riskFilter" placeholder="全部风险等级" clearable style="width: 160px">
|
||||
<el-option v-for="item in RISK_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<div class="spacer" />
|
||||
<span class="muted small">共 {{ total }} 项参数</span>
|
||||
</div>
|
||||
|
||||
<el-table v-loading="loading" :data="pagedConfigs" empty-text="暂无配置项" border>
|
||||
<el-table-column label="配置键" min-width="220">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.configKey }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="配置值" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ displayValue(row) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="description" label="说明" min-width="260" show-overflow-tooltip />
|
||||
<el-table-column label="风险等级" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.risk === 'HIGH' ? 'danger' : 'info'" size="small" effect="plain">
|
||||
{{ riskLabel(row.risk) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="更新人" width="110">
|
||||
<template #default="{ row }">{{ row.updateBy }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="更新时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.updateTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button v-perm="PERM.configEdit" link type="primary" @click="openEdit(row)">修改</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="total"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
layout="total, sizes, prev, pager, next"
|
||||
background
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="editVisible" title="修改全局参数" width="560px" :close-on-click-modal="false">
|
||||
<div v-if="editing?.risk === 'HIGH'" class="notice danger" style="margin-bottom: 14px">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>该参数为高风险配置,修改将立即影响所有接入应用,请确认影响范围并填写变更原因。</span>
|
||||
</div>
|
||||
|
||||
<el-form label-width="96px">
|
||||
<el-form-item label="配置键">
|
||||
<span class="mono">{{ editing?.configKey }}</span>
|
||||
</el-form-item>
|
||||
<el-form-item label="说明">
|
||||
<span class="small">{{ editing?.description }}</span>
|
||||
</el-form-item>
|
||||
<el-form-item label="配置值" required>
|
||||
<el-select
|
||||
v-if="editing?.configKey === 'pii.mask.enabled'"
|
||||
v-model="form.value"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option label="1(开启,推荐)" value="1" />
|
||||
<el-option
|
||||
label="0(关闭)"
|
||||
value="0"
|
||||
:disabled="editing?.configValue === '1'"
|
||||
/>
|
||||
</el-select>
|
||||
<el-input v-else v-model="form.value" maxlength="255" show-word-limit placeholder="请输入配置值" />
|
||||
<div v-if="editing?.configKey === 'pii.mask.enabled' && editing?.configValue === '1'" class="notice danger small" style="margin-top: 8px">
|
||||
<el-icon><WarningFilled /></el-icon>
|
||||
<span>PII 掩码当前已开启,禁止关闭;关闭属高危变更,需运维窗口与专项审批(服务端将返回 4097 拒绝)。</span>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="变更原因" required>
|
||||
<el-input
|
||||
v-model="form.reason"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
maxlength="255"
|
||||
show-word-limit
|
||||
placeholder="请填写变更原因(不少于 5 个字)"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="动态口令" required>
|
||||
<el-input v-model="form.totp" maxlength="6" placeholder="6 位数字动态码" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<template #footer>
|
||||
<el-button @click="editVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="submitEdit">提交修改</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.notice .el-icon {
|
||||
margin-top: 2px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.notice.small {
|
||||
font-size: 12px;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,301 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { appApi } from '@/api/core'
|
||||
import { webhookApi, type WebhookQuery } from '@/api/system'
|
||||
import { PERM, WEBHOOK_STATUS } from '@/constants'
|
||||
import { askTotp, confirmAction } from '@/utils/confirm'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { userMessage, type ApiError } from '@/utils/http'
|
||||
import type { AppInfo, WebhookDelivery, WebhookStatus } from '@/types'
|
||||
|
||||
type TagType = 'info' | 'success' | 'warning' | 'danger'
|
||||
|
||||
const STATUS_OPTIONS = (Object.keys(WEBHOOK_STATUS) as WebhookStatus[]).map(value => ({
|
||||
value,
|
||||
label: WEBHOOK_STATUS[value].label,
|
||||
}))
|
||||
|
||||
const apps = ref<AppInfo[]>([])
|
||||
const loading = ref(false)
|
||||
const rows = ref<WebhookDelivery[]>([])
|
||||
const total = ref(0)
|
||||
|
||||
const filters = reactive({
|
||||
appCode: '',
|
||||
status: '',
|
||||
keyword: '',
|
||||
})
|
||||
const range = ref<string[] | null>(null)
|
||||
const page = reactive({ page: 1, pageSize: 20 })
|
||||
|
||||
const drawerVisible = ref(false)
|
||||
const current = ref<WebhookDelivery | null>(null)
|
||||
const replayingId = ref<number | null>(null)
|
||||
|
||||
function statusMeta(value: string): { label: string; tag: TagType } {
|
||||
return WEBHOOK_STATUS[value as WebhookStatus] ?? { label: value, tag: 'info' }
|
||||
}
|
||||
|
||||
function canReplay(status: string): boolean {
|
||||
return status === 'FAILED' || status === 'DEAD'
|
||||
}
|
||||
|
||||
function prettyPayload(payload: string): string {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(payload), null, 2)
|
||||
} catch {
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
function buildQuery(): WebhookQuery {
|
||||
return {
|
||||
page: page.page,
|
||||
pageSize: page.pageSize,
|
||||
appCode: filters.appCode || undefined,
|
||||
status: filters.status || undefined,
|
||||
keyword: filters.keyword.trim() || undefined,
|
||||
from: range.value?.[0] || undefined,
|
||||
to: range.value?.[1] || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
try {
|
||||
apps.value = await appApi.list()
|
||||
} catch {
|
||||
// 应用下拉加载失败不阻塞列表,错误已由请求层提示
|
||||
}
|
||||
}
|
||||
|
||||
async function loadList(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await webhookApi.list(buildQuery())
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch {
|
||||
// 错误提示已由请求层统一处理
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function search(): void {
|
||||
page.page = 1
|
||||
void loadList()
|
||||
}
|
||||
|
||||
function resetFilters(): void {
|
||||
filters.appCode = ''
|
||||
filters.status = ''
|
||||
filters.keyword = ''
|
||||
range.value = null
|
||||
page.page = 1
|
||||
void loadList()
|
||||
}
|
||||
|
||||
function handleSizeChange(): void {
|
||||
page.page = 1
|
||||
void loadList()
|
||||
}
|
||||
|
||||
function openDetail(row: WebhookDelivery): void {
|
||||
current.value = row
|
||||
drawerVisible.value = true
|
||||
}
|
||||
|
||||
async function replay(row: WebhookDelivery): Promise<void> {
|
||||
const confirmed = await confirmAction({
|
||||
title: '重放 webhook',
|
||||
message: `将重新投递事件 ${row.eventId}(${row.eventType})。重放会重置尝试次数与错误信息,并写入审计日志,是否继续?`,
|
||||
confirmText: '确认重放',
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
const totp = await askTotp('重放 webhook')
|
||||
if (!totp) return
|
||||
|
||||
replayingId.value = row.id
|
||||
try {
|
||||
await webhookApi.replay(row.id, totp)
|
||||
ElMessage.success('已提交重放,投递状态重置为待投递')
|
||||
await loadList()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
replayingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadApps()
|
||||
void loadList()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="Webhook 投递" desc="面向接入应用的事件回调投递记录,支持失败记录人工重放。" />
|
||||
|
||||
<div class="notice info">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<span>
|
||||
Webhook 请求使用 HMAC-SHA256 签名并携带时间戳,用于验签与防重放;仅 FAILED / DEAD 状态可人工重放,
|
||||
重放操作会全量写入审计日志。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-top: 16px">
|
||||
<div class="filter-bar">
|
||||
<el-select v-model="filters.appCode" placeholder="全部应用" clearable style="width: 180px">
|
||||
<el-option
|
||||
v-for="app in apps"
|
||||
:key="app.appCode"
|
||||
:label="`${app.appName}(${app.appCode})`"
|
||||
:value="app.appCode"
|
||||
/>
|
||||
</el-select>
|
||||
<el-select v-model="filters.status" placeholder="全部状态" clearable style="width: 140px">
|
||||
<el-option v-for="item in STATUS_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="filters.keyword"
|
||||
placeholder="事件 ID / 事件类型"
|
||||
clearable
|
||||
style="width: 220px"
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
<el-date-picker
|
||||
v-model="range"
|
||||
type="daterange"
|
||||
value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
unlink-panels
|
||||
style="width: 260px"
|
||||
/>
|
||||
<el-button type="primary" @click="search">查询</el-button>
|
||||
<el-button @click="resetFilters">重置</el-button>
|
||||
<div class="spacer" />
|
||||
<span class="muted small">共 {{ total }} 条</span>
|
||||
</div>
|
||||
|
||||
<el-table v-loading="loading" :data="rows" empty-text="暂无投递记录" border>
|
||||
<el-table-column label="事件 ID" min-width="190" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.eventId }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="应用" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.appName }}</div>
|
||||
<div class="muted small mono">{{ row.appCode }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="事件类型" min-width="120">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.eventType }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="statusMeta(row.status).tag" size="small">{{ statusMeta(row.status).label }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="尝试次数" width="90" align="center">
|
||||
<template #default="{ row }">
|
||||
<span class="num">{{ row.attempts }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="下次重试时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.nextRetryAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最后错误" min-width="180" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.lastError" class="small">{{ row.lastError }}</span>
|
||||
<span v-else class="muted">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="创建时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="140" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="openDetail(row)">查看</el-button>
|
||||
<el-button
|
||||
v-perm="PERM.webhookManage"
|
||||
link
|
||||
type="warning"
|
||||
:disabled="!canReplay(row.status)"
|
||||
:loading="replayingId === row.id"
|
||||
@click="replay(row)"
|
||||
>
|
||||
重放
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page.page"
|
||||
v-model:page-size="page.pageSize"
|
||||
:total="total"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
layout="total, sizes, prev, pager, next"
|
||||
background
|
||||
@current-change="loadList"
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-drawer v-model="drawerVisible" title="Webhook 投递详情" size="600px">
|
||||
<el-descriptions :column="1" border>
|
||||
<el-descriptions-item label="事件 ID">
|
||||
<span class="mono">{{ current?.eventId || '—' }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="应用">
|
||||
{{ current?.appName || '—' }}<span class="muted small mono"> / {{ current?.appCode || '—' }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="事件类型">
|
||||
<span class="mono">{{ current?.eventType || '—' }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="状态">
|
||||
<el-tag :type="statusMeta(current?.status || '').tag" size="small">
|
||||
{{ statusMeta(current?.status || '').label }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="尝试次数">
|
||||
<span class="num">{{ current?.attempts ?? 0 }}</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="下次重试时间">{{ formatDateTime(current?.nextRetryAt) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="最后错误">
|
||||
<span v-if="current?.lastError" class="small">{{ current.lastError }}</span>
|
||||
<span v-else class="muted">—</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="创建时间">{{ formatDateTime(current?.createTime) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="更新时间">{{ formatDateTime(current?.updateTime) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<h4 class="payload-title">Payload</h4>
|
||||
<pre class="code-block">{{ prettyPayload(current?.payload || '') }}</pre>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.notice .el-icon {
|
||||
margin-top: 2px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.payload-title {
|
||||
margin: 20px 0 10px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,297 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { appApi, transactionApi, type TransactionQuery } from '@/api/core'
|
||||
import { TX_TYPE, TX_TYPE_OPTIONS } from '@/constants'
|
||||
import { formatPoints, formatSignedPoints } from '@/utils/money'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import type { CsvColumn } from '@/utils/export'
|
||||
import type { AppInfo, TransactionInfo, TxType } from '@/types'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import ExportButton from '@/components/ExportButton.vue'
|
||||
import StatCard from '@/components/StatCard.vue'
|
||||
|
||||
interface TransactionFilters {
|
||||
appCode: string
|
||||
type: string
|
||||
keyword: string
|
||||
from: string
|
||||
to: string
|
||||
}
|
||||
|
||||
const filters = reactive<TransactionFilters>({
|
||||
appCode: '',
|
||||
type: '',
|
||||
keyword: '',
|
||||
from: '',
|
||||
to: '',
|
||||
})
|
||||
|
||||
const appOptions = ref<AppInfo[]>([])
|
||||
const rows = ref<TransactionInfo[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const loading = ref(false)
|
||||
|
||||
/** 表格插槽中的 row 为 any,统一用带类型的映射函数取展示文案,避免隐式 any 索引 */
|
||||
function txTypeMeta(type: TxType) {
|
||||
return TX_TYPE[type]
|
||||
}
|
||||
|
||||
/** 当前页净变动:充值为正、扣费为负,VIP 免扣与人工调账按 sign 计算 */
|
||||
const netPoints = computed(() =>
|
||||
rows.value.reduce((sum, row) => {
|
||||
const sign = TX_TYPE[row.type].sign
|
||||
return sum + (sign === 0 ? 0 : sign * row.amount)
|
||||
}, 0),
|
||||
)
|
||||
|
||||
const netDisplay = computed(() => formatSignedPoints(Math.abs(netPoints.value), Math.sign(netPoints.value)))
|
||||
|
||||
const netTone = computed<'success' | 'danger' | 'default'>(() => {
|
||||
if (netPoints.value > 0) return 'success'
|
||||
if (netPoints.value < 0) return 'danger'
|
||||
return 'default'
|
||||
})
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
try {
|
||||
appOptions.value = await appApi.list()
|
||||
} catch {
|
||||
appOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
function buildFilter(): TransactionQuery {
|
||||
const query: TransactionQuery = {}
|
||||
if (filters.appCode) query.appCode = filters.appCode
|
||||
if (filters.type) query.type = filters.type
|
||||
const keyword = filters.keyword.trim()
|
||||
if (keyword) query.keyword = keyword
|
||||
if (filters.from) query.from = filters.from
|
||||
if (filters.to) query.to = filters.to
|
||||
return query
|
||||
}
|
||||
|
||||
async function loadTransactions(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await transactionApi.list({
|
||||
...buildFilter(),
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
})
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch {
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSearch(): void {
|
||||
if (filters.from && filters.to && filters.from > filters.to) {
|
||||
ElMessage.warning('开始日期不能晚于结束日期')
|
||||
return
|
||||
}
|
||||
page.value = 1
|
||||
void loadTransactions()
|
||||
}
|
||||
|
||||
function handleReset(): void {
|
||||
filters.appCode = ''
|
||||
filters.type = ''
|
||||
filters.keyword = ''
|
||||
filters.from = ''
|
||||
filters.to = ''
|
||||
page.value = 1
|
||||
void loadTransactions()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void Promise.all([loadApps(), loadTransactions()])
|
||||
})
|
||||
|
||||
function signedText(row: TransactionInfo): string {
|
||||
return formatSignedPoints(row.amount, TX_TYPE[row.type].sign)
|
||||
}
|
||||
|
||||
function signedClass(row: TransactionInfo): string {
|
||||
const sign = TX_TYPE[row.type].sign
|
||||
if (sign > 0) return 'points-in'
|
||||
if (sign < 0) return 'points-out'
|
||||
return 'muted'
|
||||
}
|
||||
|
||||
/* ----------------------------- 导出 ----------------------------- */
|
||||
|
||||
function exportRow(row: TransactionInfo): Record<string, any> {
|
||||
return {
|
||||
id: row.id,
|
||||
app: `${row.appName}(${row.appCode})`,
|
||||
user: `${row.businessUserId} / ${row.usernameSnapshot}`,
|
||||
type: TX_TYPE[row.type].label,
|
||||
amount: signedText(row),
|
||||
balanceBefore: row.balanceBefore,
|
||||
balanceAfter: row.balanceAfter,
|
||||
refNo: row.outTradeNo || row.businessRefId || '',
|
||||
idempotencyKey: row.idempotencyKey,
|
||||
operator: row.operatorAdminName || '',
|
||||
remark: row.remark,
|
||||
createTime: formatDateTime(row.createTime),
|
||||
}
|
||||
}
|
||||
|
||||
const exportColumns: CsvColumn<Record<string, any>>[] = [
|
||||
{ label: '流水号', value: row => row.id },
|
||||
{ label: '应用', value: row => row.app },
|
||||
{ label: '业务用户', value: row => row.user },
|
||||
{ label: '类型', value: row => row.type },
|
||||
{ label: '变动点数', value: row => row.amount },
|
||||
{ label: '变动前', value: row => row.balanceBefore },
|
||||
{ label: '变动后', value: row => row.balanceAfter },
|
||||
{ label: '关联单号', value: row => row.refNo },
|
||||
{ label: '幂等键', value: row => row.idempotencyKey },
|
||||
{ label: '操作人', value: row => row.operator },
|
||||
{ label: '备注', value: row => row.remark },
|
||||
{ label: '时间', value: row => row.createTime },
|
||||
]
|
||||
|
||||
async function fetchExportRows(): Promise<Record<string, any>[]> {
|
||||
const list = await transactionApi.export(buildFilter())
|
||||
return list.map(exportRow)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="点数流水" desc="钱包点数的全量变动记录,只读不可编辑;充值、扣费、退款与人工调账均在此留痕。">
|
||||
<ExportButton
|
||||
v-perm="'fin:export'"
|
||||
filename="点数流水"
|
||||
:columns="exportColumns"
|
||||
:fetcher="fetchExportRows"
|
||||
label="导出流水"
|
||||
/>
|
||||
</PageHeader>
|
||||
|
||||
<div class="stat-grid">
|
||||
<StatCard label="当前页笔数" :value="rows.length" :sub="`筛选结果共 ${total} 笔,仅统计当前页`" />
|
||||
<StatCard label="当前页净变动" :value="netDisplay" :tone="netTone" sub="充值为正、扣费为负,仅统计当前页" />
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<el-select v-model="filters.appCode" placeholder="全部应用" clearable style="width: 180px">
|
||||
<el-option v-for="app in appOptions" :key="app.appCode" :label="app.appName" :value="app.appCode" />
|
||||
</el-select>
|
||||
<el-select v-model="filters.type" placeholder="全部类型" clearable style="width: 150px">
|
||||
<el-option v-for="item in TX_TYPE_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="filters.keyword"
|
||||
placeholder="用户ID / 用户名 / 幂等键 / 业务单号"
|
||||
clearable
|
||||
style="width: 260px"
|
||||
@keyup.enter="handleSearch"
|
||||
/>
|
||||
<el-date-picker
|
||||
v-model="filters.from"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
placeholder="开始日期"
|
||||
style="width: 150px"
|
||||
/>
|
||||
<span class="muted">至</span>
|
||||
<el-date-picker
|
||||
v-model="filters.to"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
placeholder="结束日期"
|
||||
style="width: 150px"
|
||||
/>
|
||||
<el-button type="primary" @click="handleSearch">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
</div>
|
||||
|
||||
<el-table :data="rows" v-loading="loading" row-key="id" border stripe empty-text="暂无流水记录">
|
||||
<el-table-column label="流水号" width="100">
|
||||
<template #default="{ row }"><span class="mono">#{{ row.id }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="应用" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.appName }}</div>
|
||||
<div class="mono muted small">{{ row.appCode }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="业务用户" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<div class="mono">{{ row.businessUserId }}</div>
|
||||
<div class="muted small">{{ row.usernameSnapshot }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="类型" width="130">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="txTypeMeta(row.type).tag" effect="light">{{ txTypeMeta(row.type).label }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="变动点数" width="110" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="num" :class="signedClass(row)">{{ signedText(row) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="变动前" width="110" align="right">
|
||||
<template #default="{ row }"><span class="num">{{ formatPoints(row.balanceBefore) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="变动后" width="110" align="right">
|
||||
<template #default="{ row }"><span class="num">{{ formatPoints(row.balanceAfter) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="关联单号" min-width="190" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.outTradeNo || row.businessRefId || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="幂等键" min-width="180" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono muted">{{ row.idempotencyKey }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作人" width="130">
|
||||
<template #default="{ row }">{{ row.operatorAdminName || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="备注" min-width="160" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.remark || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page"
|
||||
v-model:page-size="pageSize"
|
||||
background
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
:total="total"
|
||||
@size-change="handleSearch"
|
||||
@current-change="loadTransactions"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.points-in {
|
||||
color: var(--el-color-success);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.points-out {
|
||||
color: var(--el-color-danger);
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,145 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { appApi } from '@/api/core'
|
||||
import { vipApi } from '@/api/settings'
|
||||
import type { AppInfo, VipHolder } from '@/types'
|
||||
import { formatDateTime, remainText } from '@/utils/format'
|
||||
|
||||
const apps = ref<AppInfo[]>([])
|
||||
const rows = ref<VipHolder[]>([])
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
|
||||
const filter = reactive({
|
||||
appCode: '',
|
||||
keyword: '',
|
||||
})
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
try {
|
||||
apps.value = await appApi.list()
|
||||
} catch {
|
||||
apps.value = []
|
||||
}
|
||||
}
|
||||
|
||||
async function loadHolders(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await vipApi.holders({
|
||||
appCode: filter.appCode || undefined,
|
||||
keyword: filter.keyword.trim() || undefined,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
})
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch {
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSearch(): void {
|
||||
page.value = 1
|
||||
void loadHolders()
|
||||
}
|
||||
|
||||
function handleReset(): void {
|
||||
filter.appCode = ''
|
||||
filter.keyword = ''
|
||||
page.value = 1
|
||||
void loadHolders()
|
||||
}
|
||||
|
||||
function handleSizeChange(): void {
|
||||
page.value = 1
|
||||
void loadHolders()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadApps()
|
||||
await loadHolders()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader
|
||||
title="VIP 持有"
|
||||
desc="查询各应用下 VIP 持有情况,有效性与剩余天数为只读展示,权益变更请到「VIP 档位」维护。"
|
||||
/>
|
||||
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<el-select v-model="filter.appCode" placeholder="全部应用" style="width: 180px" @change="handleSearch">
|
||||
<el-option label="全部应用" value="" />
|
||||
<el-option v-for="app in apps" :key="app.appCode" :label="app.appName" :value="app.appCode" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="filter.keyword"
|
||||
placeholder="业务用户ID / 用户名"
|
||||
clearable
|
||||
style="width: 240px"
|
||||
@keyup.enter="handleSearch"
|
||||
/>
|
||||
<el-button type="primary" @click="handleSearch">
|
||||
<el-icon><Search /></el-icon>
|
||||
查询
|
||||
</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
<div class="spacer" />
|
||||
<span class="small muted">共 {{ total }} 条持有记录</span>
|
||||
</div>
|
||||
|
||||
<el-table v-loading="loading" :data="rows" border empty-text="暂无 VIP 持有记录">
|
||||
<el-table-column prop="appName" label="应用" min-width="130" />
|
||||
<el-table-column label="业务用户" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.businessUserId }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="usernameSnapshot" label="用户名" min-width="110">
|
||||
<template #default="{ row }">{{ row.usernameSnapshot || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="档位编码" min-width="130">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.vipPlanCode }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="到期时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.vipUntil) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="是否有效" width="100" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.effective ? 'success' : 'info'" effect="plain">
|
||||
{{ row.effective ? '有效' : '已过期' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="剩余天数" width="140">
|
||||
<template #default="{ row }">
|
||||
<span :class="row.effective ? '' : 'muted'">{{ remainText(row.vipUntil) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="total"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
@current-change="loadHolders"
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,398 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import { appApi } from '@/api/core'
|
||||
import { vipApi } from '@/api/settings'
|
||||
import type { AppInfo, VipPlan } from '@/types'
|
||||
import { centToYuanInput, formatCent, yuanInputToCent } from '@/utils/money'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { askTotp, confirmAction } from '@/utils/confirm'
|
||||
import { userMessage } from '@/utils/http'
|
||||
import type { ApiError } from '@/utils/http'
|
||||
|
||||
interface PlanForm {
|
||||
appCode: string
|
||||
planCode: string
|
||||
planName: string
|
||||
durationDays: number
|
||||
priceYuan: string
|
||||
freeDeduction: number
|
||||
}
|
||||
|
||||
const apps = ref<AppInfo[]>([])
|
||||
const plans = ref<VipPlan[]>([])
|
||||
const appCode = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const pagedPlans = computed(() =>
|
||||
plans.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value),
|
||||
)
|
||||
|
||||
const dialogVisible = ref(false)
|
||||
const editingPlan = ref<VipPlan | null>(null)
|
||||
const submitting = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
const toggleId = ref<number | null>(null)
|
||||
|
||||
const isEdit = computed(() => editingPlan.value !== null)
|
||||
|
||||
const form = reactive<PlanForm>({
|
||||
appCode: '',
|
||||
planCode: '',
|
||||
planName: '',
|
||||
durationDays: 365,
|
||||
priceYuan: '',
|
||||
freeDeduction: 0,
|
||||
})
|
||||
|
||||
function validateDuration(_rule: unknown, value: unknown, callback: (error?: string | Error) => void): void {
|
||||
const days = Number(value)
|
||||
if (!Number.isInteger(days) || days <= 0) {
|
||||
callback(new Error('有效期天数必须为正整数'))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
}
|
||||
|
||||
function validatePrice(_rule: unknown, value: unknown, callback: (error?: string | Error) => void): void {
|
||||
if (yuanInputToCent(String(value ?? '')) === null) {
|
||||
callback(new Error('请输入正确的价格(元,最多两位小数且大于 0)'))
|
||||
return
|
||||
}
|
||||
callback()
|
||||
}
|
||||
|
||||
const planRules: FormRules = {
|
||||
appCode: [{ required: true, message: '请选择应用', trigger: 'change' }],
|
||||
planCode: [
|
||||
{ required: true, message: '请输入档位编码', trigger: 'blur' },
|
||||
{
|
||||
pattern: /^[A-Z][A-Z0-9_]{2,31}$/,
|
||||
message: '需为 3~32 位大写字母、数字或下划线,且以字母开头',
|
||||
trigger: 'blur',
|
||||
},
|
||||
],
|
||||
planName: [
|
||||
{ required: true, message: '请输入档位名称', trigger: 'blur' },
|
||||
{ min: 2, max: 32, message: '档位名称需为 2~32 个字', trigger: 'blur' },
|
||||
],
|
||||
durationDays: [{ validator: validateDuration, trigger: 'change' }],
|
||||
priceYuan: [{ validator: validatePrice, trigger: 'blur' }],
|
||||
}
|
||||
|
||||
async function loadApps(): Promise<void> {
|
||||
try {
|
||||
apps.value = await appApi.list()
|
||||
} catch {
|
||||
apps.value = []
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPlans(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
plans.value = await vipApi.plans(appCode.value || undefined)
|
||||
page.value = 1
|
||||
} catch {
|
||||
plans.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleAppChange(): void {
|
||||
page.value = 1
|
||||
void loadPlans()
|
||||
}
|
||||
|
||||
function handleSizeChange(): void {
|
||||
page.value = 1
|
||||
}
|
||||
|
||||
function openCreate(): void {
|
||||
editingPlan.value = null
|
||||
Object.assign(form, {
|
||||
appCode: appCode.value || apps.value[0]?.appCode || '',
|
||||
planCode: '',
|
||||
planName: '',
|
||||
durationDays: 365,
|
||||
priceYuan: '',
|
||||
freeDeduction: 0,
|
||||
})
|
||||
dialogVisible.value = true
|
||||
void nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function openEdit(row: VipPlan): void {
|
||||
editingPlan.value = row
|
||||
Object.assign(form, {
|
||||
appCode: row.appCode,
|
||||
planCode: row.planCode,
|
||||
planName: row.planName,
|
||||
durationDays: row.durationDays,
|
||||
priceYuan: centToYuanInput(row.priceCent),
|
||||
freeDeduction: row.freeDeduction,
|
||||
})
|
||||
dialogVisible.value = true
|
||||
void nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
async function submitPlan(): Promise<void> {
|
||||
const formEl = formRef.value
|
||||
if (!formEl) return
|
||||
let valid = false
|
||||
try {
|
||||
valid = await formEl.validate()
|
||||
} catch {
|
||||
valid = false
|
||||
}
|
||||
if (!valid) return
|
||||
|
||||
const priceCent = yuanInputToCent(form.priceYuan)
|
||||
if (priceCent === null) {
|
||||
ElMessage.error('请输入正确的价格(元)')
|
||||
return
|
||||
}
|
||||
const durationDays = Number(form.durationDays)
|
||||
if (!Number.isInteger(durationDays) || durationDays <= 0) {
|
||||
ElMessage.error('有效期天数必须为正整数')
|
||||
return
|
||||
}
|
||||
|
||||
if (isEdit.value && editingPlan.value) {
|
||||
const before = editingPlan.value
|
||||
if (priceCent !== before.priceCent) {
|
||||
const confirmed = await confirmAction({
|
||||
title: '确认改价',
|
||||
message: `档位「${before.planName}」价格将由 ${formatCent(before.priceCent)} 调整为 ${formatCent(
|
||||
priceCent,
|
||||
)},改价将写入审计日志,确认继续?`,
|
||||
requireType: '确认改价',
|
||||
confirmText: '确认改价',
|
||||
})
|
||||
if (!confirmed) return
|
||||
}
|
||||
const totp = await askTotp('修改 VIP 档位')
|
||||
if (!totp) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
await vipApi.updatePlan(before.id, {
|
||||
appCode: before.appCode,
|
||||
planName: form.planName.trim(),
|
||||
durationDays,
|
||||
priceCent,
|
||||
freeDeduction: form.freeDeduction,
|
||||
totp,
|
||||
})
|
||||
ElMessage.success('档位已更新')
|
||||
dialogVisible.value = false
|
||||
await loadPlans()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
await vipApi.createPlan({
|
||||
appCode: form.appCode,
|
||||
planCode: form.planCode.trim(),
|
||||
planName: form.planName.trim(),
|
||||
durationDays,
|
||||
priceCent,
|
||||
freeDeduction: form.freeDeduction,
|
||||
})
|
||||
ElMessage.success('档位已创建')
|
||||
dialogVisible.value = false
|
||||
await loadPlans()
|
||||
} catch (error) {
|
||||
ElMessage.error(userMessage(error as ApiError))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function beforeToggle(row: VipPlan): Promise<boolean> {
|
||||
const action = row.enabled === 1 ? '下架' : '上架'
|
||||
return confirmAction({
|
||||
title: `${action} VIP 档位`,
|
||||
message:
|
||||
row.enabled === 1
|
||||
? `确认下架档位「${row.planName}」?下架后收银台不再展示该档位,存量用户权益不受影响。`
|
||||
: `确认上架档位「${row.planName}」?上架后用户可在收银台购买。`,
|
||||
confirmText: `确认${action}`,
|
||||
})
|
||||
}
|
||||
|
||||
async function handleToggle(row: VipPlan, value: string | number | boolean): Promise<void> {
|
||||
const enabled = Number(value) === 1 ? 1 : 0
|
||||
toggleId.value = row.id
|
||||
try {
|
||||
await vipApi.togglePlan(row.id, enabled)
|
||||
ElMessage.success(enabled === 1 ? '档位已上架' : '档位已下架')
|
||||
await loadPlans()
|
||||
} catch {
|
||||
// 非静默接口,错误提示由 http 层统一处理
|
||||
} finally {
|
||||
toggleId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadApps()
|
||||
await loadPlans()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader
|
||||
title="VIP 档位"
|
||||
desc="按应用维护 VIP 档位编码、价格与免扣权益,档位新增、改价与上下架均写入审计日志。"
|
||||
>
|
||||
<el-select
|
||||
v-model="appCode"
|
||||
placeholder="全部应用"
|
||||
style="width: 180px"
|
||||
@change="handleAppChange"
|
||||
>
|
||||
<el-option label="全部应用" value="" />
|
||||
<el-option v-for="app in apps" :key="app.appCode" :label="app.appName" :value="app.appCode" />
|
||||
</el-select>
|
||||
<el-button v-perm="'fin:vip:manage'" type="primary" @click="openCreate">
|
||||
<el-icon><Plus /></el-icon>
|
||||
新建档位
|
||||
</el-button>
|
||||
</PageHeader>
|
||||
|
||||
<div class="notice info" style="margin-bottom: 16px">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
<div>
|
||||
免扣联动说明:档位标记为「免扣费」仅表示该档位享受免扣权益,是否真正免扣还取决于「兑率与策略」中对应应用的
|
||||
VIP 免扣(vipExempt)开关,两处需同时开启才生效。调整档位或策略后,请到「VIP 持有」核对存量用户权益。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<el-table v-loading="loading" :data="pagedPlans" border empty-text="暂无 VIP 档位">
|
||||
<el-table-column prop="appName" label="应用" min-width="130" />
|
||||
<el-table-column label="档位编码" width="150">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.planCode }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="planName" label="档位名称" min-width="150" />
|
||||
<el-table-column label="有效期天数" width="110" align="right">
|
||||
<template #default="{ row }">{{ row.durationDays }} 天</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="价格" width="120" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="money">{{ formatCent(row.priceCent) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="免扣" width="100" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-if="row.freeDeduction === 1" type="success" effect="plain">免扣费</el-tag>
|
||||
<span v-else class="muted">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="90" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-switch
|
||||
v-perm="'fin:vip:manage'"
|
||||
:model-value="row.enabled"
|
||||
:active-value="1"
|
||||
:inactive-value="0"
|
||||
:loading="toggleId === row.id"
|
||||
:before-change="() => beforeToggle(row)"
|
||||
@change="(value: string | number | boolean) => handleToggle(row, value)"
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="持有数" width="90" align="right">
|
||||
<template #default="{ row }">{{ row.holderCount }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="创建时间" width="170">
|
||||
<template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button v-perm="'fin:vip:manage'" link type="primary" @click="openEdit(row)">
|
||||
编辑
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="table-footer">
|
||||
<el-pagination
|
||||
v-model:current-page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="plans.length"
|
||||
:page-sizes="[10, 20, 50]"
|
||||
layout="total, sizes, prev, pager, next"
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-dialog
|
||||
v-model="dialogVisible"
|
||||
:title="isEdit ? '编辑 VIP 档位' : '新建 VIP 档位'"
|
||||
width="540px"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-form ref="formRef" :model="form" :rules="planRules" label-width="110px">
|
||||
<el-form-item label="应用" prop="appCode">
|
||||
<el-select
|
||||
v-model="form.appCode"
|
||||
:disabled="isEdit"
|
||||
placeholder="请选择应用"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option
|
||||
v-for="app in apps"
|
||||
:key="app.appCode"
|
||||
:label="`${app.appName}(${app.appCode})`"
|
||||
:value="app.appCode"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="档位编码" prop="planCode">
|
||||
<el-input
|
||||
v-model="form.planCode"
|
||||
:disabled="isEdit"
|
||||
maxlength="32"
|
||||
placeholder="如 VIP_YEAR"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="档位名称" prop="planName">
|
||||
<el-input v-model="form.planName" maxlength="32" placeholder="如 年度 VIP" />
|
||||
</el-form-item>
|
||||
<el-form-item label="有效期天数" prop="durationDays">
|
||||
<el-input-number v-model="form.durationDays" :min="1" :step="1" :precision="0" />
|
||||
</el-form-item>
|
||||
<el-form-item label="价格(元)" prop="priceYuan">
|
||||
<el-input v-model="form.priceYuan" placeholder="如 199.00">
|
||||
<template #append>元</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="免扣费">
|
||||
<el-switch v-model="form.freeDeduction" :active-value="1" :inactive-value="0" />
|
||||
<span class="small muted" style="margin-left: 10px">开启后该档位用户扣费时免扣点数</span>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="submitPlan">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"jsx": "preserve",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"useDefineForClassFields": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
},
|
||||
"types": ["vite/client", "node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 中央计费平台前端构建配置
|
||||
export default defineConfig({
|
||||
base: './',
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
host: '127.0.0.1',
|
||||
port: 5180,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
// 真实后端联调时把 VITE_USE_MOCK 设为 0
|
||||
'/api': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
sourcemap: false,
|
||||
chunkSizeWarningLimit: 1500,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
vue: ['vue', 'vue-router', 'pinia'],
|
||||
element: ['element-plus', '@element-plus/icons-vue'],
|
||||
charts: ['echarts'],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user