mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-21 14:30:59 +08:00
Merge pull request #447 from nagisa77/codex/add-new-medallions-and-related-api
feat: implement medal API
This commit is contained in:
@@ -2,8 +2,10 @@ package com.openisle;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class OpenIsleApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(OpenIsleApplication.class, args);
|
||||
|
||||
@@ -112,6 +112,7 @@ public class SecurityConfig {
|
||||
.requestMatchers(HttpMethod.POST,"/api/auth/reason").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/search/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/users/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/medals/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/push/public-key").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/reaction-types").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/activities/**").permitAll()
|
||||
@@ -147,7 +148,7 @@ public class SecurityConfig {
|
||||
uri.startsWith("/api/search") || uri.startsWith("/api/users") ||
|
||||
uri.startsWith("/api/reaction-types") || uri.startsWith("/api/config") ||
|
||||
uri.startsWith("/api/activities") || uri.startsWith("/api/push/public-key") ||
|
||||
uri.startsWith("/api/sitemap.xml"));
|
||||
uri.startsWith("/api/sitemap.xml") || uri.startsWith("/api/medals"));
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
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.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/medals")
|
||||
@RequiredArgsConstructor
|
||||
public class MedalController {
|
||||
private final MedalService medalService;
|
||||
|
||||
@GetMapping
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
11
backend/src/main/java/com/openisle/dto/CommentMedalDto.java
Normal file
11
backend/src/main/java/com/openisle/dto/CommentMedalDto.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.openisle.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class CommentMedalDto extends MedalDto {
|
||||
private long currentCommentCount;
|
||||
private long targetCommentCount;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.openisle.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class ContributorMedalDto extends MedalDto {
|
||||
private long currentContributionLines;
|
||||
private long targetContributionLines;
|
||||
}
|
||||
|
||||
14
backend/src/main/java/com/openisle/dto/MedalDto.java
Normal file
14
backend/src/main/java/com/openisle/dto/MedalDto.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.openisle.dto;
|
||||
|
||||
import com.openisle.model.MedalType;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class MedalDto {
|
||||
private String icon;
|
||||
private String title;
|
||||
private String description;
|
||||
private MedalType type;
|
||||
private boolean completed;
|
||||
private boolean selected;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.openisle.dto;
|
||||
|
||||
import com.openisle.model.MedalType;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class MedalSelectRequest {
|
||||
private MedalType type;
|
||||
}
|
||||
11
backend/src/main/java/com/openisle/dto/PostMedalDto.java
Normal file
11
backend/src/main/java/com/openisle/dto/PostMedalDto.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.openisle.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class PostMedalDto extends MedalDto {
|
||||
private long currentPostCount;
|
||||
private long targetPostCount;
|
||||
}
|
||||
11
backend/src/main/java/com/openisle/dto/SeedUserMedalDto.java
Normal file
11
backend/src/main/java/com/openisle/dto/SeedUserMedalDto.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.openisle.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class SeedUserMedalDto extends MedalDto {
|
||||
private LocalDateTime registerDate;
|
||||
}
|
||||
@@ -22,19 +22,23 @@ public class UserMapper {
|
||||
private final UserVisitService userVisitService;
|
||||
private final PostReadService postReadService;
|
||||
private final LevelService levelService;
|
||||
private final MedalService medalService;
|
||||
|
||||
@Value("${app.snippet-length:50}")
|
||||
private int snippetLength;
|
||||
|
||||
public AuthorDto toAuthorDto(User user) {
|
||||
medalService.ensureDisplayMedal(user);
|
||||
AuthorDto dto = new AuthorDto();
|
||||
dto.setId(user.getId());
|
||||
dto.setUsername(user.getUsername());
|
||||
dto.setAvatar(user.getAvatar());
|
||||
dto.setDisplayMedal(user.getDisplayMedal());
|
||||
return dto;
|
||||
}
|
||||
|
||||
public UserDto toDto(User user, Authentication viewer) {
|
||||
medalService.ensureDisplayMedal(user);
|
||||
UserDto dto = new UserDto();
|
||||
dto.setId(user.getId());
|
||||
dto.setUsername(user.getUsername());
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.openisle.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Table(name = "contributor_configs")
|
||||
public class ContributorConfig {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private String userIname;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private String githubId;
|
||||
|
||||
@Column(nullable = false)
|
||||
private long contributionLines = 0;
|
||||
}
|
||||
|
||||
8
backend/src/main/java/com/openisle/model/MedalType.java
Normal file
8
backend/src/main/java/com/openisle/model/MedalType.java
Normal file
@@ -0,0 +1,8 @@
|
||||
package com.openisle.model;
|
||||
|
||||
public enum MedalType {
|
||||
COMMENT,
|
||||
POST,
|
||||
CONTRIBUTOR,
|
||||
SEED
|
||||
}
|
||||
@@ -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)")
|
||||
|
||||
@@ -30,4 +30,6 @@ public interface CommentRepository extends JpaRepository<Comment, Long> {
|
||||
@org.springframework.data.jpa.repository.Query("SELECT COUNT(c) FROM Comment c WHERE c.post.id = :postId")
|
||||
long countByPostId(@org.springframework.data.repository.query.Param("postId") Long postId);
|
||||
|
||||
long countByAuthor_Id(Long userId);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.openisle.repository;
|
||||
|
||||
import com.openisle.model.ContributorConfig;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface ContributorConfigRepository extends JpaRepository<ContributorConfig, Long> {
|
||||
Optional<ContributorConfig> findByUserIname(String userIname);
|
||||
}
|
||||
|
||||
@@ -93,4 +93,6 @@ public interface PostRepository extends JpaRepository<Post, Long> {
|
||||
long countByCategory_Id(Long categoryId);
|
||||
|
||||
long countDistinctByTags_Id(Long tagId);
|
||||
|
||||
long countByAuthor_Id(Long userId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.model.ContributorConfig;
|
||||
import com.openisle.repository.ContributorConfigRepository;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ContributorService {
|
||||
private static final String OWNER = "nagisa77";
|
||||
private static final String REPO = "OpenIsle";
|
||||
|
||||
private final ContributorConfigRepository repository;
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
@PostConstruct
|
||||
@Scheduled(cron = "0 0 * * * *")
|
||||
public void updateContributions() {
|
||||
for (ContributorConfig config : repository.findAll()) {
|
||||
long lines = fetchContributionLines(config.getGithubId());
|
||||
config.setContributionLines(lines);
|
||||
repository.save(config);
|
||||
}
|
||||
}
|
||||
|
||||
private long fetchContributionLines(String githubId) {
|
||||
try {
|
||||
String url = String.format("https://api.github.com/repos/%s/%s/stats/contributors", OWNER, REPO);
|
||||
ResponseEntity<?> response = restTemplate.getForEntity(url, Object.class);
|
||||
|
||||
// 检查是否为202,GitHub有时会返回202表示正在生成统计数据
|
||||
if (response.getStatusCodeValue() == 202) {
|
||||
log.warn("GitHub API 返回202,统计数据正在生成中,githubId: {}", githubId);
|
||||
return 0;
|
||||
}
|
||||
|
||||
Object body = response.getBody();
|
||||
if (!(body instanceof List)) {
|
||||
// 不是List类型,直接返回0
|
||||
return 0;
|
||||
}
|
||||
List<?> listBody = (List<?>) body;
|
||||
for (Object itemObj : listBody) {
|
||||
if (!(itemObj instanceof Map)) continue;
|
||||
Map<String, Object> item = (Map<String, Object>) itemObj;
|
||||
Map<String, Object> author = (Map<String, Object>) item.get("author");
|
||||
if (author != null && githubId.equals(author.get("login"))) {
|
||||
List<Map<String, Object>> weeks = (List<Map<String, Object>>) item.get("weeks");
|
||||
long total = 0;
|
||||
if (weeks != null) {
|
||||
for (Map<String, Object> week : weeks) {
|
||||
Number a = (Number) week.get("a");
|
||||
Number d = (Number) week.get("d");
|
||||
if (a != null) {
|
||||
total += a.longValue();
|
||||
}
|
||||
if (d != null) {
|
||||
total += d.longValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn(e.getMessage());
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public long getContributionLines(String userIname) {
|
||||
return repository.findByUserIname(userIname)
|
||||
.map(ContributorConfig::getContributionLines)
|
||||
.orElse(0L);
|
||||
}
|
||||
}
|
||||
|
||||
150
backend/src/main/java/com/openisle/service/MedalService.java
Normal file
150
backend/src/main/java/com/openisle/service/MedalService.java
Normal file
@@ -0,0 +1,150 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.dto.CommentMedalDto;
|
||||
import com.openisle.dto.ContributorMedalDto;
|
||||
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;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MedalService {
|
||||
private static final long COMMENT_TARGET = 100;
|
||||
private static final long POST_TARGET = 100;
|
||||
private static final LocalDateTime SEED_USER_DEADLINE = LocalDateTime.of(2025, 9, 16, 0, 0);
|
||||
private static final long CONTRIBUTION_TARGET = 1;
|
||||
|
||||
private final CommentRepository commentRepository;
|
||||
private final PostRepository postRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final ContributorService contributorService;
|
||||
|
||||
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");
|
||||
commentMedal.setTitle("评论达人");
|
||||
commentMedal.setDescription("评论超过100条");
|
||||
commentMedal.setType(MedalType.COMMENT);
|
||||
commentMedal.setTargetCommentCount(COMMENT_TARGET);
|
||||
if (user != null) {
|
||||
long count = commentRepository.countByAuthor_Id(userId);
|
||||
commentMedal.setCurrentCommentCount(count);
|
||||
commentMedal.setCompleted(count >= COMMENT_TARGET);
|
||||
} else {
|
||||
commentMedal.setCurrentCommentCount(0);
|
||||
commentMedal.setCompleted(false);
|
||||
}
|
||||
commentMedal.setSelected(selected == MedalType.COMMENT);
|
||||
medals.add(commentMedal);
|
||||
|
||||
PostMedalDto postMedal = new PostMedalDto();
|
||||
postMedal.setIcon("https://openisle-1307107697.cos.ap-guangzhou.myqcloud.com/assert/icons/achi_post.png");
|
||||
postMedal.setTitle("发帖达人");
|
||||
postMedal.setDescription("发帖超过100条");
|
||||
postMedal.setType(MedalType.POST);
|
||||
postMedal.setTargetPostCount(POST_TARGET);
|
||||
if (user != null) {
|
||||
long count = postRepository.countByAuthor_Id(userId);
|
||||
postMedal.setCurrentPostCount(count);
|
||||
postMedal.setCompleted(count >= POST_TARGET);
|
||||
} else {
|
||||
postMedal.setCurrentPostCount(0);
|
||||
postMedal.setCompleted(false);
|
||||
}
|
||||
postMedal.setSelected(selected == MedalType.POST);
|
||||
medals.add(postMedal);
|
||||
|
||||
ContributorMedalDto contributorMedal = new ContributorMedalDto();
|
||||
contributorMedal.setIcon("https://openisle-1307107697.cos.ap-guangzhou.myqcloud.com/assert/icons/achi_coder.png");
|
||||
contributorMedal.setTitle("贡献者");
|
||||
contributorMedal.setDescription("对仓库贡献超过1行代码");
|
||||
contributorMedal.setType(MedalType.CONTRIBUTOR);
|
||||
contributorMedal.setTargetContributionLines(CONTRIBUTION_TARGET);
|
||||
if (user != null) {
|
||||
long lines = contributorService.getContributionLines(user.getUsername());
|
||||
contributorMedal.setCurrentContributionLines(lines);
|
||||
contributorMedal.setCompleted(lines >= CONTRIBUTION_TARGET);
|
||||
} else {
|
||||
contributorMedal.setCurrentContributionLines(0);
|
||||
contributorMedal.setCompleted(false);
|
||||
}
|
||||
contributorMedal.setSelected(selected == MedalType.CONTRIBUTOR);
|
||||
medals.add(contributorMedal);
|
||||
|
||||
SeedUserMedalDto seedUserMedal = new SeedUserMedalDto();
|
||||
seedUserMedal.setIcon("https://openisle-1307107697.cos.ap-guangzhou.myqcloud.com/assert/icons/achi_seed.png");
|
||||
seedUserMedal.setTitle("种子用户");
|
||||
seedUserMedal.setDescription("2025.9.16前注册的用户");
|
||||
seedUserMedal.setType(MedalType.SEED);
|
||||
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);
|
||||
if (user != null && selected == null) {
|
||||
for (MedalDto medal : medals) {
|
||||
if (medal.isCompleted()) {
|
||||
medal.setSelected(true);
|
||||
user.setDisplayMedal(medal.getType());
|
||||
userRepository.save(user);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return medals;
|
||||
}
|
||||
|
||||
public void ensureDisplayMedal(User user) {
|
||||
if (user == null || user.getDisplayMedal() != null) {
|
||||
return;
|
||||
}
|
||||
if (commentRepository.countByAuthor_Id(user.getId()) >= COMMENT_TARGET) {
|
||||
user.setDisplayMedal(MedalType.COMMENT);
|
||||
} else if (postRepository.countByAuthor_Id(user.getId()) >= POST_TARGET) {
|
||||
user.setDisplayMedal(MedalType.POST);
|
||||
} else if (contributorService.getContributionLines(user.getUsername()) >= CONTRIBUTION_TARGET) {
|
||||
user.setDisplayMedal(MedalType.CONTRIBUTOR);
|
||||
} else if (user.getCreatedAt().isBefore(SEED_USER_DEADLINE)) {
|
||||
user.setDisplayMedal(MedalType.SEED);
|
||||
}
|
||||
if (user.getDisplayMedal() != null) {
|
||||
userRepository.save(user);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.dto.CommentMedalDto;
|
||||
import com.openisle.model.MedalType;
|
||||
import com.openisle.service.MedalService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
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;
|
||||
|
||||
@WebMvcTest(MedalController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class MedalControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private MedalService medalService;
|
||||
|
||||
@Test
|
||||
void listMedals() throws Exception {
|
||||
CommentMedalDto medal = new CommentMedalDto();
|
||||
medal.setTitle("评论达人");
|
||||
medal.setType(MedalType.COMMENT);
|
||||
Mockito.when(medalService.getMedals(null)).thenReturn(List.of(medal));
|
||||
|
||||
mockMvc.perform(get("/api/medals"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].title").value("评论达人"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listMedalsWithUser() throws Exception {
|
||||
CommentMedalDto medal = new CommentMedalDto();
|
||||
medal.setCompleted(true);
|
||||
medal.setType(MedalType.COMMENT);
|
||||
Mockito.when(medalService.getMedals(1L)).thenReturn(List.of(medal));
|
||||
|
||||
mockMvc.perform(get("/api/medals").param("userId", "1"))
|
||||
.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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.dto.MedalDto;
|
||||
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;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class MedalServiceTest {
|
||||
@Test
|
||||
void getMedalsWithoutUser() {
|
||||
CommentRepository commentRepo = mock(CommentRepository.class);
|
||||
PostRepository postRepo = mock(PostRepository.class);
|
||||
UserRepository userRepo = mock(UserRepository.class);
|
||||
|
||||
MedalService service = new MedalService(commentRepo, postRepo, userRepo);
|
||||
|
||||
List<MedalDto> medals = service.getMedals(null);
|
||||
assertFalse(medals.get(0).isCompleted());
|
||||
assertFalse(medals.get(1).isCompleted());
|
||||
assertFalse(medals.get(2).isCompleted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMedalsWithUser() {
|
||||
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(80L);
|
||||
User user = new User();
|
||||
user.setId(1L);
|
||||
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
|
||||
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);
|
||||
|
||||
assertEquals(MedalType.COMMENT, user.getDisplayMedal());
|
||||
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());
|
||||
verify(userRepo).save(user);
|
||||
}
|
||||
|
||||
@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));
|
||||
}
|
||||
}
|
||||
163
frontend_nuxt/components/AchievementList.vue
Normal file
163
frontend_nuxt/components/AchievementList.vue
Normal file
@@ -0,0 +1,163 @@
|
||||
<template>
|
||||
<div class="achievements-list">
|
||||
<div
|
||||
v-for="medal in sortedMedals"
|
||||
:key="medal.type"
|
||||
:class="['achievements-list-item', { select: medal.selected && canSelect, clickable: canSelect }]"
|
||||
@click="selectMedal(medal)"
|
||||
>
|
||||
<img
|
||||
:src="medal.icon"
|
||||
:alt="medal.title"
|
||||
:class="['achievements-list-item-icon', { not_completed: !medal.completed }]"
|
||||
/>
|
||||
<div v-if="medal.selected && canSelect" 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 }}
|
||||
<template v-if="medal.type === 'COMMENT'">
|
||||
{{ medal.currentCommentCount }}/{{ medal.targetCommentCount }}
|
||||
</template>
|
||||
<template v-else-if="medal.type === 'POST'">
|
||||
{{ medal.currentPostCount }}/{{ medal.targetPostCount }}
|
||||
</template>
|
||||
<template v-else-if="medal.type === 'CONTRIBUTOR'">
|
||||
{{ medal.currentContributionLines }}/{{ medal.targetContributionLines }}
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<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
|
||||
}
|
||||
})
|
||||
|
||||
const sortedMedals = computed(() => {
|
||||
return [...props.medals].sort((a, b) => {
|
||||
if (a.completed === b.completed) return 0
|
||||
return a.completed ? -1 : 1
|
||||
})
|
||||
})
|
||||
|
||||
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>
|
||||
.achievements-list {
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
flex-direction: flex-start;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.achievements-list-item {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
|
||||
padding: 10px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.achievements-list-item.clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.achievements-list-item.select {
|
||||
border: 2px solid var(--primary-color);
|
||||
}
|
||||
|
||||
.achievements-list-item-icon {
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
}
|
||||
|
||||
.achievements-list-item-title {
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.achievements-list-item-description {
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.not_completed {
|
||||
filter: grayscale(100%);
|
||||
}
|
||||
|
||||
.achievements-list-item-top-right-label {
|
||||
font-size: 10px;
|
||||
color: white;
|
||||
background-color: var(--primary-color);
|
||||
padding: 2px 4px;
|
||||
border-radius: 2px;
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.achievements-list-item-icon {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
}
|
||||
|
||||
.achievements-list-item-title {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.achievements-list-item-description {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.achievements-list-item {
|
||||
min-width: calc(50% - 30px);
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
@@ -11,6 +11,12 @@
|
||||
<div class="common-info-content-header">
|
||||
<div class="info-content-header-left">
|
||||
<span class="user-name">{{ comment.userName }}</span>
|
||||
<i class="fas fa-medal medal-icon"></i>
|
||||
<router-link
|
||||
v-if="comment.medal"
|
||||
class="medal-name"
|
||||
:to="`/users/${comment.userId}?tab=achievements`"
|
||||
>{{ getMedalTitle(comment.medal) }}</router-link>
|
||||
<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 +70,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 +239,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 +290,23 @@ export default CommentItem
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.medal-name {
|
||||
font-size: 12px;
|
||||
margin-left: 1px;
|
||||
opacity: 0.6;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.medal-icon {
|
||||
font-size: 12px;
|
||||
opacity: 0.6;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
@keyframes highlight {
|
||||
from {
|
||||
background-color: yellow;
|
||||
|
||||
@@ -6,24 +6,36 @@
|
||||
text="建站送奶茶活动火热进行中,快来参与吧!"
|
||||
@close="closeMilkTeaPopup"
|
||||
/>
|
||||
<MedalPopup
|
||||
:visible="showMedalPopup"
|
||||
:medals="newMedals"
|
||||
@close="closeMedalPopup"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import ActivityPopup from '~/components/ActivityPopup.vue'
|
||||
import MedalPopup from '~/components/MedalPopup.vue'
|
||||
import { API_BASE_URL } from '~/main'
|
||||
import { authState } from '~/utils/auth'
|
||||
|
||||
export default {
|
||||
name: 'GlobalPopups',
|
||||
components: { ActivityPopup },
|
||||
components: { ActivityPopup, MedalPopup },
|
||||
data () {
|
||||
return {
|
||||
showMilkTeaPopup: false,
|
||||
milkTeaIcon: ''
|
||||
milkTeaIcon: '',
|
||||
showMedalPopup: false,
|
||||
newMedals: []
|
||||
}
|
||||
},
|
||||
async mounted () {
|
||||
await this.checkMilkTeaActivity()
|
||||
if (!this.showMilkTeaPopup) {
|
||||
await this.checkNewMedals()
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async checkMilkTeaActivity () {
|
||||
@@ -47,7 +59,34 @@ export default {
|
||||
if (!process.client) return
|
||||
localStorage.setItem('milkTeaActivityPopupShown', 'true')
|
||||
this.showMilkTeaPopup = false
|
||||
this.checkNewMedals()
|
||||
},
|
||||
async checkNewMedals () {
|
||||
if (!process.client) return
|
||||
if (!authState.loggedIn || !authState.userId) return
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/medals?userId=${authState.userId}`)
|
||||
if (res.ok) {
|
||||
const medals = await res.json()
|
||||
const seen = JSON.parse(localStorage.getItem('seenMedals') || '[]')
|
||||
const m = medals.filter(i => i.completed && !seen.includes(i.type))
|
||||
if (m.length > 0) {
|
||||
this.newMedals = m
|
||||
this.showMedalPopup = true
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore errors
|
||||
}
|
||||
},
|
||||
closeMedalPopup () {
|
||||
if (!process.client) return
|
||||
const seen = new Set(JSON.parse(localStorage.getItem('seenMedals') || '[]'))
|
||||
this.newMedals.forEach(m => seen.add(m.type))
|
||||
localStorage.setItem('seenMedals', JSON.stringify([...seen]))
|
||||
this.showMedalPopup = false
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
113
frontend_nuxt/components/MedalPopup.vue
Normal file
113
frontend_nuxt/components/MedalPopup.vue
Normal file
@@ -0,0 +1,113 @@
|
||||
<template>
|
||||
<BasePopup :visible="visible" @close="close">
|
||||
<div class="medal-popup">
|
||||
<div class="medal-popup-title">恭喜你获得以下勋章</div>
|
||||
<div class="medal-popup-list">
|
||||
<div v-for="medal in medals" :key="medal.type" class="medal-popup-item">
|
||||
<img :src="medal.icon" :alt="medal.title" class="medal-popup-item-icon" />
|
||||
<div class="medal-popup-item-title">{{ medal.title }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="medal-popup-actions">
|
||||
<div class="medal-popup-close" @click="close">知道了</div>
|
||||
<div class="medal-popup-button" @click="gotoMedals">去看看</div>
|
||||
</div>
|
||||
</div>
|
||||
</BasePopup>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import BasePopup from '~/components/BasePopup.vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { authState } from '~/utils/auth'
|
||||
|
||||
export default {
|
||||
name: 'MedalPopup',
|
||||
components: { BasePopup },
|
||||
props: {
|
||||
visible: { type: Boolean, default: false },
|
||||
medals: { type: Array, default: () => [] }
|
||||
},
|
||||
emits: ['close'],
|
||||
setup (props, { emit }) {
|
||||
const router = useRouter()
|
||||
const gotoMedals = () => {
|
||||
emit('close')
|
||||
if (authState.username) {
|
||||
router.push(`/users/${authState.username}?tab=achievements`)
|
||||
} else {
|
||||
router.push('/')
|
||||
}
|
||||
}
|
||||
const close = () => emit('close')
|
||||
return { gotoMedals, close }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.medal-popup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
gap: 10px;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.medal-popup-title {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.medal-popup-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.medal-popup-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.medal-popup-item-icon {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.medal-popup-actions {
|
||||
margin-top: 10px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.medal-popup-button {
|
||||
background-color: var(--primary-color);
|
||||
color: #fff;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.medal-popup-button:hover {
|
||||
background-color: var(--primary-color-hover);
|
||||
}
|
||||
|
||||
.medal-popup-close {
|
||||
cursor: pointer;
|
||||
color: var(--primary-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.medal-popup-close:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -41,14 +41,28 @@
|
||||
<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 }}
|
||||
<router-link
|
||||
v-if="author.displayMedal"
|
||||
class="user-medal"
|
||||
:to="`/users/${author.id}?tab=achievements`"
|
||||
>{{ getMedalTitle(author.displayMedal) }}</router-link>
|
||||
</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 }}
|
||||
<router-link
|
||||
v-if="author.displayMedal"
|
||||
class="user-medal"
|
||||
:to="`/users/${author.id}?tab=achievements`"
|
||||
>{{ getMedalTitle(author.displayMedal) }}</router-link>
|
||||
</div>
|
||||
<div class="post-time">{{ postTime }}</div>
|
||||
</div>
|
||||
<div class="info-content-text" v-html="renderMarkdown(postContent)" @click="handleContentClick"></div>
|
||||
@@ -116,6 +130,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 +243,8 @@ export default {
|
||||
const mapComment = (c, parentUserName = '', level = 0) => ({
|
||||
id: c.id,
|
||||
userName: c.author.username,
|
||||
medal: c.author.displayMedal,
|
||||
userId: c.author.id,
|
||||
time: TimeManager.format(c.createdAt),
|
||||
avatar: c.author.avatar,
|
||||
text: c.content,
|
||||
@@ -648,6 +665,8 @@ export default {
|
||||
commentSort,
|
||||
fetchCommentSorts,
|
||||
isFetchingComments
|
||||
,
|
||||
getMedalTitle
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -926,6 +945,13 @@ export default {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.user-medal {
|
||||
font-size: 12px;
|
||||
margin-left: 4px;
|
||||
opacity: 0.6;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.post-time {
|
||||
font-size: 14px;
|
||||
opacity: 0.5;
|
||||
@@ -990,6 +1016,10 @@ export default {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.user-medal {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.post-time {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@@ -20,17 +20,10 @@
|
||||
<i class="fas fa-user-minus"></i>
|
||||
取消关注
|
||||
</div>
|
||||
<LevelProgress
|
||||
:exp="levelInfo.exp"
|
||||
:current-level="levelInfo.currentLevel"
|
||||
:next-exp="levelInfo.nextExp"
|
||||
/>
|
||||
<LevelProgress :exp="levelInfo.exp" :current-level="levelInfo.currentLevel" :next-exp="levelInfo.nextExp" />
|
||||
<div class="profile-level-target">
|
||||
目标 Lv.{{ levelInfo.currentLevel + 1 }}
|
||||
<i
|
||||
class="fas fa-info-circle profile-exp-info"
|
||||
title="经验值可通过发帖、评论等操作获得,达到目标后即可提升等级,解锁更多功能。"
|
||||
></i>
|
||||
<i class="fas fa-info-circle profile-exp-info" title="经验值可通过发帖、评论等操作获得,达到目标后即可提升等级,解锁更多功能。"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -46,7 +39,9 @@
|
||||
</div>
|
||||
<div class="profile-info-item">
|
||||
<div class="profile-info-item-label">最后评论时间:</div>
|
||||
<div class="profile-info-item-value">{{ user.lastCommentTime!=null?formatDate(user.lastCommentTime):"暂无评论" }}</div>
|
||||
<div class="profile-info-item-value">{{ user.lastCommentTime != null ? formatDate(user.lastCommentTime) :
|
||||
"暂无评论" }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="profile-info-item">
|
||||
<div class="profile-info-item-label">浏览量:</div>
|
||||
@@ -68,6 +63,11 @@
|
||||
<i class="fas fa-user-plus"></i>
|
||||
<div class="profile-tabs-item-label">关注</div>
|
||||
</div>
|
||||
<div :class="['profile-tabs-item', { selected: selectedTab === 'achievements' }]"
|
||||
@click="selectedTab = 'achievements'">
|
||||
<i class="fas fa-medal"></i>
|
||||
<div class="profile-tabs-item-label">勋章</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="tabLoading" class="tab-loading">
|
||||
@@ -228,13 +228,13 @@
|
||||
</BaseTimeline>
|
||||
</div>
|
||||
|
||||
<div v-else class="follow-container">
|
||||
<div v-else-if="selectedTab === 'following'" class="follow-container">
|
||||
<div class="follow-tabs">
|
||||
<div :class="['follow-tab-item', { selected: followTab === 'followers' }]"
|
||||
@click="followTab = 'followers'">关注者
|
||||
<div :class="['follow-tab-item', { selected: followTab === 'followers' }]" @click="followTab = 'followers'">
|
||||
关注者
|
||||
</div>
|
||||
<div :class="['follow-tab-item', { selected: followTab === 'following' }]"
|
||||
@click="followTab = 'following'">正在关注
|
||||
<div :class="['follow-tab-item', { selected: followTab === 'following' }]" @click="followTab = 'following'">
|
||||
正在关注
|
||||
</div>
|
||||
</div>
|
||||
<div class="follow-list">
|
||||
@@ -243,6 +243,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="selectedTab === 'achievements'" class="achievements-container">
|
||||
<AchievementList :medals="medals" :can-select="isMine" />
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@@ -252,7 +255,7 @@
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { API_BASE_URL, toast } from '../main'
|
||||
import { getToken, authState } from '../utils/auth'
|
||||
import { getToken, authState } from '../../utils/auth'
|
||||
import BaseTimeline from '../components/BaseTimeline.vue'
|
||||
import UserList from '../components/UserList.vue'
|
||||
import BasePlaceholder from '../components/BasePlaceholder.vue'
|
||||
@@ -260,6 +263,7 @@ import LevelProgress from '../components/LevelProgress.vue'
|
||||
import { stripMarkdown, stripMarkdownLength } from '../utils/markdown'
|
||||
import TimeManager from '../utils/time'
|
||||
import { prevLevelExp } from '../utils/level'
|
||||
import AchievementList from '../components/AchievementList.vue'
|
||||
|
||||
definePageMeta({
|
||||
alias: ['/users/:id/']
|
||||
@@ -267,7 +271,7 @@ definePageMeta({
|
||||
|
||||
export default {
|
||||
name: 'ProfileView',
|
||||
components: { BaseTimeline, UserList, BasePlaceholder, LevelProgress },
|
||||
components: { BaseTimeline, UserList, BasePlaceholder, LevelProgress, AchievementList },
|
||||
setup() {
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
@@ -280,10 +284,15 @@ export default {
|
||||
const timelineItems = ref([])
|
||||
const followers = ref([])
|
||||
const followings = ref([])
|
||||
const medals = ref([])
|
||||
const subscribed = ref(false)
|
||||
const isLoading = ref(true)
|
||||
const tabLoading = ref(false)
|
||||
const selectedTab = ref('summary')
|
||||
const selectedTab = ref(
|
||||
['summary', 'timeline', 'following', 'achievements'].includes(route.query.tab)
|
||||
? route.query.tab
|
||||
: 'summary'
|
||||
)
|
||||
const followTab = ref('followers')
|
||||
|
||||
const levelInfo = computed(() => {
|
||||
@@ -297,7 +306,11 @@ export default {
|
||||
return { exp, currentLevel, nextExp, percent }
|
||||
})
|
||||
|
||||
const isMine = computed(() => authState.username === username)
|
||||
const isMine = computed(function() {
|
||||
const mine = authState.username === username || String(authState.userId) === username
|
||||
console.log(mine)
|
||||
return mine
|
||||
})
|
||||
|
||||
const formatDate = (d) => {
|
||||
if (!d) return ''
|
||||
@@ -397,6 +410,22 @@ export default {
|
||||
tabLoading.value = false
|
||||
}
|
||||
|
||||
const fetchAchievements = async () => {
|
||||
const res = await fetch(`${API_BASE_URL}/api/medals?userId=${user.value.id}`)
|
||||
if (res.ok) {
|
||||
medals.value = await res.json()
|
||||
} else {
|
||||
medals.value = []
|
||||
toast.error('获取成就失败')
|
||||
}
|
||||
}
|
||||
|
||||
const loadAchievements = async () => {
|
||||
tabLoading.value = true
|
||||
await fetchAchievements()
|
||||
tabLoading.value = false
|
||||
}
|
||||
|
||||
const subscribeUser = async () => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
@@ -441,7 +470,15 @@ export default {
|
||||
const init = async () => {
|
||||
try {
|
||||
await fetchUser()
|
||||
await loadSummary()
|
||||
if (selectedTab.value === 'summary') {
|
||||
await loadSummary()
|
||||
} else if (selectedTab.value === 'timeline') {
|
||||
await loadTimeline()
|
||||
} else if (selectedTab.value === 'following') {
|
||||
await loadFollow()
|
||||
} else if (selectedTab.value === 'achievements') {
|
||||
await loadAchievements()
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
} finally {
|
||||
@@ -452,12 +489,16 @@ export default {
|
||||
onMounted(init)
|
||||
|
||||
watch(selectedTab, async val => {
|
||||
// router.replace({ query: { ...route.query, tab: val } })
|
||||
if (val === 'timeline' && timelineItems.value.length === 0) {
|
||||
await loadTimeline()
|
||||
} else if (val === 'following' && followers.value.length === 0 && followings.value.length === 0) {
|
||||
await loadFollow()
|
||||
} else if (val === 'achievements' && medals.value.length === 0) {
|
||||
await loadAchievements()
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
user,
|
||||
hotPosts,
|
||||
@@ -465,6 +506,7 @@ export default {
|
||||
timelineItems,
|
||||
followers,
|
||||
followings,
|
||||
medals,
|
||||
subscribed,
|
||||
isMine,
|
||||
isLoading,
|
||||
@@ -476,6 +518,7 @@ export default {
|
||||
stripMarkdownLength,
|
||||
loadTimeline,
|
||||
loadFollow,
|
||||
loadAchievements,
|
||||
loadSummary,
|
||||
subscribeUser,
|
||||
unsubscribeUser,
|
||||
@@ -612,7 +655,7 @@ export default {
|
||||
gap: 20px;
|
||||
border-top: 1px solid var(--normal-border-color);
|
||||
border-bottom: 1px solid var(--normal-border-color);
|
||||
scrollbar-width: none;
|
||||
scrollbar-width: none;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
@@ -622,7 +665,7 @@ export default {
|
||||
gap: 5px;
|
||||
align-items: center;
|
||||
padding: 10px 0;
|
||||
white-space: nowrap;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.profile-info-item-label {
|
||||
@@ -643,9 +686,9 @@ export default {
|
||||
flex-direction: row;
|
||||
padding: 0 20px;
|
||||
border-bottom: 1px solid var(--normal-border-color);
|
||||
scrollbar-width: none;
|
||||
scrollbar-width: none;
|
||||
overflow-x: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.profile-tabs-item {
|
||||
display: flex;
|
||||
@@ -657,7 +700,7 @@ export default {
|
||||
padding: 10px 0;
|
||||
width: 200px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.profile-tabs-item.selected {
|
||||
|
||||
9
frontend_nuxt/utils/medal.js
Normal file
9
frontend_nuxt/utils/medal.js
Normal file
@@ -0,0 +1,9 @@
|
||||
export const medalTitles = {
|
||||
COMMENT: '评论达人',
|
||||
POST: '发帖达人',
|
||||
SEED: '种子用户'
|
||||
}
|
||||
|
||||
export function getMedalTitle(type) {
|
||||
return medalTitles[type] || ''
|
||||
}
|
||||
Reference in New Issue
Block a user