Compare commits

...

4 Commits

Author SHA1 Message Date
a125b5922f 修复 2026-03-08 16:35:17 +08:00
f76af4d01a 优化 2026-03-08 13:59:35 +08:00
69835ae990 feat: 优化 2026-03-08 13:55:10 +08:00
2aa459889a feat: 优化 2026-03-07 23:39:57 +08:00
32 changed files with 2601 additions and 1846 deletions

View File

@@ -1,72 +1,99 @@
<template>
<div class="voice-selector">
<!-- 空状态 -->
<div v-if="userVoiceCards.length === 0" class="empty-voices">
<a-empty :image="simpleImage" description="还没有配音">
<template #image>
<div class="empty-icon">
<svg viewBox="0 0 64 64" fill="none">
<circle cx="32" cy="32" r="28" fill="#f1f5f9" stroke="#e2e8f0" stroke-width="2"/>
<path d="M32 18C36.4183 18 40 21.5817 40 26V38C40 42.4183 36.4183 46 32 46C27.5817 46 24 42.4183 24 38V26C24 21.5817 27.5817 18 32 18Z" fill="#cbd5e1"/>
<path d="M32 14V18M32 46V50M18 32H22M42 32H46" stroke="#94a3b8" stroke-width="2" stroke-linecap="round"/>
</svg>
</div>
</template>
<a-button type="primary" size="small" @click="$router.push('/voice-copy')">
去创建配音
</a-button>
</a-empty>
</div>
<div v-else class="voice-selector-wrapper">
<!-- 选择器卡片 -->
<div class="voice-card" :class="{ 'has-audio': audioUrl }">
<div class="voice-card-header">
<div class="header-icon">
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 14C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10C10.8954 10 10 10.8954 10 12C10 13.1046 10.8954 14 12 14Z" fill="currentColor"/>
<path d="M12 6C14.813 6 17.125 8.156 17.469 10.875C17.5 11.125 17.719 11.313 17.969 11.313H18.031C18.313 11.313 18.531 11.063 18.5 10.781C18.094 7.5 15.344 5 12 5C8.656 5 5.906 7.5 5.5 10.781C5.469 11.063 5.687 11.313 5.969 11.313H6.031C6.281 11.313 6.5 11.125 6.531 10.875C6.875 8.156 9.187 6 12 6Z" fill="currentColor" opacity="0.6"/>
<path d="M12 3C16.5 3 20.188 6.5 20.469 11C20.5 11.25 20.719 11.438 20.969 11.438H21.031C21.313 11.438 21.531 11.188 21.5 10.906C21.156 5.875 17 2 12 2C7 2 2.844 5.875 2.5 10.906C2.469 11.188 2.687 11.438 2.969 11.438H3.031C3.281 11.438 3.5 11.25 3.531 11C3.813 6.5 7.5 3 12 3Z" fill="currentColor" opacity="0.3"/>
</svg>
</div>
<span class="header-title">音色选择</span>
<span v-if="currentVoiceName" class="header-badge">{{ currentVoiceName }}</span>
<!-- 标题栏 -->
<div class="selector-header">
<div class="header-left">
<span class="header-title">选择音色</span>
<span class="voice-count">{{ userVoiceCards.length }} 个配音</span>
</div>
<a-button
v-if="selectedVoiceId"
class="synthesize-btn"
:disabled="isPlayerInitializing"
:loading="previewLoadingVoiceId === selectedVoiceId"
@click="handleSynthesize"
>
<template #icon>
<SoundOutlined />
</template>
合成试听
</a-button>
</div>
<div class="voice-card-body">
<div class="select-wrapper">
<a-select
v-model:value="selectedVoiceId"
placeholder="请选择音色"
class="voice-select"
:options="voiceOptions"
@change="handleVoiceChange"
>
<template #suffixIcon>
<DownOutlined class="select-arrow" />
</template>
</a-select>
<!-- 卡片网格 -->
<div class="voice-grid" :class="{ 'has-many': userVoiceCards.length > 4 }">
<div
v-for="voice in userVoiceCards"
:key="voice.id"
class="voice-card"
:class="{ 'selected': selectedVoiceId === voice.id }"
@click="handleVoiceSelect(voice)"
>
<!-- 头像区域 -->
<div class="card-avatar">
<div class="avatar-ring"></div>
<div class="avatar-icon">
<svg viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="3" fill="currentColor"/>
<path d="M12 2v4M12 18v4M2 12h4M18 12h4" stroke="currentColor" stroke-width="2" stroke-linecap="round" opacity="0.5"/>
<path d="M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" stroke="currentColor" stroke-width="2" stroke-linecap="round" opacity="0.3"/>
</svg>
</div>
<!-- 选中指示器 -->
<div v-if="selectedVoiceId === voice.id" class="selected-indicator">
<CheckOutlined />
</div>
</div>
<a-button
class="synthesize-btn"
:class="{ 'btn-active': selectedVoiceId }"
:disabled="!selectedVoiceId || isPlayerInitializing"
:loading="previewLoadingVoiceId === selectedVoiceId"
@click="handleSynthesize"
>
<template #icon>
<SoundOutlined />
</template>
<span class="btn-text">合成试听</span>
</a-button>
<!-- 信息区域 -->
<div class="card-info">
<div class="voice-name">{{ voice.name }}</div>
<div class="voice-desc">{{ voice.description || '我的配音' }}</div>
</div>
</div>
</div>
<!-- 播放器区域 -->
<transition name="slide-fade">
<div v-if="audioUrl" class="player-section">
<div ref="playerContainer" class="aplayer-container"></div>
<div class="player-actions">
<a-button
type="text"
size="small"
@click="downloadAudio"
class="download-btn"
>
<template #icon>
<DownloadOutlined />
</template>
下载音频
<div class="player-header">
<div class="player-info">
<div class="player-icon">
<svg viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="10" fill="currentColor" opacity="0.1"/>
<path d="M10 8L16 12L10 16V8Z" fill="currentColor"/>
</svg>
</div>
<div class="player-meta">
<div class="player-title">{{ currentVoiceName }}</div>
<div class="player-label">合成预览</div>
</div>
</div>
<a-button type="text" size="small" @click="downloadAudio" class="download-btn">
<template #icon><DownloadOutlined /></template>
下载
</a-button>
</div>
<div ref="playerContainer" class="aplayer-container"></div>
</div>
</transition>
</div>
@@ -76,7 +103,7 @@
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { Empty, message } from 'ant-design-vue'
import { SoundOutlined, DownloadOutlined, DownOutlined } from '@ant-design/icons-vue'
import { SoundOutlined, DownloadOutlined, CheckOutlined } from '@ant-design/icons-vue'
import { useVoiceCopyStore } from '@/stores/voiceCopy'
import { useTTS, TTS_PROVIDERS } from '@/composables/useTTS'
import APlayer from 'aplayer'
@@ -166,17 +193,8 @@ const userVoiceCards = computed(() =>
}))
)
const voiceOptions = computed(() =>
userVoiceCards.value.map(voice => ({
value: voice.id,
label: voice.name,
data: voice
}))
)
const handleVoiceChange = (value, option) => {
const voice = option.data
selectedVoiceId.value = value
const handleVoiceSelect = (voice) => {
selectedVoiceId.value = voice.id
currentVoiceName.value = voice.name
emit('select', voice)
}
@@ -209,7 +227,7 @@ const handlePlayVoiceSample = (voice) => {
if (!url) return
initPlayer(url)
},
undefined, // 错误静默处理
() => { /* 错误已在 useTTS 中处理 */ },
{ autoPlay: false }
)
}
@@ -321,212 +339,292 @@ onBeforeUnmount(() => {
width: 100%;
}
/* 空状态 */
.empty-voices {
padding: 24px 0;
background: var(--color-surface);
border: 1px dashed var(--color-border);
border-radius: 12px;
padding: 40px 24px;
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
border: 1px dashed #e2e8f0;
border-radius: 16px;
text-align: center;
.empty-icon {
margin-bottom: 12px;
svg {
width: 64px;
height: 64px;
}
}
}
/* 主容器 */
.voice-selector-wrapper {
display: flex;
flex-direction: column;
gap: 14px;
gap: 16px;
}
/* 音色卡片 - 柔和风格 */
.voice-card {
background: rgba(59, 130, 246, 0.03);
border: 1px solid rgba(59, 130, 246, 0.1);
border-radius: 10px;
padding: 14px;
transition: all 0.25s ease;
&:hover {
border-color: rgba(59, 130, 246, 0.18);
background: rgba(59, 130, 246, 0.05);
}
&.has-audio {
border-color: rgba(59, 130, 246, 0.2);
background: rgba(59, 130, 246, 0.06);
}
/* 标题栏 */
.selector-header {
display: flex;
align-items: center;
justify-content: space-between;
padding-bottom: 12px;
border-bottom: 1px solid #f1f5f9;
}
/* 卡片头部 */
.voice-card-header {
.header-left {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
}
.header-icon {
width: 26px;
height: 26px;
border-radius: 6px;
background: rgba(59, 130, 246, 0.1);
display: flex;
align-items: center;
justify-content: center;
color: #3b82f6;
svg {
width: 14px;
height: 14px;
}
}
.header-title {
font-size: 13px;
font-weight: 500;
color: var(--color-text);
font-size: 15px;
font-weight: 600;
color: #1e293b;
}
.header-badge {
margin-left: auto;
.voice-count {
font-size: 12px;
color: #94a3b8;
background: #f1f5f9;
padding: 2px 8px;
background: rgba(59, 130, 246, 0.08);
border-radius: 10px;
font-size: 11px;
color: #3b82f6;
}
.synthesize-btn {
height: 34px;
padding: 0 14px;
border-radius: 8px;
border: none;
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
color: white;
font-weight: 500;
max-width: 100px;
font-size: 13px;
box-shadow: 0 2px 8px rgba(59, 130, 246, 0.25);
transition: all 0.2s ease;
&:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(59, 130, 246, 0.35);
}
&:disabled {
background: #94a3b8;
box-shadow: none;
cursor: not-allowed;
transform: none;
}
}
/* 卡片网格 */
.voice-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 12px;
&.has-many {
max-height: 280px;
overflow-y: auto;
padding-right: 4px;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-track {
background: #f1f5f9;
border-radius: 2px;
}
&::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 2px;
}
}
}
/* 音色卡片 */
.voice-card {
position: relative;
background: white;
border: 2px solid #f1f5f9;
border-radius: 14px;
padding: 16px 12px;
cursor: pointer;
transition: all 0.25s ease;
overflow: hidden;
&:hover {
border-color: #e2e8f0;
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
}
&.selected {
border-color: #3b82f6;
background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
box-shadow: 0 4px 16px rgba(59, 130, 246, 0.15);
}
}
/* 头像区域 */
.card-avatar {
position: relative;
width: 48px;
height: 48px;
margin: 0 auto 10px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
.avatar-ring {
background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
}
.avatar-icon {
color: #3b82f6;
}
}
.avatar-ring {
position: absolute;
inset: 0;
border-radius: 50%;
}
.avatar-icon {
position: relative;
z-index: 1;
width: 28px;
height: 28px;
svg {
width: 100%;
height: 100%;
}
}
.selected-indicator {
position: absolute;
top: -4px;
right: -4px;
width: 20px;
height: 20px;
background: #3b82f6;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 10px;
box-shadow: 0 2px 6px rgba(59, 130, 246, 0.4);
animation: scaleIn 0.2s ease;
}
@keyframes scaleIn {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
/* 信息区域 */
.card-info {
text-align: center;
}
.voice-name {
font-size: 13px;
font-weight: 600;
color: #1e293b;
margin-bottom: 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 卡片主体 */
.voice-card-body {
display: flex;
gap: 10px;
align-items: stretch;
}
.select-wrapper {
flex: 1;
:deep(.ant-select) {
width: 100%;
height: 36px;
.ant-select-selector {
height: 36px !important;
border-radius: 8px !important;
border-color: rgba(59, 130, 246, 0.12) !important;
background: rgba(255, 255, 255, 0.9) !important;
transition: all 0.2s ease !important;
&:hover {
border-color: rgba(59, 130, 246, 0.25) !important;
}
}
&.ant-select-focused .ant-select-selector {
border-color: rgba(59, 130, 246, 0.3) !important;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.06) !important;
}
.ant-select-selection-item {
line-height: 34px !important;
font-size: 13px;
}
.ant-select-selection-placeholder {
line-height: 34px !important;
font-size: 13px;
}
}
}
.select-arrow {
.voice-desc {
font-size: 11px;
color: #94a3b8;
transition: transform 0.3s ease;
}
/* 合成按钮 - 柔和风格 */
.synthesize-btn {
height: 36px;
padding: 0 16px;
border-radius: 8px;
border: none;
background: rgba(59, 130, 246, 0.08);
color: #64748b;
font-weight: 500;
display: flex;
align-items: center;
gap: 6px;
transition: all 0.25s ease;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
&:hover:not(:disabled) {
background: rgba(59, 130, 246, 0.12);
color: #475569;
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&.btn-active {
background: rgba(59, 130, 246, 0.15);
color: #3b82f6;
&:hover:not(:disabled) {
background: rgba(59, 130, 246, 0.2);
}
}
.btn-text {
font-size: 13px;
}
}
/* 播放器区域 */
.player-section {
background: rgba(59, 130, 246, 0.03);
border-radius: 10px;
padding: 12px;
border: 1px solid rgba(59, 130, 246, 0.08);
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
border-radius: 14px;
padding: 14px;
border: 1px solid #e2e8f0;
}
.aplayer-container {
:deep(.aplayer) {
border-radius: 8px;
box-shadow: none;
border: 1px solid rgba(0, 0, 0, 0.04);
.player-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.aplayer-body {
border-radius: 8px;
}
.player-info {
display: flex;
align-items: center;
gap: 10px;
}
.player-icon {
width: 36px;
height: 36px;
color: #3b82f6;
svg {
width: 100%;
height: 100%;
}
}
.player-actions {
margin-top: 8px;
display: flex;
justify-content: flex-end;
.player-meta {
.player-title {
font-size: 14px;
font-weight: 600;
color: #1e293b;
}
.player-label {
font-size: 11px;
color: #94a3b8;
}
}
.download-btn {
color: #94a3b8;
color: #64748b;
font-size: 12px;
padding: 4px 8px;
padding: 4px 10px;
height: auto;
border-radius: 6px;
transition: all 0.2s ease;
&:hover {
color: #3b82f6;
background: rgba(59, 130, 246, 0.06);
background: rgba(59, 130, 246, 0.08);
}
}
.aplayer-container {
:deep(.aplayer) {
border-radius: 10px;
box-shadow: none;
border: 1px solid rgba(0, 0, 0, 0.04);
.aplayer-body {
border-radius: 10px;
}
}
}
/* 动画 */
.slide-fade-enter-active {
transition: all 0.25s ease-out;
transition: all 0.3s ease-out;
}
.slide-fade-leave-active {
@@ -534,12 +632,12 @@ onBeforeUnmount(() => {
}
.slide-fade-enter-from {
transform: translateY(-8px);
transform: translateY(-10px);
opacity: 0;
}
.slide-fade-leave-to {
transform: translateY(-8px);
transform: translateY(-10px);
opacity: 0;
}
</style>

View File

@@ -19,7 +19,7 @@ const navConfig = [
group: '数字人',
order: 2,
items: [
{ name: '数字人', path: 'digital-human/kling', icon: 'user', component: () => import('../views/kling/IdentifyFace.vue') },
{ name: '数字人', path: 'digital-human/generate', icon: 'user', component: () => import('../views/kling/IdentifyFace.vue') },
{ name: '人声克隆', path: 'digital-human/voice-copy', icon: 'mic', component: () => import('../views/dh/VoiceCopy.vue') },
]
},

File diff suppressed because it is too large Load Diff

View File

@@ -72,4 +72,11 @@ public interface FileApi {
*/
String getMasterFileDomain();
/**
* 根据OSS URL删除文件
*
* @param ossUrl OSS文件完整URL
*/
void deleteFileByUrl(@NotEmpty(message = "URL 不能为空") String ossUrl);
}

View File

@@ -49,4 +49,13 @@ public class FileApiImpl implements FileApi {
return null;
}
@Override
public void deleteFileByUrl(String ossUrl) {
try {
fileService.deleteFileByUrl(ossUrl);
} catch (Exception e) {
throw new RuntimeException("删除文件失败: " + e.getMessage(), e);
}
}
}

View File

@@ -246,7 +246,7 @@ public class S3FileClient extends AbstractFileClient<S3FileClientConfig> {
.url().toString();
}
// 4. 替换为 CDN 域名
// 4. 替换为 CDN 域名(用户配置了自定义域名时使用)
if (StrUtil.isNotEmpty(config.getDomain())) {
return replaceUrlHost(signedUrl, config.getDomain());
}

View File

@@ -174,7 +174,24 @@ public class DifyClient {
return switch (eventType) {
case "message", "agent_message" -> DifyChatRespVO.message(answer, conversationId);
case "workflow_finished", "message_end" -> DifyChatRespVO.done(conversationId, null);
case "workflow_finished", "message_end" -> {
// 解析 token 使用信息
@SuppressWarnings("unchecked")
Map<String, Object> metadata = (Map<String, Object>) data.get("metadata");
if (metadata != null) {
@SuppressWarnings("unchecked")
Map<String, Object> usage = (Map<String, Object>) metadata.get("usage");
if (usage != null) {
Integer promptTokens = parseTokenCount(usage.get("prompt_tokens"));
Integer completionTokens = parseTokenCount(usage.get("completion_tokens"));
Integer totalTokens = parseTokenCount(usage.get("total_tokens"));
log.debug("[parseSSEEvent] message_end with tokens: prompt={}, completion={}, total={}",
promptTokens, completionTokens, totalTokens);
yield DifyChatRespVO.doneWithTokens(conversationId, null, promptTokens, completionTokens, totalTokens);
}
}
yield DifyChatRespVO.done(conversationId, null);
}
case "error" -> DifyChatRespVO.error(answer);
// chatflow 节点事件,尝试提取内容
case "node_finished" -> {
@@ -273,4 +290,21 @@ public class DifyClient {
.block();
}
/**
* 解析 token 数量(处理 Number 类型)
*/
private Integer parseTokenCount(Object value) {
if (value == null) {
return 0;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return 0;
}
}
}

View File

@@ -49,6 +49,8 @@ public class DifyServiceImpl implements DifyService {
AtomicLong pendingRecordId = new AtomicLong();
// 用于存储会话ID
AtomicReference<String> conversationIdRef = new AtomicReference<>(reqVO.getConversationId());
// 用于存储 token 使用信息
AtomicReference<DifyChatRespVO> tokenUsageRef = new AtomicReference<>();
// Dify 用户标识(固定格式)
String difyUserId = "user-" + userId;
@@ -70,12 +72,13 @@ public class DifyServiceImpl implements DifyService {
// 3. 预检积分
pointsService.checkPoints(userId, config.getConsumePoints());
// 4. 创建预扣记录
// 4. 创建预扣记录(带 serviceCode
Long recordId = pointsService.createPendingDeduct(
userId,
config.getConsumePoints(),
"dify_chat",
reqVO.getAgentId().toString()
reqVO.getAgentId().toString(),
config.getServiceCode()
);
pendingRecordId.set(recordId);
@@ -95,13 +98,29 @@ public class DifyServiceImpl implements DifyService {
if (resp.getConversationId() != null) {
conversationIdRef.set(resp.getConversationId());
}
// 捕获 token 使用信息
if (resp.getTotalTokens() != null && resp.getTotalTokens() > 0) {
tokenUsageRef.set(resp);
}
})
// 7. 流结束时确认扣费
// 7. 流结束时确认扣费(带 token
.doOnComplete(() -> {
if (pendingRecordId.get() > 0) {
try {
pointsService.confirmPendingDeduct(pendingRecordId.get());
log.info("[chatStream] 流结束确认扣费记录ID: {}", pendingRecordId.get());
DifyChatRespVO tokenUsage = tokenUsageRef.get();
if (tokenUsage != null) {
pointsService.confirmPendingDeductWithTokens(
pendingRecordId.get(),
tokenUsage.getInputTokens(),
tokenUsage.getOutputTokens(),
tokenUsage.getTotalTokens()
);
log.info("[chatStream] 流结束确认扣费带token记录ID: {}, tokens: {}",
pendingRecordId.get(), tokenUsage.getTotalTokens());
} else {
pointsService.confirmPendingDeduct(pendingRecordId.get());
log.info("[chatStream] 流结束确认扣费无token记录ID: {}", pendingRecordId.get());
}
} catch (Exception e) {
log.error("[chatStream] 确认扣费失败", e);
}
@@ -133,6 +152,15 @@ public class DifyServiceImpl implements DifyService {
})
// 10. 在最后添加 done 事件
.concatWith(Mono.defer(() -> {
DifyChatRespVO tokenUsage = tokenUsageRef.get();
if (tokenUsage != null) {
return Mono.just(DifyChatRespVO.doneWithTokens(
conversationIdRef.get(), null,
tokenUsage.getInputTokens(),
tokenUsage.getOutputTokens(),
tokenUsage.getTotalTokens()
));
}
return Mono.just(DifyChatRespVO.done(conversationIdRef.get(), null));
}))
.onErrorResume(e -> {
@@ -147,6 +175,8 @@ public class DifyServiceImpl implements DifyService {
AtomicLong pendingRecordId = new AtomicLong();
// 用于存储会话ID
AtomicReference<String> conversationIdRef = new AtomicReference<>("");
// 用于存储 token 使用信息
AtomicReference<DifyChatRespVO> tokenUsageRef = new AtomicReference<>();
// Dify 用户标识(固定格式)
String difyUserId = "user-" + userId;
@@ -168,12 +198,13 @@ public class DifyServiceImpl implements DifyService {
// 3. 预检积分
pointsService.checkPoints(userId, config.getConsumePoints());
// 4. 创建预扣记录
// 4. 创建预扣记录(带 serviceCode
Long recordId = pointsService.createPendingDeduct(
userId,
config.getConsumePoints(),
"forecast_rewrite",
reqVO.getModelType()
reqVO.getModelType(),
config.getServiceCode()
);
pendingRecordId.set(recordId);
@@ -213,13 +244,29 @@ public class DifyServiceImpl implements DifyService {
if (resp.getConversationId() != null) {
conversationIdRef.set(resp.getConversationId());
}
// 捕获 token 使用信息
if (resp.getTotalTokens() != null && resp.getTotalTokens() > 0) {
tokenUsageRef.set(resp);
}
})
// 8. 流结束时确认扣费
// 8. 流结束时确认扣费(带 token
.doOnComplete(() -> {
if (pendingRecordId.get() > 0) {
try {
pointsService.confirmPendingDeduct(pendingRecordId.get());
log.info("[rewriteStream] 流结束确认扣费记录ID: {}", pendingRecordId.get());
DifyChatRespVO tokenUsage = tokenUsageRef.get();
if (tokenUsage != null) {
pointsService.confirmPendingDeductWithTokens(
pendingRecordId.get(),
tokenUsage.getInputTokens(),
tokenUsage.getOutputTokens(),
tokenUsage.getTotalTokens()
);
log.info("[rewriteStream] 流结束确认扣费带token记录ID: {}, tokens: {}",
pendingRecordId.get(), tokenUsage.getTotalTokens());
} else {
pointsService.confirmPendingDeduct(pendingRecordId.get());
log.info("[rewriteStream] 流结束确认扣费无token记录ID: {}", pendingRecordId.get());
}
} catch (Exception e) {
log.error("[rewriteStream] 确认扣费失败", e);
}
@@ -250,6 +297,15 @@ public class DifyServiceImpl implements DifyService {
})
// 11. 在最后添加 done 事件
.concatWith(Mono.defer(() -> {
DifyChatRespVO tokenUsage = tokenUsageRef.get();
if (tokenUsage != null) {
return Mono.just(DifyChatRespVO.doneWithTokens(
conversationIdRef.get(), null,
tokenUsage.getInputTokens(),
tokenUsage.getOutputTokens(),
tokenUsage.getTotalTokens()
));
}
return Mono.just(DifyChatRespVO.done(conversationIdRef.get(), null));
}))
.onErrorResume(e -> {

View File

@@ -31,6 +31,15 @@ public class DifyChatRespVO {
@Schema(description = "错误信息")
private String errorMessage;
@Schema(description = "输入token数")
private Integer inputTokens;
@Schema(description = "输出token数")
private Integer outputTokens;
@Schema(description = "总token数")
private Integer totalTokens;
/** 事件类型常量 */
public static final String EVENT_MESSAGE = "message";
public static final String EVENT_DONE = "done";
@@ -52,6 +61,18 @@ public class DifyChatRespVO {
.build();
}
public static DifyChatRespVO doneWithTokens(String conversationId, Integer consumePoints,
Integer inputTokens, Integer outputTokens, Integer totalTokens) {
return DifyChatRespVO.builder()
.event(EVENT_DONE)
.conversationId(conversationId)
.consumePoints(consumePoints)
.inputTokens(inputTokens)
.outputTokens(outputTokens)
.totalTokens(totalTokens)
.build();
}
public static DifyChatRespVO error(String errorMessage) {
return DifyChatRespVO.builder()
.event(EVENT_ERROR)

View File

@@ -274,9 +274,11 @@ public class TikUserFileServiceImpl implements TikUserFileService {
vo.setThumbnailUrl(thumbnailUrl);
// 图片封面URL优先缩略图否则原图
vo.setImgUrl(isImage
? (thumbnailUrl != null ? thumbnailUrl : getCachedPresignUrl(file.getFileUrl(), PRESIGN_URL_EXPIRATION_SECONDS))
: null);
if (isImage) {
vo.setImgUrl(thumbnailUrl != null
? thumbnailUrl
: getCachedPresignUrl(file.getFileUrl(), PRESIGN_URL_EXPIRATION_SECONDS));
}
return vo;
});
@@ -329,27 +331,30 @@ public class TikUserFileServiceImpl implements TikUserFileService {
public String getVideoPlayUrl(Long fileId) {
TikUserFileDO file = getUserFile(fileId);
if (StrUtil.isBlank(file.getFileUrl())) {
throw exception(FILE_NOT_EXISTS, "文件URL为空");
if (StrUtil.isBlank(file.getFilePath())) {
throw exception(FILE_NOT_EXISTS, "文件路径为空");
}
if (!StrUtil.containsIgnoreCase(file.getFileType(), "video")) {
throw exception(FILE_CATEGORY_INVALID, "文件不是视频类型");
}
// 视频播放URL不缓存每次都生成新的签名URL
return fileApi.presignGetUrl(file.getFileUrl(), PRESIGN_URL_EXPIRATION_SECONDS);
// 视频播放URL不缓存每次都生成新的签名URL(使用 filePath 而非 fileUrl避免域名匹配问题
return fileApi.presignGetUrl(file.getFilePath(), PRESIGN_URL_EXPIRATION_SECONDS);
}
@Override
public String getAudioPlayUrl(Long fileId) {
TikUserFileDO file = getUserFile(fileId);
if (StrUtil.isBlank(file.getFilePath())) {
throw exception(FILE_NOT_EXISTS, "文件路径为空");
}
if (!StrUtil.containsIgnoreCase(file.getFileType(), "audio")) {
throw exception(FILE_CATEGORY_INVALID, "文件不是音频类型");
}
// 音频播放URL不缓存每次都生成新的签名URL
return fileApi.presignGetUrl(file.getFileUrl(), PRESIGN_URL_EXPIRATION_SECONDS);
// 音频播放URL不缓存每次都生成新的签名URL(使用 filePath 而非 fileUrl避免域名匹配问题
return fileApi.presignGetUrl(file.getFilePath(), PRESIGN_URL_EXPIRATION_SECONDS);
}
@Override

View File

@@ -6,7 +6,7 @@ import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import com.alibaba.ttl.TtlRunnable;
import cn.iocoder.yudao.module.tik.mix.client.IceClient;
import cn.iocoder.yudao.module.tik.mix.constants.MixTaskConstants;
@@ -45,7 +45,7 @@ public class MixTaskServiceImpl implements MixTaskService {
private final IceClient iceClient;
@Resource
private FileService fileService;
private FileApi fileApi;
@Override
@Transactional(rollbackFor = Exception.class)
@@ -115,7 +115,7 @@ public class MixTaskServiceImpl implements MixTaskService {
log.info("[MixTask][删除OSS文件] taskId={}, fileCount={}", id, outputUrls.size());
for (String url : outputUrls) {
try {
fileService.deleteFileByUrl(url);
fileApi.deleteFileByUrl(url);
} catch (Exception e) {
log.error("[MixTask][删除单个OSS文件失败] taskId={}, url={}", id, url, e);
}
@@ -432,7 +432,7 @@ public class MixTaskServiceImpl implements MixTaskService {
return null;
}
// 使用FileService生成签名URL
return fileService.presignGetUrl(ossUrl, expirationSeconds);
return fileApi.presignGetUrl(ossUrl, expirationSeconds);
} catch (Exception e) {
log.error("[MixTask][生成签名URL失败] url={}", ossUrl, e);
return null;

View File

@@ -0,0 +1,74 @@
package cn.iocoder.yudao.module.tik.muye.aiusagestats.controller;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.tik.muye.aiusagestats.service.AiUsageStatsService;
import cn.iocoder.yudao.module.tik.muye.aiusagestats.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
/**
* AI 使用统计 Controller
*/
@Tag(name = "管理后台 - AI 使用统计")
@RestController
@RequestMapping("/admin-api/muye/ai-usage-stats")
@Validated
public class AiUsageStatsController {
@Resource
private AiUsageStatsService aiUsageStatsService;
@GetMapping("/overview")
@Operation(summary = "获取概览统计")
public CommonResult<AiUsageOverviewRespVO> getOverview(
@Parameter(description = "开始时间") @RequestParam(required = false)
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime startTime,
@Parameter(description = "结束时间") @RequestParam(required = false)
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime endTime,
@Parameter(description = "业务类型") @RequestParam(required = false) String bizType) {
return success(aiUsageStatsService.getOverview(startTime, endTime, bizType));
}
@GetMapping("/user-stats")
@Operation(summary = "获取用户统计分页")
public CommonResult<PageResult<AiUsageUserStatsRespVO>> getUserStatsPage(@Valid AiUsageStatsPageReqVO reqVO) {
return success(aiUsageStatsService.getUserStatsPage(reqVO));
}
@GetMapping("/app-stats")
@Operation(summary = "获取应用统计列表")
public CommonResult<List<AiUsageAppStatsRespVO>> getAppStats(
@Parameter(description = "开始时间") @RequestParam(required = false)
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime startTime,
@Parameter(description = "结束时间") @RequestParam(required = false)
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime endTime,
@Parameter(description = "业务类型") @RequestParam(required = false) String bizType) {
return success(aiUsageStatsService.getAppStats(startTime, endTime, bizType));
}
@GetMapping("/trend")
@Operation(summary = "获取趋势数据")
public CommonResult<AiUsageTrendRespVO> getTrend(
@Parameter(description = "开始时间") @RequestParam(required = false)
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime startTime,
@Parameter(description = "结束时间") @RequestParam(required = false)
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime endTime,
@Parameter(description = "业务类型") @RequestParam(required = false) String bizType,
@Parameter(description = "类型day-按天hour-按小时)") @RequestParam(defaultValue = "day") String type) {
return success(aiUsageStatsService.getTrend(startTime, endTime, bizType, type));
}
}

View File

@@ -0,0 +1,66 @@
package cn.iocoder.yudao.module.tik.muye.aiusagestats.service;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.tik.muye.aiusagestats.vo.*;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import java.util.List;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
/**
* AI 使用统计 Service 接口
*/
public interface AiUsageStatsService {
/**
* 获取概览统计
*
* @param startTime 开始时间
* @param endTime 结束时间
* @param bizType 业务类型(可选)
* @return 概览统计
*/
AiUsageOverviewRespVO getOverview(
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime startTime,
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime endTime,
String bizType);
/**
* 获取用户统计分页
*
* @param reqVO 查询条件
* @return 用户统计分页
*/
PageResult<AiUsageUserStatsRespVO> getUserStatsPage(AiUsageStatsPageReqVO reqVO);
/**
* 获取应用统计列表
*
* @param startTime 开始时间
* @param endTime 结束时间
* @param bizType 业务类型(可选)
* @return 应用统计列表
*/
List<AiUsageAppStatsRespVO> getAppStats(
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime startTime,
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime endTime,
String bizType);
/**
* 获取趋势数据
*
* @param startTime 开始时间
* @param endTime 结束时间
* @param bizType 业务类型(可选)
* @param type 类型day-按天hour-按小时)
* @return 趋势数据
*/
AiUsageTrendRespVO getTrend(
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime startTime,
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime endTime,
String bizType,
String type);
}

View File

@@ -0,0 +1,231 @@
package cn.iocoder.yudao.module.tik.muye.aiusagestats.service;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.tik.muye.aiusagestats.vo.*;
import cn.iocoder.yudao.module.tik.muye.aiserviceconfig.dal.AiServiceConfigDO;
import cn.iocoder.yudao.module.tik.muye.aiserviceconfig.mapper.AiServiceConfigMapper;
import cn.iocoder.yudao.module.tik.muye.pointrecord.mapper.PointRecordMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
/**
* AI 使用统计 Service 实现类
*/
@Service
@Validated
@Slf4j
public class AiUsageStatsServiceImpl implements AiUsageStatsService {
@Resource
private PointRecordMapper pointRecordMapper;
@Resource
private AiServiceConfigMapper aiServiceConfigMapper;
/**
* 业务类型名称映射
*/
private static final Map<String, String> BIZ_TYPE_NAMES = Map.of(
"dify_chat", "AI对话",
"forecast_rewrite", "文案改写",
"voice_tts", "语音合成",
"digital_human", "数字人",
"tikhub_fetch", "TikHub获取",
"signin", "签到",
"recharge", "充值",
"exchange", "兑换",
"admin", "后台调整",
"gift", "礼包赠送"
);
@Override
public AiUsageOverviewRespVO getOverview(LocalDateTime startTime, LocalDateTime endTime, String bizType) {
// 查询业务类型统计
List<Map<String, Object>> bizTypeStatsList = pointRecordMapper.selectBizTypeStats(startTime, endTime);
// 计算汇总数据
long totalCallCount = 0;
long totalConsumePoints = 0;
long totalTokens = 0;
List<AiUsageOverviewRespVO.BizTypeStats> bizTypeStats = new ArrayList<>();
for (Map<String, Object> stats : bizTypeStatsList) {
String bt = (String) stats.get("bizType");
// 如果指定了业务类型,只统计该类型
if (bizType != null && !bizType.isEmpty() && !bizType.equals(bt)) {
continue;
}
long callCount = getLongValue(stats, "callCount");
long consumePoints = getLongValue(stats, "consumePoints");
long tokens = getLongValue(stats, "totalTokens");
totalCallCount += callCount;
totalConsumePoints += consumePoints;
totalTokens += tokens;
bizTypeStats.add(AiUsageOverviewRespVO.BizTypeStats.builder()
.bizType(bt)
.bizTypeName(BIZ_TYPE_NAMES.getOrDefault(bt, bt))
.callCount(callCount)
.consumePoints(consumePoints)
.totalTokens(tokens)
.build());
}
// 查询活跃用户数
Long activeUserCount = pointRecordMapper.selectActiveUserCount(startTime, endTime, bizType);
return AiUsageOverviewRespVO.builder()
.totalCallCount(totalCallCount)
.totalConsumePoints(totalConsumePoints)
.totalTokens(totalTokens)
.activeUserCount(activeUserCount)
.bizTypeStats(bizTypeStats)
.build();
}
@Override
public PageResult<AiUsageUserStatsRespVO> getUserStatsPage(AiUsageStatsPageReqVO reqVO) {
// 查询用户统计数据
List<Map<String, Object>> userStatsList = pointRecordMapper.selectUserStats(
reqVO.getStartTime(), reqVO.getEndTime(), reqVO.getBizType(), reqVO.getUserId(), reqVO.getMobile());
// 计算总数
long total = userStatsList.size();
// 分页处理
int fromIndex = (reqVO.getPageNo() - 1) * reqVO.getPageSize();
int toIndex = Math.min(fromIndex + reqVO.getPageSize(), userStatsList.size());
if (fromIndex >= userStatsList.size()) {
return new PageResult<>(Collections.emptyList(), total);
}
List<Map<String, Object>> pagedList = userStatsList.subList(fromIndex, toIndex);
// 转换为 VO
List<AiUsageUserStatsRespVO> list = pagedList.stream()
.map(this::convertToUserStatsVO)
.collect(Collectors.toList());
return new PageResult<>(list, total);
}
@Override
public List<AiUsageAppStatsRespVO> getAppStats(LocalDateTime startTime, LocalDateTime endTime, String bizType) {
// 查询应用统计数据
List<Map<String, Object>> appStatsList = pointRecordMapper.selectAppStats(
startTime, endTime, bizType);
// 获取服务配置信息
Map<String, AiServiceConfigDO> configMap = aiServiceConfigMapper.selectList(
new LambdaQueryWrapperX<AiServiceConfigDO>().eq(AiServiceConfigDO::getStatus, 1))
.stream()
.collect(Collectors.toMap(AiServiceConfigDO::getServiceCode, c -> c, (a, b) -> a));
// 转换为 VO
return appStatsList.stream()
.map(stats -> convertToAppStatsVO(stats, configMap))
.collect(Collectors.toList());
}
@Override
public AiUsageTrendRespVO getTrend(LocalDateTime startTime, LocalDateTime endTime, String bizType, String type) {
// 查询趋势数据
List<Map<String, Object>> trendList = pointRecordMapper.selectTrend(
startTime, endTime, bizType, "day".equals(type) ? "%Y-%m-%d" : "%Y-%m-%d %H:00");
// 转换为 VO
List<AiUsageTrendRespVO.TrendItem> items = trendList.stream()
.map(this::convertToTrendItem)
.collect(Collectors.toList());
return AiUsageTrendRespVO.builder()
.trendList(items)
.build();
}
/**
* 转换为用户统计 VO
*/
private AiUsageUserStatsRespVO convertToUserStatsVO(Map<String, Object> stats) {
Long callCount = getLongValue(stats, "callCount");
Long consumePoints = getLongValue(stats, "consumePoints");
return AiUsageUserStatsRespVO.builder()
.userId(getLongValue(stats, "userId"))
.mobile((String) stats.get("mobile"))
.callCount(callCount)
.consumePoints(consumePoints)
.inputTokens(getLongValue(stats, "inputTokens"))
.outputTokens(getLongValue(stats, "outputTokens"))
.totalTokens(getLongValue(stats, "totalTokens"))
.avgPointsPerCall(callCount > 0 ? (double) consumePoints / callCount : 0.0)
.build();
}
/**
* 转换为应用统计 VO
*/
private AiUsageAppStatsRespVO convertToAppStatsVO(Map<String, Object> stats,
Map<String, AiServiceConfigDO> configMap) {
String serviceCode = (String) stats.get("serviceCode");
Long callCount = getLongValue(stats, "callCount");
Long consumePoints = getLongValue(stats, "consumePoints");
Long totalTokens = getLongValue(stats, "totalTokens");
AiServiceConfigDO config = configMap.get(serviceCode);
return AiUsageAppStatsRespVO.builder()
.serviceCode(serviceCode)
.serviceName(config != null ? config.getServiceName() : serviceCode)
.platform(config != null ? config.getPlatform() : "")
.callCount(callCount)
.consumePoints(consumePoints)
.inputTokens(getLongValue(stats, "inputTokens"))
.outputTokens(getLongValue(stats, "outputTokens"))
.totalTokens(totalTokens)
.avgPointsPerCall(callCount > 0 ? (double) consumePoints / callCount : 0.0)
.avgTokensPerCall(callCount > 0 ? (double) totalTokens / callCount : 0.0)
.build();
}
/**
* 转换为趋势数据项
*/
private AiUsageTrendRespVO.TrendItem convertToTrendItem(Map<String, Object> stats) {
return AiUsageTrendRespVO.TrendItem.builder()
.time((String) stats.get("time"))
.callCount(getLongValue(stats, "callCount"))
.consumePoints(getLongValue(stats, "consumePoints"))
.totalTokens(getLongValue(stats, "totalTokens"))
.build();
}
/**
* 安全获取 Long 值
*/
private Long getLongValue(Map<String, Object> map, String key) {
Object value = map.get(key);
if (value == null) {
return 0L;
}
if (value instanceof Number) {
return ((Number) value).longValue();
}
try {
return Long.parseLong(value.toString());
} catch (NumberFormatException e) {
return 0L;
}
}
}

View File

@@ -0,0 +1,49 @@
package cn.iocoder.yudao.module.tik.muye.aiusagestats.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* AI 使用应用统计响应 VO
*/
@Schema(description = "AI 使用应用统计响应")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AiUsageAppStatsRespVO {
@Schema(description = "服务标识")
private String serviceCode;
@Schema(description = "服务名称")
private String serviceName;
@Schema(description = "平台")
private String platform;
@Schema(description = "调用次数")
private Long callCount;
@Schema(description = "消耗积分")
private Long consumePoints;
@Schema(description = "输入 Token 数")
private Long inputTokens;
@Schema(description = "输出 Token 数")
private Long outputTokens;
@Schema(description = "总 Token 数")
private Long totalTokens;
@Schema(description = "平均每次消耗积分")
private Double avgPointsPerCall;
@Schema(description = "平均每次 Token 数")
private Double avgTokensPerCall;
}

View File

@@ -0,0 +1,60 @@
package cn.iocoder.yudao.module.tik.muye.aiusagestats.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* AI 使用概览统计响应 VO
*/
@Schema(description = "AI 使用概览统计响应")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AiUsageOverviewRespVO {
@Schema(description = "总调用次数")
private Long totalCallCount;
@Schema(description = "总消耗积分")
private Long totalConsumePoints;
@Schema(description = "总 Token 数")
private Long totalTokens;
@Schema(description = "活跃用户数")
private Long activeUserCount;
@Schema(description = "业务类型统计列表")
private List<BizTypeStats> bizTypeStats;
/**
* 业务类型统计
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class BizTypeStats {
@Schema(description = "业务类型")
private String bizType;
@Schema(description = "业务类型名称")
private String bizTypeName;
@Schema(description = "调用次数")
private Long callCount;
@Schema(description = "消耗积分")
private Long consumePoints;
@Schema(description = "Token 数")
private Long totalTokens;
}
}

View File

@@ -0,0 +1,43 @@
package cn.iocoder.yudao.module.tik.muye.aiusagestats.vo;
import cn.iocoder.yudao.framework.common.pojo.SortablePageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
/**
* AI 使用统计查询请求 VO
*/
@Schema(description = "AI 使用统计查询请求")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class AiUsageStatsPageReqVO extends SortablePageParam {
@Schema(description = "开始时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime startTime;
@Schema(description = "结束时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime endTime;
@Schema(description = "业务类型")
private String bizType;
@Schema(description = "用户ID")
private Long userId;
@Schema(description = "手机号")
private String mobile;
@Schema(description = "服务标识")
private String serviceCode;
}

View File

@@ -0,0 +1,45 @@
package cn.iocoder.yudao.module.tik.muye.aiusagestats.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* AI 使用趋势统计响应 VO
*/
@Schema(description = "AI 使用趋势统计响应")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AiUsageTrendRespVO {
@Schema(description = "趋势数据列表")
private List<TrendItem> trendList;
/**
* 趋势数据项
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class TrendItem {
@Schema(description = "时间(日期或小时)")
private String time;
@Schema(description = "调用次数")
private Long callCount;
@Schema(description = "消耗积分")
private Long consumePoints;
@Schema(description = "Token 数")
private Long totalTokens;
}
}

View File

@@ -0,0 +1,43 @@
package cn.iocoder.yudao.module.tik.muye.aiusagestats.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* AI 使用用户统计响应 VO
*/
@Schema(description = "AI 使用用户统计响应")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AiUsageUserStatsRespVO {
@Schema(description = "用户ID")
private Long userId;
@Schema(description = "手机号")
private String mobile;
@Schema(description = "调用次数")
private Long callCount;
@Schema(description = "消耗积分")
private Long consumePoints;
@Schema(description = "输入 Token 数")
private Long inputTokens;
@Schema(description = "输出 Token 数")
private Long outputTokens;
@Schema(description = "总 Token 数")
private Long totalTokens;
@Schema(description = "平均每次消耗积分")
private Double avgPointsPerCall;
}

View File

@@ -1,6 +1,5 @@
package cn.iocoder.yudao.module.tik.muye.memberuserprofile.service;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
@@ -8,14 +7,15 @@ import cn.iocoder.yudao.module.tik.muye.memberuserprofile.dal.MemberUserProfileD
import cn.iocoder.yudao.module.tik.muye.memberuserprofile.mapper.MemberUserProfileMapper;
import cn.iocoder.yudao.module.tik.muye.memberuserprofile.vo.MemberUserProfilePageReqVO;
import cn.iocoder.yudao.module.tik.muye.memberuserprofile.vo.MemberUserProfileSaveReqVO;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import java.time.LocalDateTime;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.time.LocalDateTime;
import java.util.List;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
@@ -96,11 +96,7 @@ public class MemberUserProfileServiceImpl implements MemberUserProfileService {
profile.setUserId(String.valueOf(userId));
// 获取用户手机号
MemberUserRespDTO user = memberUserApi.getUser(userId);
if (user != null) {
profile.setMobile(user.getMobile());
} else {
profile.setMobile("");
}
profile.setMobile(user != null ? user.getMobile() : "");
profile.setRegisterTime(LocalDateTime.now());
profile.setLastLoginTime(LocalDateTime.now());
profile.setTotalPoints(0);
@@ -136,28 +132,24 @@ public class MemberUserProfileServiceImpl implements MemberUserProfileService {
@Override
public boolean increaseUsedStorage(String userId, long fileSizeBytes) {
// 确保档案存在(兼容旧用户)
createIfAbsent(Long.parseLong(userId));
// 将字节转换为GB保留6位小数
BigDecimal storageGb = new BigDecimal(fileSizeBytes).divide(GB_TO_BYTES, 6, RoundingMode.HALF_UP);
String storageGbStr = storageGb.toPlainString();
int affectedRows = memberUserProfileMapper.updateStorageIncrease(userId, storageGbStr);
return affectedRows > 0;
String storageGbStr = convertBytesToGb(fileSizeBytes);
return memberUserProfileMapper.updateStorageIncrease(userId, storageGbStr) > 0;
}
@Override
public boolean decreaseUsedStorage(String userId, long fileSizeBytes) {
// 确保档案存在(兼容旧用户)
createIfAbsent(Long.parseLong(userId));
String storageGbStr = convertBytesToGb(fileSizeBytes);
return memberUserProfileMapper.updateStorageDecrease(userId, storageGbStr) > 0;
}
// 将字节转换为GB保留6位小数
/**
* 将字节转换为GB字符串
*/
private String convertBytesToGb(long fileSizeBytes) {
BigDecimal storageGb = new BigDecimal(fileSizeBytes).divide(GB_TO_BYTES, 6, RoundingMode.HALF_UP);
String storageGbStr = storageGb.toPlainString();
int affectedRows = memberUserProfileMapper.updateStorageDecrease(userId, storageGbStr);
return affectedRows > 0;
return storageGb.toPlainString();
}
@Override

View File

@@ -64,5 +64,21 @@ public class PointRecordDO extends BaseDO {
* 状态pending-预扣 confirmed-已确认 canceled-已取消
*/
private String status;
/**
* AI服务标识(对应muye_ai_service_config.service_code)
*/
private String serviceCode;
/**
* 输入token数
*/
private Integer inputTokens;
/**
* 输出token数
*/
private Integer outputTokens;
/**
* 总token数
*/
private Integer totalTokens;
}

View File

@@ -1,5 +1,6 @@
package cn.iocoder.yudao.module.tik.muye.pointrecord.mapper;
import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
@@ -8,6 +9,8 @@ import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.tik.muye.pointrecord.dal.PointRecordDO;
import cn.iocoder.yudao.module.tik.muye.pointrecord.vo.PointRecordPageReqVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
/**
@@ -41,4 +44,106 @@ public interface PointRecordMapper extends BaseMapperX<PointRecordDO> {
"WHERE status = 'pending' AND create_time < DATE_SUB(NOW(), INTERVAL 30 MINUTE)")
int cancelExpiredPendingRecords();
}
/**
* 按业务类型统计
*/
@Select("<script>" +
"SELECT biz_type AS bizType, " +
" COUNT(*) AS callCount, " +
" SUM(ABS(point_amount)) AS consumePoints, " +
" SUM(COALESCE(total_tokens, 0)) AS totalTokens " +
"FROM muye_point_record " +
"WHERE status = 'confirmed' AND type = 'decrease' " +
"<if test='startTime != null'> AND create_time &gt;= #{startTime}</if>" +
"<if test='endTime != null'> AND create_time &lt;= #{endTime}</if>" +
"GROUP BY biz_type " +
"ORDER BY consumePoints DESC" +
"</script>")
List<Map<String, Object>> selectBizTypeStats(@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
/**
* 按用户统计
*/
@Select("<script>" +
"SELECT user_id AS userId, mobile, " +
" COUNT(*) AS callCount, " +
" SUM(ABS(point_amount)) AS consumePoints, " +
" SUM(COALESCE(input_tokens, 0)) AS inputTokens, " +
" SUM(COALESCE(output_tokens, 0)) AS outputTokens, " +
" SUM(COALESCE(total_tokens, 0)) AS totalTokens " +
"FROM muye_point_record " +
"WHERE status = 'confirmed' AND type = 'decrease' " +
"<if test='startTime != null'> AND create_time &gt;= #{startTime}</if>" +
"<if test='endTime != null'> AND create_time &lt;= #{endTime}</if>" +
"<if test='bizType != null and bizType != \"\"'> AND biz_type = #{bizType}</if>" +
"<if test='userId != null'> AND user_id = #{userId}</if>" +
"<if test='mobile != null and mobile != \"\"'> AND mobile LIKE CONCAT('%', #{mobile}, '%')</if>" +
"GROUP BY user_id, mobile " +
"ORDER BY consumePoints DESC" +
"</script>")
List<Map<String, Object>> selectUserStats(@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime,
@Param("bizType") String bizType,
@Param("userId") Long userId,
@Param("mobile") String mobile);
/**
* 按应用统计
*/
@Select("<script>" +
"SELECT service_code AS serviceCode, " +
" COUNT(*) AS callCount, " +
" SUM(ABS(point_amount)) AS consumePoints, " +
" SUM(COALESCE(input_tokens, 0)) AS inputTokens, " +
" SUM(COALESCE(output_tokens, 0)) AS outputTokens, " +
" SUM(COALESCE(total_tokens, 0)) AS totalTokens " +
"FROM muye_point_record " +
"WHERE status = 'confirmed' AND type = 'decrease' AND service_code IS NOT NULL AND service_code != '' " +
"<if test='startTime != null'> AND create_time &gt;= #{startTime}</if>" +
"<if test='endTime != null'> AND create_time &lt;= #{endTime}</if>" +
"<if test='bizType != null and bizType != \"\"'> AND biz_type = #{bizType}</if>" +
"GROUP BY service_code " +
"ORDER BY consumePoints DESC" +
"</script>")
List<Map<String, Object>> selectAppStats(@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime,
@Param("bizType") String bizType);
/**
* 按时间趋势统计
*/
@Select("<script>" +
"SELECT DATE_FORMAT(create_time, #{dateFormat}) AS time, " +
" COUNT(*) AS callCount, " +
" SUM(ABS(point_amount)) AS consumePoints, " +
" SUM(COALESCE(total_tokens, 0)) AS totalTokens " +
"FROM muye_point_record " +
"WHERE status = 'confirmed' AND type = 'decrease' " +
"<if test='startTime != null'> AND create_time &gt;= #{startTime}</if>" +
"<if test='endTime != null'> AND create_time &lt;= #{endTime}</if>" +
"<if test='bizType != null and bizType != \"\"'> AND biz_type = #{bizType}</if>" +
"GROUP BY DATE_FORMAT(create_time, #{dateFormat}) " +
"ORDER BY time ASC" +
"</script>")
List<Map<String, Object>> selectTrend(@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime,
@Param("bizType") String bizType,
@Param("dateFormat") String dateFormat);
/**
* 统计活跃用户数(去重)
*/
@Select("<script>" +
"SELECT COUNT(DISTINCT user_id) " +
"FROM muye_point_record " +
"WHERE status = 'confirmed' AND type = 'decrease' " +
"<if test='startTime != null'> AND create_time &gt;= #{startTime}</if>" +
"<if test='endTime != null'> AND create_time &lt;= #{endTime}</if>" +
"<if test='bizType != null and bizType != \"\"'> AND biz_type = #{bizType}</if>" +
"</script>")
Long selectActiveUserCount(@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime,
@Param("bizType") String bizType);
}

View File

@@ -56,6 +56,22 @@ public class PointRecordRespVO {
@ExcelProperty("状态")
private String status;
@Schema(description = "服务标识", example = "writing_pro")
@ExcelProperty("服务标识")
private String serviceCode;
@Schema(description = "输入Token数")
@ExcelProperty("输入Token数")
private Integer inputTokens;
@Schema(description = "输出Token数")
@ExcelProperty("输出Token数")
private Integer outputTokens;
@Schema(description = "总Token数")
@ExcelProperty("总Token数")
private Integer totalTokens;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
@ExcelProperty("创建时间")
private LocalDateTime createTime;

View File

@@ -66,4 +66,26 @@ public interface PointsService {
*/
void cancelPendingDeduct(Long recordId);
/**
* 创建预扣(带服务标识)
*
* @param userId 用户ID
* @param points 预扣积分数量
* @param bizType 业务类型
* @param bizId 业务关联ID
* @param serviceCode AI服务标识
* @return 预扣记录ID
*/
Long createPendingDeduct(String userId, Integer points, String bizType, String bizId, String serviceCode);
/**
* 确认预扣并更新 token 信息
*
* @param recordId 预扣记录ID
* @param inputTokens 输入token数
* @param outputTokens 输出token数
* @param totalTokens 总token数
*/
void confirmPendingDeductWithTokens(Long recordId, Integer inputTokens, Integer outputTokens, Integer totalTokens);
}

View File

@@ -191,4 +191,81 @@ public class PointsServiceImpl implements PointsService {
recordId, record.getUserId(), Math.abs(record.getPointAmount()));
}
@Override
@Transactional(rollbackFor = Exception.class)
public Long createPendingDeduct(String userId, Integer points, String bizType, String bizId, String serviceCode) {
// 1. 预检积分
checkPoints(userId, points);
// 2. 查询当前余额
MemberUserProfileDO profile = memberUserProfileMapper.selectByUserId(userId);
// 2.1 获取用户手机号
MemberUserDO user = memberUserService.getUser(Long.parseLong(userId));
String mobile = user != null ? user.getMobile() : "";
// 3. 创建预扣记录(待确认状态)
PointRecordDO record = PointRecordDO.builder()
.userId(Long.parseLong(userId))
.mobile(mobile)
.type("decrease")
.pointAmount(-points)
.balance(profile.getRemainingPoints())
.reason(bizType + "(预扣)")
.bizType(bizType)
.bizId(bizId != null ? bizId : UUID.randomUUID().toString())
.serviceCode(serviceCode)
.inputTokens(0)
.outputTokens(0)
.totalTokens(0)
.status(STATUS_PENDING)
.build();
pointRecordMapper.insert(record);
log.info("[createPendingDeduct] 用户 {} 创建预扣 {} 积分,业务类型 {},服务标识 {}记录ID {}",
userId, points, bizType, serviceCode, record.getId());
return record.getId();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void confirmPendingDeductWithTokens(Long recordId, Integer inputTokens, Integer outputTokens, Integer totalTokens) {
// 1. 查询预扣记录
PointRecordDO record = pointRecordMapper.selectById(recordId);
if (record == null) {
throw exception(POINTS_PENDING_NOT_FOUND);
}
// 2. 校验状态
if (!STATUS_PENDING.equals(record.getStatus())) {
throw exception(POINTS_PENDING_ALREADY_CONFIRMED);
}
// 3. 获取扣减信息
String userId = record.getUserId().toString();
Integer points = Math.abs(record.getPointAmount());
// 4. 原子扣减积分
int affectedRows = memberUserProfileMapper.updatePointsDeduct(userId, points);
if (affectedRows == 0) {
log.warn("[confirmPendingDeductWithTokens] 积分扣减失败可能余额不足记录ID {}", recordId);
throw exception(POINTS_DEDUCT_FAILED);
}
// 5. 查询扣减后余额
MemberUserProfileDO profile = memberUserProfileMapper.selectByUserId(userId);
// 6. 更新预扣记录状态和 token 信息
record.setStatus(STATUS_CONFIRMED);
record.setBalance(profile.getRemainingPoints());
record.setReason(record.getReason().replace("(预扣)", ""));
record.setInputTokens(inputTokens != null ? inputTokens : 0);
record.setOutputTokens(outputTokens != null ? outputTokens : 0);
record.setTotalTokens(totalTokens != null ? totalTokens : 0);
pointRecordMapper.updateById(record);
log.info("[confirmPendingDeductWithTokens] 确认预扣记录 {},用户 {} 扣减 {} 积分tokens: {}/{}/{}",
recordId, userId, points, inputTokens, outputTokens, totalTokens);
}
}

View File

@@ -113,8 +113,17 @@ public class TikUserVoiceServiceImpl implements TikUserVoiceService {
public Long createVoice(AppTikUserVoiceCreateReqVO createReqVO) {
Long userId = SecurityFrameworkUtils.getLoginUserId();
// 1. 校验文件是否存在且属于voice分类
FileDO fileDO = fileMapper.selectById(createReqVO.getFileId());
// 1. 前端传入的是 userFileIdtik_user_file.id先查询用户文件记录
TikUserFileDO userFile = userFileMapper.selectOne(new LambdaQueryWrapperX<TikUserFileDO>()
.eq(TikUserFileDO::getId, createReqVO.getFileId())
.eq(TikUserFileDO::getFileCategory, "voice")
.eq(TikUserFileDO::getUserId, userId));
if (userFile == null) {
throw exception(VOICE_FILE_NOT_EXISTS, "文件不存在或不属于voice分类");
}
// 2. 通过 userFile.fileIdinfra_file.id查询实际文件信息
FileDO fileDO = fileMapper.selectById(userFile.getFileId());
if (fileDO == null) {
throw exception(VOICE_FILE_NOT_EXISTS);
}
@@ -126,15 +135,6 @@ public class TikUserVoiceServiceImpl implements TikUserVoiceService {
String.format("音频文件过大(%.1fMB请上传小于5MB的音频文件", sizeMB));
}
// 验证文件分类是否为voice通过tik_user_file表查询
TikUserFileDO userFile = userFileMapper.selectOne(new LambdaQueryWrapperX<TikUserFileDO>()
.eq(TikUserFileDO::getFileId, createReqVO.getFileId())
.eq(TikUserFileDO::getFileCategory, "voice")
.eq(TikUserFileDO::getUserId, userId));
if (userFile == null) {
throw exception(VOICE_FILE_NOT_EXISTS, "文件不存在或不属于voice分类");
}
// 2. 校验名称是否重复
TikUserVoiceDO existingVoice = voiceMapper.selectOne(new LambdaQueryWrapperX<TikUserVoiceDO>()
.eq(TikUserVoiceDO::getUserId, userId)
@@ -144,11 +144,11 @@ public class TikUserVoiceServiceImpl implements TikUserVoiceService {
throw exception(VOICE_NAME_DUPLICATE);
}
// 3. 创建配音记录
// 3. 创建配音记录fileId 存储 infra_file.id用于后续查询文件URL
TikUserVoiceDO voice = new TikUserVoiceDO()
.setUserId(userId)
.setName(createReqVO.getName())
.setFileId(createReqVO.getFileId())
.setFileId(userFile.getFileId()) // 存储 infra_file.id
.setLanguage(StrUtil.blankToDefault(createReqVO.getLanguage(), "zh-CN"))
.setGender(StrUtil.blankToDefault(createReqVO.getGender(), "female"))
.setNote(createReqVO.getNote())

View File

@@ -19,7 +19,7 @@ public class AppTikUserVoiceCreateReqVO {
@NotBlank(message = "配音名称不能为空")
private String name;
@Schema(description = "音频文件编号(关联 infra_file.id", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
@Schema(description = "用户文件编号(关联 tik_user_file.id上传文件后返回的 userFileId", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
@NotNull(message = "音频文件编号不能为空")
private Long fileId;

View File

@@ -0,0 +1,93 @@
import request from '@/config/axios'
export interface AiUsageOverview {
totalCallCount: number
totalConsumePoints: number
totalTokens: number
activeUserCount: number
bizTypeStats: BizTypeStats[]
}
export interface BizTypeStats {
bizType: string
bizTypeName: string
callCount: number
consumePoints: number
totalTokens: number
}
export interface AiUsageUserStats {
userId: number
mobile: string
callCount: number
consumePoints: number
inputTokens: number
outputTokens: number
totalTokens: number
avgPointsPerCall: number
}
export interface AiUsageAppStats {
serviceCode: string
serviceName: string
platform: string
callCount: number
consumePoints: number
inputTokens: number
outputTokens: number
totalTokens: number
avgPointsPerCall: number
avgTokensPerCall: number
}
export interface AiUsageTrend {
trendList: TrendItem[]
}
export interface TrendItem {
time: string
callCount: number
consumePoints: number
totalTokens: number
}
// 获取概览统计
export const getAiUsageOverview = (params: {
startTime?: string
endTime?: string
bizType?: string
}) => {
return request.get({ url: '/muye/ai-usage-stats/overview', params })
}
// 获取用户统计分页
export const getAiUsageUserStatsPage = (params: {
pageNo: number
pageSize: number
startTime?: string
endTime?: string
bizType?: string
userId?: number
mobile?: string
}) => {
return request.get({ url: '/muye/ai-usage-stats/user-stats', params })
}
// 获取应用统计列表
export const getAiUsageAppStats = (params: {
startTime?: string
endTime?: string
bizType?: string
}) => {
return request.get({ url: '/muye/ai-usage-stats/app-stats', params })
}
// 获取趋势数据
export const getAiUsageTrend = (params: {
startTime?: string
endTime?: string
bizType?: string
type?: string
}) => {
return request.get({ url: '/muye/ai-usage-stats/trend', params })
}

View File

@@ -0,0 +1,360 @@
<template>
<div class="app-stats-panel">
<!-- 筛选条件 -->
<el-form :model="queryParams" :inline="true" class="mb-16px">
<el-form-item label="应用">
<el-select
v-model="queryParams.serviceCode"
placeholder="全部应用"
clearable
filterable
class="!w-200px"
@change="handleQuery"
>
<el-option
v-for="app in appOptions"
:key="app.serviceCode"
:label="app.serviceName || app.serviceCode"
:value="app.serviceCode"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleQuery">
<Icon icon="ep:search" class="mr-4px" /> 查询
</el-button>
<el-button @click="handleReset">
<Icon icon="ep:refresh" class="mr-4px" /> 重置
</el-button>
</el-form-item>
</el-form>
<!-- 统计卡片 -->
<el-row :gutter="16" class="mb-16px">
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-blue">
<Icon icon="ep:menu" />
</div>
<div class="stat-content">
<div class="stat-label">应用数量</div>
<div class="stat-value">{{ summary.appCount?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-green">
<Icon icon="ep:phone" />
</div>
<div class="stat-content">
<div class="stat-label">总调用次数</div>
<div class="stat-value">{{ summary.totalCallCount?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-orange">
<Icon icon="ep:coin" />
</div>
<div class="stat-content">
<div class="stat-label">总消耗积分</div>
<div class="stat-value">{{ summary.totalConsumePoints?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-purple">
<Icon icon="ep:data-analysis" />
</div>
<div class="stat-content">
<div class="stat-label">平均积分/应用</div>
<div class="stat-value">{{ avgPointsPerApp }}</div>
</div>
</div>
</el-card>
</el-col>
</el-row>
<!-- 图表区域 -->
<el-row :gutter="16" class="mb-16px">
<el-col :span="12">
<el-card shadow="hover">
<template #header>
<div class="card-header">
<span>应用积分消耗排行 TOP10</span>
</div>
</template>
<div ref="rankChartRef" class="chart-container"></div>
</el-card>
</el-col>
<el-col :span="12">
<el-card shadow="hover">
<template #header>
<div class="card-header">
<span>平台占比分布</span>
</div>
</template>
<div ref="pieChartRef" class="chart-container"></div>
</el-card>
</el-col>
</el-row>
<!-- 数据表格 -->
<el-card shadow="hover">
<template #header>
<div class="card-header">
<span>应用详细统计</span>
</div>
</template>
<el-table v-loading="loading" :data="filteredDataList" :stripe="true">
<el-table-column label="服务标识" align="center" prop="serviceCode" width="150" />
<el-table-column label="服务名称" align="center" prop="serviceName" />
<el-table-column label="平台" align="center" prop="platform" width="100" />
<el-table-column label="调用次数" align="center" prop="callCount" sortable>
<template #default="{ row }">{{ row.callCount?.toLocaleString() }}</template>
</el-table-column>
<el-table-column label="消耗积分" align="center" prop="consumePoints" sortable>
<template #default="{ row }">{{ row.consumePoints?.toLocaleString() }}</template>
</el-table-column>
<el-table-column label="总Token" align="center" prop="totalTokens" sortable>
<template #default="{ row }">{{ row.totalTokens?.toLocaleString() || '-' }}</template>
</el-table-column>
<el-table-column label="平均积分/次" align="center" prop="avgPointsPerCall" sortable>
<template #default="{ row }">{{ row.avgPointsPerCall?.toFixed(2) }}</template>
</el-table-column>
<el-table-column label="平均Token/次" align="center" prop="avgTokensPerCall" sortable>
<template #default="{ row }">{{ row.avgTokensPerCall?.toFixed(2) }}</template>
</el-table-column>
</el-table>
</el-card>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getAiUsageAppStats, type AiUsageAppStats } from '@/api/muye/aiusagestats'
interface Props {
timeRange: string[]
bizType: string
}
const props = defineProps<Props>()
// 查询参数
const queryParams = reactive({
serviceCode: undefined as string | undefined
})
// 数据
const loading = ref(false)
const dataList = ref<AiUsageAppStats[]>([])
const appOptions = ref<{ serviceCode: string; serviceName: string }[]>([])
// 筛选后的数据
const filteredDataList = computed(() => {
if (!queryParams.serviceCode) return dataList.value
return dataList.value.filter(d => d.serviceCode === queryParams.serviceCode)
})
// 汇总数据
const summary = computed(() => {
const data = filteredDataList.value
const appCount = data.length
const totalCallCount = data.reduce((sum, item) => sum + (item.callCount || 0), 0)
const totalConsumePoints = data.reduce((sum, item) => sum + (item.consumePoints || 0), 0)
return { appCount, totalCallCount, totalConsumePoints }
})
const avgPointsPerApp = computed(() => {
if (summary.value.appCount === 0) return '0'
return (summary.value.totalConsumePoints / summary.value.appCount).toFixed(2)
})
// 图表
const rankChartRef = ref<HTMLElement>()
const pieChartRef = ref<HTMLElement>()
let rankChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null
const initCharts = () => {
if (rankChartRef.value && !rankChart) {
rankChart = echarts.init(rankChartRef.value)
}
if (pieChartRef.value && !pieChart) {
pieChart = echarts.init(pieChartRef.value)
}
}
const drawCharts = () => {
initCharts()
const data = filteredDataList.value
// 积分消耗排行 TOP10
const topByPoints = [...data]
.sort((a, b) => (b.consumePoints || 0) - (a.consumePoints || 0))
.slice(0, 10)
if (rankChart && topByPoints.length > 0) {
rankChart.setOption({
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
grid: { left: 120, right: 20, top: 20, bottom: 20 },
xAxis: { type: 'value', name: '积分' },
yAxis: {
type: 'category',
data: topByPoints.map(d => d.serviceName || d.serviceCode).reverse(),
axisLabel: { width: 100, overflow: 'truncate' }
},
series: [{
type: 'bar',
data: topByPoints.map(d => d.consumePoints).reverse(),
itemStyle: { color: '#e6a23c' }
}]
})
}
// 平台占比饼图
const platformStats = new Map<string, number>()
data.forEach(item => {
const platform = item.platform || '未知'
platformStats.set(platform, (platformStats.get(platform) || 0) + (item.consumePoints || 0))
})
const pieData = Array.from(platformStats.entries())
.map(([name, value]) => ({ name, value }))
.sort((a, b) => b.value - a.value)
if (pieChart && pieData.length > 0) {
pieChart.setOption({
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
legend: { orient: 'vertical', left: 'left', top: 'center' },
series: [{
type: 'pie',
radius: ['40%', '70%'],
center: ['60%', '50%'],
data: pieData,
emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }},
label: { show: false }
}]
})
}
}
// 获取数据
const getDataList = async () => {
loading.value = true
try {
const [startTime, endTime] = props.timeRange || []
const res = await getAiUsageAppStats({
startTime,
endTime,
bizType: props.bizType
})
dataList.value = res || []
// 构建应用选项
appOptions.value = (res || []).map(item => ({
serviceCode: item.serviceCode,
serviceName: item.serviceName || item.serviceCode
}))
await nextTick()
drawCharts()
} finally {
loading.value = false
}
}
// 查询
const handleQuery = () => {
nextTick(() => drawCharts())
}
// 重置
const handleReset = () => {
queryParams.serviceCode = undefined
handleQuery()
}
// 监听外部参数变化
watch(() => [props.timeRange, props.bizType], () => {
getDataList()
}, { deep: true })
// 窗口大小变化
const handleResize = () => {
rankChart?.resize()
pieChart?.resize()
}
onMounted(() => {
getDataList()
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
rankChart?.dispose()
pieChart?.dispose()
})
</script>
<style scoped lang="scss">
.app-stats-panel {
.stat-card {
display: flex;
align-items: center;
padding: 8px;
.stat-icon {
width: 48px;
height: 48px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: #fff;
margin-right: 16px;
&.bg-blue { background: linear-gradient(135deg, #409eff, #3375b9); }
&.bg-orange { background: linear-gradient(135deg, #e6a23c, #cf9236); }
&.bg-green { background: linear-gradient(135deg, #67c23a, #529b2e); }
&.bg-purple { background: linear-gradient(135deg, #909399, #73767a); }
}
.stat-content {
.stat-label {
font-size: 14px;
color: #909399;
margin-bottom: 4px;
}
.stat-value {
font-size: 24px;
font-weight: 600;
color: #303133;
}
}
}
.card-header {
font-size: 16px;
font-weight: 500;
}
.chart-container {
height: 280px;
}
}
</style>

View File

@@ -0,0 +1,370 @@
<template>
<div class="user-stats-panel">
<!-- 筛选条件 -->
<el-form :model="queryParams" :inline="true" class="mb-16px">
<el-form-item label="手机号">
<el-input
v-model="queryParams.mobile"
placeholder="请输入手机号"
clearable
class="!w-200px"
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleQuery">
<Icon icon="ep:search" class="mr-4px" /> 查询
</el-button>
<el-button @click="handleReset">
<Icon icon="ep:refresh" class="mr-4px" /> 重置
</el-button>
</el-form-item>
</el-form>
<!-- 统计卡片 -->
<el-row :gutter="16" class="mb-16px">
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-blue">
<Icon icon="ep:user" />
</div>
<div class="stat-content">
<div class="stat-label">活跃用户数</div>
<div class="stat-value">{{ summary.activeUserCount?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-green">
<Icon icon="ep:phone" />
</div>
<div class="stat-content">
<div class="stat-label">总调用次数</div>
<div class="stat-value">{{ summary.totalCallCount?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-orange">
<Icon icon="ep:coin" />
</div>
<div class="stat-content">
<div class="stat-label">总消耗积分</div>
<div class="stat-value">{{ summary.totalConsumePoints?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-purple">
<Icon icon="ep:data-analysis" />
</div>
<div class="stat-content">
<div class="stat-label">平均积分/用户</div>
<div class="stat-value">{{ avgPointsPerUser }}</div>
</div>
</div>
</el-card>
</el-col>
</el-row>
<!-- 图表区域 -->
<el-row :gutter="16" class="mb-16px">
<el-col :span="12">
<el-card shadow="hover">
<template #header>
<div class="card-header">
<span>用户积分消耗排行 TOP10</span>
</div>
</template>
<div ref="rankChartRef" class="chart-container"></div>
</el-card>
</el-col>
<el-col :span="12">
<el-card shadow="hover">
<template #header>
<div class="card-header">
<span>用户调用次数排行 TOP10</span>
</div>
</template>
<div ref="callChartRef" class="chart-container"></div>
</el-card>
</el-col>
</el-row>
<!-- 数据表格 -->
<el-card shadow="hover">
<template #header>
<div class="card-header">
<span>用户详细统计</span>
</div>
</template>
<el-table v-loading="loading" :data="dataList" :stripe="true">
<el-table-column label="用户ID" align="center" prop="userId" width="100" />
<el-table-column label="手机号" align="center" prop="mobile" width="130" />
<el-table-column label="调用次数" align="center" prop="callCount" sortable>
<template #default="{ row }">{{ row.callCount?.toLocaleString() }}</template>
</el-table-column>
<el-table-column label="消耗积分" align="center" prop="consumePoints" sortable>
<template #default="{ row }">{{ row.consumePoints?.toLocaleString() }}</template>
</el-table-column>
<el-table-column label="输入Token" align="center" prop="inputTokens" sortable>
<template #default="{ row }">{{ row.inputTokens?.toLocaleString() || '-' }}</template>
</el-table-column>
<el-table-column label="输出Token" align="center" prop="outputTokens" sortable>
<template #default="{ row }">{{ row.outputTokens?.toLocaleString() || '-' }}</template>
</el-table-column>
<el-table-column label="总Token" align="center" prop="totalTokens" sortable>
<template #default="{ row }">{{ row.totalTokens?.toLocaleString() || '-' }}</template>
</el-table-column>
<el-table-column label="平均积分/次" align="center" prop="avgPointsPerCall" sortable>
<template #default="{ row }">{{ row.avgPointsPerCall?.toFixed(2) }}</template>
</el-table-column>
</el-table>
<Pagination
v-model:page="pageParams.pageNo"
v-model:limit="pageParams.pageSize"
:total="pageParams.total"
@pagination="getDataList"
/>
</el-card>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getAiUsageUserStatsPage, type AiUsageUserStats } from '@/api/muye/aiusagestats'
interface Props {
timeRange: string[]
bizType: string
}
const props = defineProps<Props>()
// 查询参数
const queryParams = reactive({
mobile: undefined as string | undefined
})
// 分页参数
const pageParams = reactive({
pageNo: 1,
pageSize: 10,
total: 0
})
// 数据
const loading = ref(false)
const dataList = ref<AiUsageUserStats[]>([])
const allUserData = ref<AiUsageUserStats[]>([])
// 汇总数据
const summary = computed(() => {
const activeUserCount = allUserData.value.length
const totalCallCount = allUserData.value.reduce((sum, item) => sum + (item.callCount || 0), 0)
const totalConsumePoints = allUserData.value.reduce((sum, item) => sum + (item.consumePoints || 0), 0)
return { activeUserCount, totalCallCount, totalConsumePoints }
})
const avgPointsPerUser = computed(() => {
if (summary.value.activeUserCount === 0) return '0'
return (summary.value.totalConsumePoints / summary.value.activeUserCount).toFixed(2)
})
// 图表
const rankChartRef = ref<HTMLElement>()
const callChartRef = ref<HTMLElement>()
let rankChart: echarts.ECharts | null = null
let callChart: echarts.ECharts | null = null
const initCharts = () => {
if (rankChartRef.value && !rankChart) {
rankChart = echarts.init(rankChartRef.value)
}
if (callChartRef.value && !callChart) {
callChart = echarts.init(callChartRef.value)
}
}
const drawCharts = () => {
initCharts()
// 积分消耗排行 TOP10
const topByPoints = [...allUserData.value]
.sort((a, b) => (b.consumePoints || 0) - (a.consumePoints || 0))
.slice(0, 10)
if (rankChart && topByPoints.length > 0) {
rankChart.setOption({
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
grid: { left: 100, right: 20, top: 20, bottom: 20 },
xAxis: { type: 'value', name: '积分' },
yAxis: {
type: 'category',
data: topByPoints.map(d => d.mobile || `用户${d.userId}`).reverse(),
axisLabel: { width: 80, overflow: 'truncate' }
},
series: [{
type: 'bar',
data: topByPoints.map(d => d.consumePoints).reverse(),
itemStyle: { color: '#e6a23c' }
}]
})
}
// 调用次数排行 TOP10
const topByCalls = [...allUserData.value]
.sort((a, b) => (b.callCount || 0) - (a.callCount || 0))
.slice(0, 10)
if (callChart && topByCalls.length > 0) {
callChart.setOption({
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
grid: { left: 100, right: 20, top: 20, bottom: 20 },
xAxis: { type: 'value', name: '次数' },
yAxis: {
type: 'category',
data: topByCalls.map(d => d.mobile || `用户${d.userId}`).reverse(),
axisLabel: { width: 80, overflow: 'truncate' }
},
series: [{
type: 'bar',
data: topByCalls.map(d => d.callCount).reverse(),
itemStyle: { color: '#409eff' }
}]
})
}
}
// 获取数据
const getDataList = async () => {
loading.value = true
try {
const [startTime, endTime] = props.timeRange || []
const res = await getAiUsageUserStatsPage({
pageNo: pageParams.pageNo,
pageSize: pageParams.pageSize,
startTime,
endTime,
bizType: props.bizType,
mobile: queryParams.mobile
})
dataList.value = res?.list || []
pageParams.total = res?.total || 0
} finally {
loading.value = false
}
}
// 获取全部数据用于图表
const getAllDataForChart = async () => {
const [startTime, endTime] = props.timeRange || []
const res = await getAiUsageUserStatsPage({
pageNo: 1,
pageSize: 100,
startTime,
endTime,
bizType: props.bizType,
mobile: queryParams.mobile
})
allUserData.value = res?.list || []
await nextTick()
drawCharts()
}
// 查询
const handleQuery = () => {
pageParams.pageNo = 1
getDataList()
getAllDataForChart()
}
// 重置
const handleReset = () => {
queryParams.mobile = undefined
handleQuery()
}
// 监听外部参数变化
watch(() => [props.timeRange, props.bizType], () => {
handleQuery()
}, { deep: true })
// 窗口大小变化
const handleResize = () => {
rankChart?.resize()
callChart?.resize()
}
onMounted(() => {
handleQuery()
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
rankChart?.dispose()
callChart?.dispose()
})
</script>
<style scoped lang="scss">
.user-stats-panel {
.stat-card {
display: flex;
align-items: center;
padding: 8px;
.stat-icon {
width: 48px;
height: 48px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: #fff;
margin-right: 16px;
&.bg-blue { background: linear-gradient(135deg, #409eff, #3375b9); }
&.bg-orange { background: linear-gradient(135deg, #e6a23c, #cf9236); }
&.bg-green { background: linear-gradient(135deg, #67c23a, #529b2e); }
&.bg-purple { background: linear-gradient(135deg, #909399, #73767a); }
}
.stat-content {
.stat-label {
font-size: 14px;
color: #909399;
margin-bottom: 4px;
}
.stat-value {
font-size: 24px;
font-weight: 600;
color: #303133;
}
}
}
.card-header {
font-size: 16px;
font-weight: 500;
}
.chart-container {
height: 280px;
}
}
</style>

View File

@@ -0,0 +1,394 @@
<template>
<ContentWrap>
<!-- 筛选条件 -->
<el-form :model="queryParams" :inline="true" class="-mb-15px">
<el-form-item label="时间范围">
<el-date-picker
v-model="queryParams.timeRange"
type="daterange"
value-format="YYYY-MM-DD HH:mm:ss"
:shortcuts="timeShortcuts"
range-separator="-"
start-placeholder="开始时间"
end-placeholder="结束时间"
class="!w-240px"
@change="handleQuery"
/>
</el-form-item>
<el-form-item label="业务类型">
<el-select v-model="queryParams.bizType" placeholder="全部" clearable class="!w-180px" @change="handleQuery">
<el-option label="全部" value="" />
<el-option label="AI对话" value="dify_chat" />
<el-option label="文案改写" value="forecast_rewrite" />
<el-option label="语音合成" value="voice_tts" />
<el-option label="数字人" value="digital_human" />
</el-select>
</el-form-item>
</el-form>
</ContentWrap>
<!-- Tab 切换 -->
<ContentWrap>
<el-tabs v-model="activeTab">
<!-- 概览 Tab -->
<el-tab-pane label="概览" name="overview">
<!-- 统计卡片 -->
<el-row :gutter="16" class="mb-16px">
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-blue">
<Icon icon="ep:phone" />
</div>
<div class="stat-content">
<div class="stat-label">总调用次数</div>
<div class="stat-value">{{ overviewData.totalCallCount?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-orange">
<Icon icon="ep:coin" />
</div>
<div class="stat-content">
<div class="stat-label">总消耗积分</div>
<div class="stat-value">{{ overviewData.totalConsumePoints?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-green">
<Icon icon="ep:data-analysis" />
</div>
<div class="stat-content">
<div class="stat-label"> Token </div>
<div class="stat-value">{{ overviewData.totalTokens?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-card">
<div class="stat-icon bg-purple">
<Icon icon="ep:user" />
</div>
<div class="stat-content">
<div class="stat-label">活跃用户数</div>
<div class="stat-value">{{ overviewData.activeUserCount?.toLocaleString() || 0 }}</div>
</div>
</div>
</el-card>
</el-col>
</el-row>
<!-- 图表区域 -->
<el-row :gutter="16">
<el-col :span="16">
<el-card shadow="hover">
<template #header>
<div class="card-header">
<span>消耗趋势</span>
</div>
</template>
<div ref="trendChartRef" class="chart-container"></div>
</el-card>
</el-col>
<el-col :span="8">
<el-card shadow="hover">
<template #header>
<div class="card-header">
<span>业务类型占比</span>
</div>
</template>
<div ref="pieChartRef" class="chart-container"></div>
</el-card>
</el-col>
</el-row>
<!-- 业务类型统计表格 -->
<el-card shadow="hover" class="mt-16px">
<template #header>
<div class="card-header">
<span>业务类型统计</span>
</div>
</template>
<el-table :data="overviewData.bizTypeStats || []" :stripe="true">
<el-table-column label="业务类型" align="center" prop="bizTypeName" />
<el-table-column label="调用次数" align="center" prop="callCount">
<template #default="{ row }">{{ row.callCount?.toLocaleString() }}</template>
</el-table-column>
<el-table-column label="消耗积分" align="center" prop="consumePoints">
<template #default="{ row }">{{ row.consumePoints?.toLocaleString() }}</template>
</el-table-column>
<el-table-column label="Token 数" align="center" prop="totalTokens">
<template #default="{ row }">{{ row.totalTokens?.toLocaleString() || '-' }}</template>
</el-table-column>
</el-table>
</el-card>
</el-tab-pane>
<!-- 用户统计 Tab -->
<el-tab-pane label="用户统计" name="user">
<UserStatsPanel v-if="activeTab === 'user'" :time-range="queryParams.timeRange" :biz-type="queryParams.bizType" />
</el-tab-pane>
<!-- 应用统计 Tab -->
<el-tab-pane label="应用统计" name="app">
<AppStatsPanel v-if="activeTab === 'app'" :time-range="queryParams.timeRange" :biz-type="queryParams.bizType" />
</el-tab-pane>
</el-tabs>
</ContentWrap>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import {
getAiUsageOverview,
getAiUsageTrend,
type AiUsageOverview
} from '@/api/muye/aiusagestats'
import UserStatsPanel from './components/UserStatsPanel.vue'
import AppStatsPanel from './components/AppStatsPanel.vue'
defineOptions({ name: 'AiUsageStats' })
// 时间快捷选项
const timeShortcuts = [
{ text: '今天', value: () => {
const today = new Date()
today.setHours(0, 0, 0, 0)
return [today, new Date()]
}},
{ text: '本周', value: () => {
const today = new Date()
const day = today.getDay() || 7
const monday = new Date(today)
monday.setDate(today.getDate() - day + 1)
monday.setHours(0, 0, 0, 0)
return [monday, new Date()]
}},
{ text: '本月', value: () => {
const today = new Date()
const firstDay = new Date(today.getFullYear(), today.getMonth(), 1)
return [firstDay, new Date()]
}},
{ text: '最近7天', value: () => {
const end = new Date()
const start = new Date()
start.setDate(start.getDate() - 7)
return [start, end]
}},
{ text: '最近30天', value: () => {
const end = new Date()
const start = new Date()
start.setDate(start.getDate() - 30)
return [start, end]
}}
]
// 查询参数
const queryParams = reactive({
timeRange: [] as string[],
bizType: ''
})
// Tab
const activeTab = ref('overview')
// 概览数据
const overviewData = ref<AiUsageOverview>({} as AiUsageOverview)
// 图表
const trendChartRef = ref<HTMLElement>()
const pieChartRef = ref<HTMLElement>()
let trendChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null
// 获取概览数据
const getOverviewData = async () => {
const [startTime, endTime] = queryParams.timeRange || []
const res = await getAiUsageOverview({
startTime,
endTime,
bizType: queryParams.bizType
})
overviewData.value = res || {}
}
// 初始化趋势图表
const initTrendChart = () => {
if (!trendChartRef.value) return false
if (!trendChart) {
trendChart = echarts.init(trendChartRef.value)
}
return true
}
// 获取趋势数据并绘制图表
const getTrendData = async () => {
const [startTime, endTime] = queryParams.timeRange || []
const res = await getAiUsageTrend({
startTime,
endTime,
bizType: queryParams.bizType,
type: 'day'
})
await nextTick()
if (!initTrendChart()) {
console.warn('趋势图表容器未找到')
return
}
if (res?.trendList?.length > 0) {
const data = res.trendList
trendChart!.setOption({
tooltip: { trigger: 'axis' },
legend: { data: ['调用次数', '消耗积分', 'Token数'] },
xAxis: { type: 'category', data: data.map((d: any) => d.time) },
yAxis: [
{ type: 'value', name: '次数/积分' },
{ type: 'value', name: 'Token' }
],
series: [
{ name: '调用次数', type: 'line', data: data.map((d: any) => d.callCount) },
{ name: '消耗积分', type: 'line', data: data.map((d: any) => d.consumePoints) },
{ name: 'Token数', type: 'line', yAxisIndex: 1, data: data.map((d: any) => d.totalTokens) }
]
})
}
}
// 初始化饼图
const initPieChart = () => {
if (!pieChartRef.value) return false
if (!pieChart) {
pieChart = echarts.init(pieChartRef.value)
}
return true
}
// 绘制饼图
const drawPieChart = () => {
if (!initPieChart()) {
console.warn('饼图容器未找到')
return
}
if (overviewData.value.bizTypeStats?.length > 0) {
const data = overviewData.value.bizTypeStats.map((item: any) => ({
name: item.bizTypeName,
value: item.consumePoints
}))
pieChart!.setOption({
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
legend: { orient: 'vertical', left: 'left' },
series: [{
type: 'pie',
radius: '50%',
data,
emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }}
}]
})
}
}
// 查询
const handleQuery = async () => {
if (activeTab.value !== 'overview') return
await getOverviewData()
await getTrendData()
await nextTick()
drawPieChart()
}
// 窗口大小变化时重绘图表
const handleResize = () => {
trendChart?.resize()
pieChart?.resize()
}
// 格式化日期为本地时间字符串
const formatLocalDateTime = (date: Date) => {
const pad = (n: number) => String(n).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
onMounted(async () => {
// 设置默认时间范围最近7天
const end = new Date()
const start = new Date()
start.setDate(start.getDate() - 7)
queryParams.timeRange = [
formatLocalDateTime(start),
formatLocalDateTime(end)
]
await handleQuery()
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
trendChart?.dispose()
pieChart?.dispose()
})
</script>
<style scoped lang="scss">
.stat-card {
display: flex;
align-items: center;
padding: 8px;
.stat-icon {
width: 48px;
height: 48px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: #fff;
margin-right: 16px;
&.bg-blue { background: linear-gradient(135deg, #409eff, #3375b9); }
&.bg-orange { background: linear-gradient(135deg, #e6a23c, #cf9236); }
&.bg-green { background: linear-gradient(135deg, #67c23a, #529b2e); }
&.bg-purple { background: linear-gradient(135deg, #909399, #73767a); }
}
.stat-content {
.stat-label {
font-size: 14px;
color: #909399;
margin-bottom: 4px;
}
.stat-value {
font-size: 24px;
font-weight: 600;
color: #303133;
}
}
}
.card-header {
font-size: 16px;
font-weight: 500;
}
.chart-container {
height: 300px;
}
</style>

View File

@@ -124,6 +124,26 @@
</template>
</el-table-column>
<el-table-column label="业务关联ID" align="center" prop="bizId" />
<el-table-column label="服务标识" align="center" prop="serviceCode">
<template #default="scope">
{{ scope.row.serviceCode || '-' }}
</template>
</el-table-column>
<el-table-column label="输入Token" align="center" prop="inputTokens">
<template #default="scope">
{{ scope.row.inputTokens?.toLocaleString() || '-' }}
</template>
</el-table-column>
<el-table-column label="输出Token" align="center" prop="outputTokens">
<template #default="scope">
{{ scope.row.outputTokens?.toLocaleString() || '-' }}
</template>
</el-table-column>
<el-table-column label="总Token" align="center" prop="totalTokens">
<template #default="scope">
{{ scope.row.totalTokens?.toLocaleString() || '-' }}
</template>
</el-table-column>
<el-table-column label="备注" align="center" prop="remark" />
<el-table-column label="操作" align="center" min-width="120px">
<template #default="scope">
@@ -247,43 +267,42 @@ const openForm = (type: string, id?: number) => {
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
try {
// 删除的二次确认
await message.delConfirm()
// 发起删除
await PointRecordApi.deletePointRecord(id)
message.success(t('common.delSuccess'))
// 刷新列表
await getList()
} catch {}
} catch {
// 用户取消操作
}
}
/** 批量删除积分记录 */
const handleDeleteBatch = async () => {
try {
// 删除的二次确认
await message.delConfirm()
await PointRecordApi.deletePointRecordList(checkedIds.value);
checkedIds.value = [];
await PointRecordApi.deletePointRecordList(checkedIds.value)
checkedIds.value = []
message.success(t('common.delSuccess'))
await getList();
} catch {}
await getList()
} catch {
// 用户取消操作
}
}
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: PointRecord[]) => {
checkedIds.value = records.map((item) => item.id!);
checkedIds.value = records.map((item) => item.id!)
}
/** 导出按钮操作 */
const handleExport = async () => {
try {
// 导出的二次确认
await message.exportConfirm()
// 发起导出
exportLoading.value = true
const data = await PointRecordApi.exportPointRecord(queryParams)
download.excel(data, '积分记录.xls')
} catch {
// 用户取消操作
} finally {
exportLoading.value = false
}