This commit is contained in:
2026-02-23 02:05:48 +08:00
parent c8598d3dea
commit 5b3047f675
8 changed files with 178 additions and 159 deletions

View File

@@ -5,6 +5,7 @@ import router from '@/router'
import { getUserInfo,clearUserInfoCache } from './userinfo'
const SERVER_BASE = API_BASE.APP_MEMBER
const TIK_BASE = API_BASE.APP_TIK
/**
* 保存token
@@ -195,6 +196,15 @@ export function getUserInfoAuth() {
return getUserInfo()
}
/**
* 获取用户档案(积分、存储配额等)
* @returns {Promise<Object>} 用户档案
*/
export async function getUserProfile() {
const { data } = await api.get(`${TIK_BASE}/muye/member-profile/get`)
return data
}
/**
* 手机+验证码+密码注册流程
* @param {string} mobile - 手机号
@@ -223,4 +233,5 @@ export default {
resetPasswordBySms,
registerWithMobileCodePassword,
getUserInfo: getUserInfoAuth,
getUserProfile,
}

View File

@@ -1,5 +1,5 @@
<script setup>
import { ref, computed } from 'vue'
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
@@ -7,35 +7,16 @@ const router = useRouter()
const userStore = useUserStore()
const showDropdown = ref(false)
// 计算会员状态
const isVip = computed(() => userStore.vipLevel > 0)
const vipLevelText = computed(() => {
if (userStore.vipLevel === 0) return '普通用户'
if (userStore.vipLevel === 1) return 'VIP会员'
if (userStore.vipLevel === 2) return '高级VIP'
return `VIP${userStore.vipLevel}`
// 存储空间数据(后端单位 GB前端展示转换为 MB
const GB_TO_MB = 1024
const totalStorage = computed(() => userStore.totalStorage * GB_TO_MB)
const usedStorage = computed(() => userStore.usedStorage * GB_TO_MB)
const availableStorage = computed(() => userStore.remainingStorage * GB_TO_MB)
const storagePercent = computed(() => {
if (totalStorage.value === 0) return 0
return (usedStorage.value / totalStorage.value) * 100
})
// 计算存储空间根据VIP等级设置不同总空间
const totalStorage = computed(() => {
// VIP等级越高总空间越大
if (userStore.vipLevel >= 2) return 50 * 1024 // 50GB
if (userStore.vipLevel === 1) return 20 * 1024 // 20GB
return 10 * 1024 // 10GB (普通用户)
})
const usedStorage = computed(() => {
// 根据credits估算已用空间这里可以根据实际业务逻辑调整
// 假设每1000积分对应100MB存储使用
const estimatedFromCredits = (userStore.credits / 1000) * 100
// 默认已用30%但不超过总空间的80%
const defaultUsed = totalStorage.value * 0.3
return Math.min(Math.max(defaultUsed, estimatedFromCredits), totalStorage.value * 0.8)
})
const availableStorage = computed(() => totalStorage.value - usedStorage.value)
const storagePercent = computed(() => (usedStorage.value / totalStorage.value) * 100)
// 格式化存储空间显示
function formatStorage(mb) {
if (mb >= 1024) {
@@ -44,9 +25,9 @@ function formatStorage(mb) {
return Math.round(mb) + ' MB'
}
// 格式化
function formatBalance(balance) {
return balance.toFixed(2)
// 格式化
function formatMoney(amount) {
return amount.toFixed(2)
}
// 格式化积分
@@ -68,12 +49,18 @@ function handleMouseLeave() {
async function handleLogout() {
try {
await userStore.logout()
// 跳转到登录页
router.push('/login')
} catch (error) {
console.error('退出登录失败:', error)
}
}
// 挂载时获取档案数据
onMounted(async () => {
if (userStore.isLoggedIn && !userStore.profile) {
await userStore.fetchUserProfile()
}
})
</script>
<template>
@@ -93,12 +80,6 @@ async function handleLogout() {
<div v-else class="user-avatar-placeholder">
{{ userStore.displayName?.charAt(0) || 'U' }}
</div>
<!-- VIP标识 -->
<div v-if="isVip" class="vip-badge">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M6 0L7.5 4.5L12 6L7.5 7.5L6 12L4.5 7.5L0 6L4.5 4.5L6 0Z" fill="#FFD700"/>
</svg>
</div>
</div>
<!-- 下拉菜单 -->
@@ -108,11 +89,11 @@ async function handleLogout() {
<div class="dropdown-arrow"></div>
<div class="dropdown-header">
<div class="header-avatar">
<img
v-if="userStore.displayAvatar"
class="avatar-large"
:src="userStore.displayAvatar"
alt="avatar"
<img
v-if="userStore.displayAvatar"
class="avatar-large"
:src="userStore.displayAvatar"
alt="avatar"
/>
<div v-else class="avatar-large-placeholder">
{{ userStore.displayName?.charAt(0) || 'U' }}
@@ -121,7 +102,6 @@ async function handleLogout() {
<div class="header-info">
<div class="user-name-row">
<span class="user-name">{{ userStore.displayName }}</span>
<span v-if="isVip" class="vip-tag">{{ vipLevelText }}</span>
</div>
<div class="user-id">ID: {{ userStore.userId || '未设置' }}</div>
</div>
@@ -130,19 +110,6 @@ async function handleLogout() {
<div class="dropdown-divider"></div>
<div class="dropdown-content">
<!-- 会员状态 -->
<div class="info-item">
<div class="info-label">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="info-icon">
<path d="M8 0L10 6L16 8L10 10L8 16L6 10L0 8L6 6L8 0Z" fill="currentColor" opacity="0.6"/>
</svg>
<span>会员状态</span>
</div>
<div class="info-value" :class="{ 'vip-text': isVip }">
{{ vipLevelText }}
</div>
</div>
<!-- 可用空间 -->
<div class="info-item">
<div class="info-label">
@@ -160,8 +127,8 @@ async function handleLogout() {
<!-- 存储进度条 -->
<div class="storage-progress">
<div class="progress-bar">
<div
class="progress-fill"
<div
class="progress-fill"
:style="{ width: storagePercent + '%' }"
></div>
</div>
@@ -172,31 +139,31 @@ async function handleLogout() {
</div>
</div>
<!-- 剩余额度 -->
<!-- 剩余积分 -->
<div class="info-item">
<div class="info-label">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="info-icon">
<circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.6"/>
<path d="M8 4V8L10 10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" opacity="0.6"/>
</svg>
<span>剩余额度</span>
<span>剩余积分</span>
</div>
<div class="info-value credits-value">
{{ formatCredits(userStore.credits) }}
{{ formatCredits(userStore.remainingPoints) }}
</div>
</div>
<!-- 账户余额 -->
<!-- 累计充值 -->
<div class="info-item">
<div class="info-label">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="info-icon">
<circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.6"/>
<path d="M8 5V8L10 10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" opacity="0.6"/>
</svg>
<span>账户余额</span>
<span>累计充值</span>
</div>
<div class="info-value balance-value">
¥{{ formatBalance(userStore.balance) }}
¥{{ formatMoney(userStore.totalRecharge) }}
</div>
</div>
</div>
@@ -268,21 +235,6 @@ async function handleLogout() {
box-shadow: var(--glow-primary);
}
.vip-badge {
position: absolute;
bottom: -2px;
right: -2px;
width: 18px;
height: 18px;
background: var(--color-surface);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
border: 2px solid var(--color-border);
z-index: 1;
}
.user-dropdown {
position: absolute;
top: calc(100% + 12px);
@@ -377,20 +329,6 @@ async function handleLogout() {
white-space: nowrap;
}
.vip-tag {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
background: linear-gradient(135deg, #FFD700, #FFA500);
color: #000;
font-size: 11px;
font-weight: 700;
border-radius: 10px;
white-space: nowrap;
box-shadow: 0 2px 4px rgba(255, 215, 0, 0.3);
}
.user-id {
font-size: 12px;
color: var(--color-text-secondary);
@@ -436,10 +374,6 @@ async function handleLogout() {
color: var(--color-text);
}
.vip-text {
color: #FFD700;
}
.credits-value {
color: var(--color-primary);
}

View File

@@ -3,22 +3,29 @@ import { defineStore } from 'pinia'
import { getJSON, setJSON, remove } from '@/utils/storage'
import tokenManager from '@gold/utils/token-manager'
import { getUserInfo, clearUserInfoCache } from '@/api/userinfo'
import { getUserProfile } from '@/api/auth'
const STORAGE_KEY = 'user_store_v1'
export const useUserStore = defineStore('user', () => {
const isLoggedIn = ref(false)
const isHydrated = ref(false)
// 基础信息
const userId = ref('')
const nickname = ref('')
const avatar = ref('')
const wechat = ref({ openId: '', unionId: '', nickname: '', avatar: '' })
const balance = ref(0)
const vipLevel = ref(0)
const credits = ref(0)
const isHydrated = ref(false)
const displayName = computed(() => nickname.value || wechat.value.nickname || '未命名用户')
const displayAvatar = computed(() => avatar.value || wechat.value.avatar || '')
// 档案数据(来自 MemberUserProfile
const profile = ref(null)
const remainingPoints = computed(() => profile.value?.remainingPoints ?? 0)
const remainingStorage = computed(() => profile.value?.remainingStorage ?? 10) // GB
const usedStorage = computed(() => profile.value?.usedStorage ?? 0) // GB
const totalStorage = computed(() => profile.value?.totalStorage ?? 10) // GB
const totalRecharge = computed(() => profile.value?.totalRecharge ?? 0) // 充值金额
const displayName = computed(() => nickname.value || '未命名用户')
const displayAvatar = computed(() => avatar.value || '')
// 持久化数据
const userData = computed(() => ({
@@ -26,10 +33,7 @@ export const useUserStore = defineStore('user', () => {
userId: userId.value,
nickname: nickname.value,
avatar: avatar.value,
wechat: wechat.value,
balance: balance.value,
vipLevel: vipLevel.value,
credits: credits.value,
profile: profile.value,
}))
// 自动持久化
@@ -43,10 +47,7 @@ export const useUserStore = defineStore('user', () => {
userId.value = saved.userId || ''
nickname.value = saved.nickname || ''
avatar.value = saved.avatar || ''
wechat.value = saved.wechat || { openId: '', unionId: '', nickname: '', avatar: '' }
balance.value = Number(saved.balance || 0)
vipLevel.value = Number(saved.vipLevel || 0)
credits.value = Number(saved.credits || 0)
profile.value = saved.profile || null
}
hydrateFromStorage().then(() => {
@@ -54,17 +55,11 @@ export const useUserStore = defineStore('user', () => {
})
// 登录
const login = (profile) => {
const login = (data) => {
isLoggedIn.value = true
userId.value = String(profile.userId || profile.id || '')
nickname.value = profile.nickname || ''
avatar.value = profile.avatar || ''
if (profile.wechat) {
wechat.value = profile.wechat
}
balance.value = Number(profile.balance || 0)
vipLevel.value = Number(profile.vipLevel || 0)
credits.value = Number(profile.credits || 0)
userId.value = String(data.userId || data.id || '')
nickname.value = data.nickname || ''
avatar.value = data.avatar || ''
}
// 获取用户信息
@@ -75,7 +70,6 @@ export const useUserStore = defineStore('user', () => {
userId.value = String(userInfo.id || userInfo.userId || '')
nickname.value = userInfo.nickname || ''
avatar.value = userInfo.avatar || ''
if (userInfo.point !== undefined) credits.value = Number(userInfo.point || 0)
isLoggedIn.value = true
}
} catch (error) {
@@ -83,6 +77,18 @@ export const useUserStore = defineStore('user', () => {
}
}
// 获取用户档案
const fetchUserProfile = async () => {
try {
const profileData = await getUserProfile()
if (profileData) {
profile.value = profileData
}
} catch (error) {
console.error('获取用户档案失败:', error)
}
}
// 登出
const logout = async () => {
try {
@@ -96,10 +102,7 @@ export const useUserStore = defineStore('user', () => {
userId.value = ''
nickname.value = ''
avatar.value = ''
wechat.value = { openId: '', unionId: '', nickname: '', avatar: '' }
balance.value = 0
vipLevel.value = 0
credits.value = 0
profile.value = null
await remove(STORAGE_KEY)
}
@@ -110,18 +113,19 @@ export const useUserStore = defineStore('user', () => {
userId,
nickname,
avatar,
wechat,
balance,
vipLevel,
credits,
profile,
remainingPoints,
remainingStorage,
usedStorage,
totalStorage,
totalRecharge,
displayName,
displayAvatar,
login,
fetchUserInfo,
fetchUserProfile,
logout,
}
})
export default useUserStore

View File

@@ -1,18 +1,18 @@
package cn.iocoder.yudao.module.tik.member.mq.consumer;
import cn.iocoder.yudao.module.member.api.message.user.MemberUserCreateMessage;
import cn.iocoder.yudao.module.tik.muye.memberuserprofile.service.MemberUserProfileService;
import cn.iocoder.yudao.module.tik.quota.service.TikUserQuotaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import jakarta.annotation.Resource;
/**
* 会员用户创建事件监听器
*
* 功能:用户注册后自动初始化配额
*
* 功能:用户注册后自动初始化配额和档案
* 触发时机用户注册时MemberUserServiceImpl.createUser()
*
* @author 芋道源码
@@ -23,30 +23,28 @@ public class MemberUserCreateConsumer {
@Resource
private TikUserQuotaService quotaService;
@Resource
private MemberUserProfileService memberUserProfileService;
/**
* 监听用户创建事件(注册时触发)
*
* 同步执行,确保登录后立即可用
*
* @param message 用户创建消息
*/
@EventListener
@Async // 异步处理,避免阻塞主事务
public void onMessage(MemberUserCreateMessage message) {
log.info("[onMessage][用户注册事件,用户编号({})]", message.getUserId());
try {
Long userId = message.getUserId();
// 初始化用户配额默认VIP等级0
// 注意OSS目录采用懒加载策略在首次上传时再初始化
quotaService.initQuota(userId, 0);
log.info("[onMessage][用户({})配额初始化成功]", userId);
} catch (Exception e) {
log.error("[onMessage][用户({})配额初始化失败]", message.getUserId(), e);
// 注意:这里不抛出异常,避免影响用户注册流程
// 可以考虑记录失败日志,后续通过定时任务补偿
}
Long userId = message.getUserId();
// 初始化用户配额默认VIP等级0
quotaService.initQuota(userId, 0);
log.info("[onMessage][用户({})配额初始化成功]", userId);
// 初始化会员档案
memberUserProfileService.createIfAbsent(userId);
log.info("[onMessage][用户({})档案初始化成功]", userId);
}
}

View File

@@ -0,0 +1,37 @@
package cn.iocoder.yudao.module.tik.muye.memberuserprofile.controller.app;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.tik.muye.memberuserprofile.dal.MemberUserProfileDO;
import cn.iocoder.yudao.module.tik.muye.memberuserprofile.service.MemberUserProfileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
/**
* 用户 APP - 会员档案
*/
@Tag(name = "用户 APP - 会员档案")
@RestController
@RequestMapping("/api/muye/member-profile")
@Validated
public class AppMemberUserProfileController {
@Resource
private MemberUserProfileService memberUserProfileService;
@GetMapping("/get")
@Operation(summary = "获取当前用户档案")
public CommonResult<MemberUserProfileDO> getProfile() {
Long userId = SecurityFrameworkUtils.getLoginUserId();
MemberUserProfileDO profile = memberUserProfileService.createIfAbsent(userId);
return success(profile);
}
}

View File

@@ -40,10 +40,11 @@ public interface MemberUserProfileMapper extends BaseMapperX<MemberUserProfileDO
/**
* 根据用户ID查询档案
* @param userId 用户ID支持 String 或 Long 类型)
*/
default MemberUserProfileDO selectByUserId(String userId) {
default MemberUserProfileDO selectByUserId(Object userId) {
return selectOne(new LambdaQueryWrapperX<MemberUserProfileDO>()
.eq(MemberUserProfileDO::getUserId, userId));
.eq(MemberUserProfileDO::getUserId, String.valueOf(userId)));
}
/**

View File

@@ -60,4 +60,13 @@ public interface MemberUserProfileService {
*/
PageResult<MemberUserProfileDO> getMemberUserProfilePage(MemberUserProfilePageReqVO pageReqVO);
/**
* 根据用户ID获取或创建档案
* 如果档案不存在,则自动创建
*
* @param userId 用户ID
* @return 档案信息
*/
MemberUserProfileDO createIfAbsent(Long userId);
}

View File

@@ -10,6 +10,8 @@ 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.util.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
@@ -55,11 +57,9 @@ public class MemberUserProfileServiceImpl implements MemberUserProfileService {
}
@Override
public void deleteMemberUserProfileListByIds(List<Long> ids) {
// 删除
public void deleteMemberUserProfileListByIds(List<Long> ids) {
memberUserProfileMapper.deleteByIds(ids);
}
}
private void validateMemberUserProfileExists(Long id) {
if (memberUserProfileMapper.selectById(id) == null) {
@@ -77,4 +77,29 @@ public class MemberUserProfileServiceImpl implements MemberUserProfileService {
return memberUserProfileMapper.selectPage(pageReqVO);
}
@Override
public MemberUserProfileDO createIfAbsent(Long userId) {
// 1. 先查询是否存在
MemberUserProfileDO profile = memberUserProfileMapper.selectByUserId(userId);
if (profile != null) {
return profile;
}
// 2. 创建新档案
profile = new MemberUserProfileDO();
profile.setUserId(String.valueOf(userId));
profile.setRegisterTime(LocalDateTime.now());
profile.setLastLoginTime(LocalDateTime.now());
profile.setTotalPoints(0);
profile.setUsedPoints(0);
profile.setRemainingPoints(0);
profile.setTotalStorage(new BigDecimal("1.0"));
profile.setUsedStorage(BigDecimal.ZERO);
profile.setRemainingStorage(new BigDecimal("1.0"));
profile.setTotalRecharge(BigDecimal.ZERO);
profile.setStatus(1);
memberUserProfileMapper.insert(profile);
return profile;
}
}