feat: 优化

This commit is contained in:
2026-03-08 13:55:10 +08:00
parent 2aa459889a
commit 69835ae990
9 changed files with 484 additions and 310 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') },
]
},

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

@@ -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

@@ -5,7 +5,6 @@ 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.dal.PointRecordDO;
import cn.iocoder.yudao.module.tik.muye.pointrecord.mapper.PointRecordMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
@@ -33,19 +32,18 @@ public class AiUsageStatsServiceImpl implements AiUsageStatsService {
/**
* 业务类型名称映射
*/
private static final Map<String, String> BIZ_TYPE_NAMES = new HashMap<>();
static {
BIZ_TYPE_NAMES.put("dify_chat", "AI对话");
BIZ_TYPE_NAMES.put("forecast_rewrite", "文案改写");
BIZ_TYPE_NAMES.put("voice_tts", "语音合成");
BIZ_TYPE_NAMES.put("digital_human", "数字人");
BIZ_TYPE_NAMES.put("tikhub_fetch", "TikHub获取");
BIZ_TYPE_NAMES.put("signin", "签到");
BIZ_TYPE_NAMES.put("recharge", "充值");
BIZ_TYPE_NAMES.put("exchange", "兑换");
BIZ_TYPE_NAMES.put("admin", "后台调整");
BIZ_TYPE_NAMES.put("gift", "礼包赠送");
}
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) {
@@ -59,15 +57,15 @@ public class AiUsageStatsServiceImpl implements AiUsageStatsService {
List<AiUsageOverviewRespVO.BizTypeStats> bizTypeStats = new ArrayList<>();
for (Map<String, Object> stats : bizTypeStatsList) {
String bt = (String) stats.get("biz_type");
String bt = (String) stats.get("bizType");
// 如果指定了业务类型,只统计该类型
if (bizType != null && !bizType.isEmpty() && !bizType.equals(bt)) {
continue;
}
long callCount = getLongValue(stats, "call_count");
long consumePoints = getLongValue(stats, "consume_points");
long tokens = getLongValue(stats, "total_tokens");
long callCount = getLongValue(stats, "callCount");
long consumePoints = getLongValue(stats, "consumePoints");
long tokens = getLongValue(stats, "totalTokens");
totalCallCount += callCount;
totalConsumePoints += consumePoints;
@@ -83,15 +81,7 @@ public class AiUsageStatsServiceImpl implements AiUsageStatsService {
}
// 查询活跃用户数
Long activeUserCount = pointRecordMapper.selectCount(
new LambdaQueryWrapperX<PointRecordDO>()
.betweenIfPresent(PointRecordDO::getCreateTime, startTime, endTime)
.eqIfPresent(PointRecordDO::getBizType, bizType)
.eq(PointRecordDO::getStatus, "confirmed")
.eq(PointRecordDO::getType, "decrease")
.select(PointRecordDO::getUserId)
.groupBy(PointRecordDO::getUserId)
);
Long activeUserCount = pointRecordMapper.selectActiveUserCount(startTime, endTime, bizType);
return AiUsageOverviewRespVO.builder()
.totalCallCount(totalCallCount)
@@ -136,12 +126,10 @@ public class AiUsageStatsServiceImpl implements AiUsageStatsService {
startTime, endTime, bizType);
// 获取服务配置信息
Map<String, AiServiceConfigDO> configMap = new HashMap<>();
List<AiServiceConfigDO> configs = aiServiceConfigMapper.selectList(
new LambdaQueryWrapperX<AiServiceConfigDO>().eq(AiServiceConfigDO::getStatus, 1));
for (AiServiceConfigDO config : configs) {
configMap.put(config.getServiceCode(), config);
}
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()
@@ -169,17 +157,17 @@ public class AiUsageStatsServiceImpl implements AiUsageStatsService {
* 转换为用户统计 VO
*/
private AiUsageUserStatsRespVO convertToUserStatsVO(Map<String, Object> stats) {
Long callCount = getLongValue(stats, "call_count");
Long consumePoints = getLongValue(stats, "consume_points");
Long callCount = getLongValue(stats, "callCount");
Long consumePoints = getLongValue(stats, "consumePoints");
return AiUsageUserStatsRespVO.builder()
.userId(getLongValue(stats, "user_id"))
.userId(getLongValue(stats, "userId"))
.mobile((String) stats.get("mobile"))
.callCount(callCount)
.consumePoints(consumePoints)
.inputTokens(getLongValue(stats, "input_tokens"))
.outputTokens(getLongValue(stats, "output_tokens"))
.totalTokens(getLongValue(stats, "total_tokens"))
.inputTokens(getLongValue(stats, "inputTokens"))
.outputTokens(getLongValue(stats, "outputTokens"))
.totalTokens(getLongValue(stats, "totalTokens"))
.avgPointsPerCall(callCount > 0 ? (double) consumePoints / callCount : 0.0)
.build();
}
@@ -189,10 +177,10 @@ public class AiUsageStatsServiceImpl implements AiUsageStatsService {
*/
private AiUsageAppStatsRespVO convertToAppStatsVO(Map<String, Object> stats,
Map<String, AiServiceConfigDO> configMap) {
String serviceCode = (String) stats.get("service_code");
Long callCount = getLongValue(stats, "call_count");
Long consumePoints = getLongValue(stats, "consume_points");
Long totalTokens = getLongValue(stats, "total_tokens");
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);
@@ -202,8 +190,8 @@ public class AiUsageStatsServiceImpl implements AiUsageStatsService {
.platform(config != null ? config.getPlatform() : "")
.callCount(callCount)
.consumePoints(consumePoints)
.inputTokens(getLongValue(stats, "input_tokens"))
.outputTokens(getLongValue(stats, "output_tokens"))
.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)
@@ -216,9 +204,9 @@ public class AiUsageStatsServiceImpl implements AiUsageStatsService {
private AiUsageTrendRespVO.TrendItem convertToTrendItem(Map<String, Object> stats) {
return AiUsageTrendRespVO.TrendItem.builder()
.time((String) stats.get("time"))
.callCount(getLongValue(stats, "call_count"))
.consumePoints(getLongValue(stats, "consume_points"))
.totalTokens(getLongValue(stats, "total_tokens"))
.callCount(getLongValue(stats, "callCount"))
.consumePoints(getLongValue(stats, "consumePoints"))
.totalTokens(getLongValue(stats, "totalTokens"))
.build();
}

View File

@@ -48,16 +48,16 @@ public interface PointRecordMapper extends BaseMapperX<PointRecordDO> {
* 按业务类型统计
*/
@Select("<script>" +
"SELECT biz_type, " +
" COUNT(*) as call_count, " +
" SUM(ABS(point_amount)) as consume_points, " +
" SUM(COALESCE(total_tokens, 0)) as total_tokens " +
"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 consume_points DESC" +
"ORDER BY consumePoints DESC" +
"</script>")
List<Map<String, Object>> selectBizTypeStats(@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
@@ -66,12 +66,12 @@ public interface PointRecordMapper extends BaseMapperX<PointRecordDO> {
* 按用户统计
*/
@Select("<script>" +
"SELECT user_id, mobile, " +
" COUNT(*) as call_count, " +
" SUM(ABS(point_amount)) as consume_points, " +
" SUM(COALESCE(input_tokens, 0)) as input_tokens, " +
" SUM(COALESCE(output_tokens, 0)) as output_tokens, " +
" SUM(COALESCE(total_tokens, 0)) as total_tokens " +
"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>" +
@@ -79,7 +79,7 @@ public interface PointRecordMapper extends BaseMapperX<PointRecordDO> {
"<if test='bizType != null and bizType != \"\"'> AND biz_type = #{bizType}</if>" +
"<if test='userId != null'> AND user_id = #{userId}</if>" +
"GROUP BY user_id, mobile " +
"ORDER BY consume_points DESC" +
"ORDER BY consumePoints DESC" +
"</script>")
List<Map<String, Object>> selectUserStats(@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime,
@@ -90,19 +90,19 @@ public interface PointRecordMapper extends BaseMapperX<PointRecordDO> {
* 按应用统计
*/
@Select("<script>" +
"SELECT service_code, " +
" COUNT(*) as call_count, " +
" SUM(ABS(point_amount)) as consume_points, " +
" SUM(COALESCE(input_tokens, 0)) as input_tokens, " +
" SUM(COALESCE(output_tokens, 0)) as output_tokens, " +
" SUM(COALESCE(total_tokens, 0)) as total_tokens " +
"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 consume_points DESC" +
"ORDER BY consumePoints DESC" +
"</script>")
List<Map<String, Object>> selectAppStats(@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime,
@@ -112,10 +112,10 @@ public interface PointRecordMapper extends BaseMapperX<PointRecordDO> {
* 按时间趋势统计
*/
@Select("<script>" +
"SELECT DATE_FORMAT(create_time, #{dateFormat}) as time, " +
" COUNT(*) as call_count, " +
" SUM(ABS(point_amount)) as consume_points, " +
" SUM(COALESCE(total_tokens, 0)) as total_tokens " +
"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>" +
@@ -129,4 +129,19 @@ public interface PointRecordMapper extends BaseMapperX<PointRecordDO> {
@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

@@ -284,6 +284,15 @@ const getOverviewData = async () => {
overviewData.value = res.data || {}
}
// 初始化趋势图表
const initTrendChart = () => {
if (!trendChartRef.value) return false
if (!trendChart) {
trendChart = echarts.init(trendChartRef.value)
}
return true
}
// 获取趋势数据并绘制图表
const getTrendData = async () => {
const [startTime, endTime] = queryParams.timeRange || []
@@ -294,14 +303,18 @@ const getTrendData = async () => {
type: 'day'
})
// 确保 DOM 已渲染
await nextTick()
if (!trendChart && trendChartRef.value) {
trendChart = echarts.init(trendChartRef.value)
// 初始化图表
if (!initTrendChart()) {
console.warn('趋势图表容器未找到')
return
}
if (trendChart && res.data?.trendList) {
if (res.data?.trendList?.length > 0) {
const data = res.data.trendList
trendChart.setOption({
trendChart!.setOption({
tooltip: { trigger: 'axis' },
legend: { data: ['调用次数', '消耗积分', 'Token数'] },
xAxis: { type: 'category', data: data.map((d: any) => d.time) },
@@ -318,19 +331,30 @@ const getTrendData = async () => {
}
}
// 绘制饼图
const drawPieChart = () => {
if (!pieChart && pieChartRef.value) {
// 初始化饼图
const initPieChart = () => {
if (!pieChartRef.value) return false
if (!pieChart) {
pieChart = echarts.init(pieChartRef.value)
}
return true
}
if (pieChart && overviewData.value.bizTypeStats) {
// 绘制饼图
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({
pieChart!.setOption({
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
legend: { orient: 'vertical', left: 'left' },
series: [{
@@ -382,6 +406,7 @@ const getAppStatsList = async () => {
const handleQuery = async () => {
await getOverviewData()
await getTrendData()
await nextTick()
drawPieChart()
if (activeTab.value === 'user') {
getUserStatsList()
@@ -405,14 +430,21 @@ const handleResize = () => {
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 = [
start.toISOString().slice(0, 19).replace('T', ' '),
end.toISOString().slice(0, 19).replace('T', ' ')
formatLocalDateTime(start),
formatLocalDateTime(end)
]
await handleQuery()

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">