feat: add user medal selection and display

This commit is contained in:
Tim
2025-08-10 00:13:54 +08:00
parent 6aedec7a9b
commit 041496cf98
14 changed files with 202 additions and 20 deletions

View File

@@ -1,12 +1,12 @@
package com.openisle.controller;
import com.openisle.dto.MedalDto;
import com.openisle.dto.MedalSelectRequest;
import com.openisle.service.MedalService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -20,4 +20,14 @@ public class MedalController {
public List<MedalDto> getMedals(@RequestParam(value = "userId", required = false) Long userId) {
return medalService.getMedals(userId);
}
@PostMapping("/select")
public ResponseEntity<Void> selectMedal(@RequestBody MedalSelectRequest req, Authentication auth) {
try {
medalService.selectMedal(auth.getName(), req.getType());
return ResponseEntity.ok().build();
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().build();
}
}
}

View File

@@ -1,6 +1,7 @@
package com.openisle.dto;
import lombok.Data;
import com.openisle.model.MedalType;
/**
* DTO representing a post or comment author.
@@ -10,5 +11,6 @@ public class AuthorDto {
private Long id;
private String username;
private String avatar;
private MedalType displayMedal;
}

View File

@@ -10,4 +10,5 @@ public class MedalDto {
private String description;
private MedalType type;
private boolean completed;
private boolean selected;
}

View File

@@ -0,0 +1,9 @@
package com.openisle.dto;
import com.openisle.model.MedalType;
import lombok.Data;
@Data
public class MedalSelectRequest {
private MedalType type;
}

View File

@@ -31,6 +31,7 @@ public class UserMapper {
dto.setId(user.getId());
dto.setUsername(user.getUsername());
dto.setAvatar(user.getAvatar());
dto.setDisplayMedal(user.getDisplayMedal());
return dto;
}

View File

@@ -59,6 +59,9 @@ public class User {
@Column(nullable = false)
private Role role = Role.USER;
@Enumerated(EnumType.STRING)
private MedalType displayMedal;
@CreationTimestamp
@Column(nullable = false, updatable = false,
columnDefinition = "DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6)")

View File

@@ -5,6 +5,7 @@ import com.openisle.dto.MedalDto;
import com.openisle.dto.PostMedalDto;
import com.openisle.dto.SeedUserMedalDto;
import com.openisle.model.MedalType;
import com.openisle.model.User;
import com.openisle.repository.CommentRepository;
import com.openisle.repository.PostRepository;
import com.openisle.repository.UserRepository;
@@ -28,6 +29,11 @@ public class MedalService {
public List<MedalDto> getMedals(Long userId) {
List<MedalDto> medals = new ArrayList<>();
User user = null;
if (userId != null) {
user = userRepository.findById(userId).orElse(null);
}
MedalType selected = user != null ? user.getDisplayMedal() : null;
CommentMedalDto commentMedal = new CommentMedalDto();
commentMedal.setIcon("https://openisle-1307107697.cos.ap-guangzhou.myqcloud.com/assert/icons/achi_comment.png");
@@ -35,7 +41,7 @@ public class MedalService {
commentMedal.setDescription("评论超过100条");
commentMedal.setType(MedalType.COMMENT);
commentMedal.setTargetCommentCount(COMMENT_TARGET);
if (userId != null) {
if (user != null) {
long count = commentRepository.countByAuthor_Id(userId);
commentMedal.setCurrentCommentCount(count);
commentMedal.setCompleted(count >= COMMENT_TARGET);
@@ -43,6 +49,7 @@ public class MedalService {
commentMedal.setCurrentCommentCount(0);
commentMedal.setCompleted(false);
}
commentMedal.setSelected(selected == MedalType.COMMENT);
medals.add(commentMedal);
PostMedalDto postMedal = new PostMedalDto();
@@ -51,7 +58,7 @@ public class MedalService {
postMedal.setDescription("发帖超过100条");
postMedal.setType(MedalType.POST);
postMedal.setTargetPostCount(POST_TARGET);
if (userId != null) {
if (user != null) {
long count = postRepository.countByAuthor_Id(userId);
postMedal.setCurrentPostCount(count);
postMedal.setCompleted(count >= POST_TARGET);
@@ -59,6 +66,7 @@ public class MedalService {
postMedal.setCurrentPostCount(0);
postMedal.setCompleted(false);
}
postMedal.setSelected(selected == MedalType.POST);
medals.add(postMedal);
SeedUserMedalDto seedUserMedal = new SeedUserMedalDto();
@@ -66,19 +74,29 @@ public class MedalService {
seedUserMedal.setTitle("种子用户");
seedUserMedal.setDescription("2025.9.16前注册的用户");
seedUserMedal.setType(MedalType.SEED);
if (userId != null) {
userRepository.findById(userId).ifPresent(user -> {
seedUserMedal.setRegisterDate(user.getCreatedAt());
seedUserMedal.setCompleted(user.getCreatedAt().isBefore(SEED_USER_DEADLINE));
});
if (seedUserMedal.getRegisterDate() == null) {
seedUserMedal.setCompleted(false);
}
if (user != null) {
seedUserMedal.setRegisterDate(user.getCreatedAt());
seedUserMedal.setCompleted(user.getCreatedAt().isBefore(SEED_USER_DEADLINE));
} else {
seedUserMedal.setCompleted(false);
}
seedUserMedal.setSelected(selected == MedalType.SEED);
medals.add(seedUserMedal);
return medals;
}
public void selectMedal(String username, MedalType type) {
User user = userRepository.findByUsername(username).orElseThrow();
boolean completed = getMedals(user.getId()).stream()
.filter(m -> m.getType() == type)
.findFirst()
.map(MedalDto::isCompleted)
.orElse(false);
if (!completed) {
throw new IllegalArgumentException("Medal not completed");
}
user.setDisplayMedal(type);
userRepository.save(user);
}
}

View File

@@ -9,11 +9,13 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -49,4 +51,24 @@ class MedalControllerTest {
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].completed").value(true));
}
@Test
void selectMedal() throws Exception {
mockMvc.perform(post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user"))
.andExpect(status().isOk());
}
@Test
void selectMedalBadRequest() throws Exception {
Mockito.doThrow(new IllegalArgumentException()).when(medalService)
.selectMedal("user", MedalType.COMMENT);
mockMvc.perform(post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user"))
.andExpect(status().isBadRequest());
}
}

View File

@@ -41,13 +41,55 @@ class MedalServiceTest {
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
user.setDisplayMedal(MedalType.COMMENT);
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
MedalService service = new MedalService(commentRepo, postRepo, userRepo);
List<MedalDto> medals = service.getMedals(1L);
assertTrue(medals.stream().filter(m -> m.getType() == MedalType.COMMENT).findFirst().orElseThrow().isCompleted());
assertTrue(medals.stream().filter(m -> m.getType() == MedalType.COMMENT).findFirst().orElseThrow().isSelected());
assertFalse(medals.stream().filter(m -> m.getType() == MedalType.POST).findFirst().orElseThrow().isCompleted());
assertFalse(medals.stream().filter(m -> m.getType() == MedalType.POST).findFirst().orElseThrow().isSelected());
assertTrue(medals.stream().filter(m -> m.getType() == MedalType.SEED).findFirst().orElseThrow().isCompleted());
assertFalse(medals.stream().filter(m -> m.getType() == MedalType.SEED).findFirst().orElseThrow().isSelected());
}
@Test
void selectMedal() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
when(commentRepo.countByAuthor_Id(1L)).thenReturn(120L);
when(postRepo.countByAuthor_Id(1L)).thenReturn(0L);
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
MedalService service = new MedalService(commentRepo, postRepo, userRepo);
service.selectMedal("user", MedalType.COMMENT);
assertEquals(MedalType.COMMENT, user.getDisplayMedal());
}
@Test
void selectMedalNotCompleted() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
when(commentRepo.countByAuthor_Id(1L)).thenReturn(10L);
when(postRepo.countByAuthor_Id(1L)).thenReturn(0L);
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
MedalService service = new MedalService(commentRepo, postRepo, userRepo);
assertThrows(IllegalArgumentException.class, () -> service.selectMedal("user", MedalType.COMMENT));
}
}

View File

@@ -3,14 +3,15 @@
<div
v-for="medal in sortedMedals"
:key="medal.type"
class="achievements-list-item select"
:class="['achievements-list-item', { select: medal.selected, clickable: canSelect }]"
@click="selectMedal(medal)"
>
<img
:src="medal.icon"
:alt="medal.title"
:class="['achievements-list-item-icon', { not_completed: !medal.completed }]"
/>
<div class="achievements-list-item-top-right-label">展示</div>
<div v-if="medal.selected" class="achievements-list-item-top-right-label">展示</div>
<div class="achievements-list-item-title">{{ medal.title }}</div>
<div class="achievements-list-item-description">
{{ medal.description }}
@@ -27,12 +28,18 @@
<script setup>
import { computed } from 'vue'
import { API_BASE_URL, toast } from '../main'
import { getToken } from '../utils/auth'
const props = defineProps({
medals: {
type: Array,
required: true,
default: () => []
},
canSelect: {
type: Boolean,
default: false
}
})
@@ -43,6 +50,32 @@ const sortedMedals = computed(() => {
})
})
const selectMedal = async (medal) => {
if (!props.canSelect || medal.selected) return
if (!medal.completed) {
toast('该勋章尚未完成')
return
}
try {
const res = await fetch(`${API_BASE_URL}/api/medals/select`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`
},
body: JSON.stringify({ type: medal.type })
})
if (res.ok) {
props.medals.forEach(m => { m.selected = m.type === medal.type })
toast('展示勋章已更新')
} else {
toast('选择勋章失败')
}
} catch (e) {
toast('选择勋章失败')
}
}
</script>
<style scoped>
@@ -66,6 +99,10 @@ const sortedMedals = computed(() => {
border-radius: 10px;
}
.achievements-list-item.clickable {
cursor: pointer;
}
.achievements-list-item.select {
border: 2px solid var(--primary-color);
}

View File

@@ -11,6 +11,7 @@
<div class="common-info-content-header">
<div class="info-content-header-left">
<span class="user-name">{{ comment.userName }}</span>
<span v-if="comment.medal" class="medal-name">{{ getMedalTitle(comment.medal) }}</span>
<span v-if="level >= 2">
<i class="fas fa-reply reply-icon"></i>
<span class="user-name reply-user-name">{{ comment.parentUserName }}</span>
@@ -64,6 +65,7 @@ import VueEasyLightbox from 'vue-easy-lightbox'
import { useRouter } from 'vue-router'
import CommentEditor from './CommentEditor.vue'
import { renderMarkdown, handleMarkdownClick } from '../utils/markdown'
import { getMedalTitle } from '../utils/medal'
import TimeManager from '../utils/time'
import BaseTimeline from './BaseTimeline.vue'
import { API_BASE_URL, toast } from '../main'
@@ -232,7 +234,7 @@ const CommentItem = {
lightboxVisible.value = true
}
}
return { showReplies, toggleReplies, showEditor, toggleEditor, submitReply, copyCommentLink, renderMarkdown, isWaitingForReply, commentMenuItems, deleteComment, lightboxVisible, lightboxIndex, lightboxImgs, handleContentClick, loggedIn, replyCount, replyList }
return { showReplies, toggleReplies, showEditor, toggleEditor, submitReply, copyCommentLink, renderMarkdown, isWaitingForReply, commentMenuItems, deleteComment, lightboxVisible, lightboxIndex, lightboxImgs, handleContentClick, loggedIn, replyCount, replyList, getMedalTitle }
}
}
@@ -283,6 +285,12 @@ export default CommentItem
opacity: 0.3;
}
.medal-name {
font-size: 12px;
margin-left: 4px;
opacity: 0.6;
}
@keyframes highlight {
from {
background-color: yellow;

View File

@@ -41,14 +41,20 @@
<img class="user-avatar-item-img" :src="author.avatar" alt="avatar">
</div>
<div v-if="isMobile" class="info-content-header">
<div class="user-name">{{ author.username }}</div>
<div class="user-name">
{{ author.username }}
<span v-if="author.displayMedal" class="user-medal">{{ getMedalTitle(author.displayMedal) }}</span>
</div>
<div class="post-time">{{ postTime }}</div>
</div>
</div>
<div class="info-content">
<div v-if="!isMobile" class="info-content-header">
<div class="user-name">{{ author.username }}</div>
<div class="user-name">
{{ author.username }}
<span v-if="author.displayMedal" class="user-medal">{{ getMedalTitle(author.displayMedal) }}</span>
</div>
<div class="post-time">{{ postTime }}</div>
</div>
<div class="info-content-text" v-html="renderMarkdown(postContent)" @click="handleContentClick"></div>
@@ -116,6 +122,7 @@ import ArticleCategory from '../../../components/ArticleCategory.vue'
import ReactionsGroup from '../../../components/ReactionsGroup.vue'
import DropdownMenu from '../../../components/DropdownMenu.vue'
import { renderMarkdown, handleMarkdownClick, stripMarkdownLength } from '../../../utils/markdown'
import { getMedalTitle } from '../../../utils/medal'
import { API_BASE_URL, toast } from '../../../main'
import { getToken, authState } from '../../../utils/auth'
import TimeManager from '../../../utils/time'
@@ -228,6 +235,7 @@ export default {
const mapComment = (c, parentUserName = '', level = 0) => ({
id: c.id,
userName: c.author.username,
medal: c.author.displayMedal,
time: TimeManager.format(c.createdAt),
avatar: c.author.avatar,
text: c.content,
@@ -648,6 +656,8 @@ export default {
commentSort,
fetchCommentSorts,
isFetchingComments
,
getMedalTitle
}
}
}
@@ -926,6 +936,12 @@ export default {
opacity: 0.7;
}
.user-medal {
font-size: 12px;
margin-left: 4px;
opacity: 0.6;
}
.post-time {
font-size: 14px;
opacity: 0.5;
@@ -990,6 +1006,10 @@ export default {
font-size: 14px;
}
.user-medal {
font-size: 12px;
}
.post-time {
font-size: 12px;
}

View File

@@ -244,7 +244,7 @@
</div>
<div v-else-if="selectedTab === 'achievements'" class="achievements-container">
<AchievementList :medals="medals" />
<AchievementList :medals="medals" :can-select="isMine" />
</div>
</template>
</div>

View File

@@ -0,0 +1,9 @@
export const medalTitles = {
COMMENT: '评论达人',
POST: '发帖达人',
SEED: '种子用户'
}
export function getMedalTitle(type) {
return medalTitles[type] || ''
}