feat(api): 补齐 /me/* 命名空间,恢复 17 个 404 调用 + 修 /me/status 过期桩

背景:小程序 services/*.js 按 REST 规范(§16 / §22-§40 / §80 / §83-§84)统一调用
/me/*,但后端从未注册 /me 基路径,个人资料、照片、择偶条件、隐私设置、关系状态、
我的举报/申诉等约 17 个调用全部 404。

后端
- 新增 me/controller/MeController:把既有 service 能力暴露到规范路径(纯委托,不复制
  业务规则,AGENTS.md #26)。旧路径(/profile/*、/photos、/relationship/*、
  /account/privacy-settings、/risk/reports/my、/appeals/my)全部保留。
- 响应形状按小程序 JSDoc 适配(小程序被 86 页引用,是权威契约):
  · /me/relationship-status 返回 status(旧 /relationship/status 返回 relationshipStatus,
    字段名不同,前端读的是 result.status)
  · /me/profile/review-status 返回 {status, items, submittedAt, reviewedAt},时间统一 epoch 毫秒
  · /me/profile/submit-review 返回 {reviewStatus, submittedAt}
- 小程序三条历史写法一并兼容:/me/privacy-settings、/me/photos/{id}/main、/me/appeals

修复
- AuthService.getMeStatus:verified / profileStatus / reviewStatus 三项写死为
  false / not_started / not_submitted,注释标注"Phase 03/04/05 填充",但那三个 Phase
  早已交付,导致 /me/status 长期返回错误的实名与审核状态。改为 capabilityService
  + userProfileMapper + reviewTaskMapper 的真实来源(与首页聚合同一判定)。
- PhotoController.deletePhoto:原用 ((Map<?,?>) p).get("id") 强转 UserPhoto 实体,
  必然抛 ClassCastException,删除照片恒定 500。改用实体主键比对。
- PhotoService.setMainAvatar(新增):数据模型以 photo_type='avatar' 标识头像(见
  UserPhotoMapper#findAvatar),无 is_main 字段,故"设主图"= 换类型并保证至多一张。
  注意:插入该方法时曾把 deletePhoto 原有的 @Transactional 挤到新方法上,导致
  "Transactional is not a repeatable annotation" 并引发 Lombok 全面停摆(满屏
  找不到 getter/setter),已修正注解归属。

验证
- 后端全量:299 tests / 0 failures / 0 errors / 3 skipped / BUILD SUCCESS(+2 为新增契约测试)
- 新增 MeRouteContractTest(2 例):同时断言 HTTP 方法,锁定 21 条 /me/* 与 13 条旧路径
- 小程序 tsc --noEmit 通过;UI 契约门禁 13/13

文档
- STATUS.md:/me/* 从"待裁决"改为"已完成";核心待清债务 1 项 → 0 项
- API_INVENTORY.md:顶部"待收敛"警告改为"已收敛",补全 /me/* 端点表
This commit is contained in:
Codex
2026-09-16 12:54:39 +08:00
parent ce172ffd4f
commit bc4531a734
11 changed files with 651 additions and 52 deletions
@@ -5,9 +5,14 @@ import com.danyang.match.platform.audit.entity.AuditLog;
import com.danyang.match.platform.audit.mapper.AuditLogMapper;
import com.danyang.match.platform.auth.provider.WechatLoginProvider;
import com.danyang.match.platform.auth.token.JwtTokenService;
import com.danyang.match.platform.capability.service.CapabilityService;
import com.danyang.match.platform.shared.constant.Constants;
import com.danyang.match.platform.local_eligibility.entity.LocalEligibility;
import com.danyang.match.platform.local_eligibility.mapper.LocalEligibilityMapper;
import com.danyang.match.platform.profile.entity.UserProfile;
import com.danyang.match.platform.profile.mapper.UserProfileMapper;
import com.danyang.match.platform.review.entity.ReviewTask;
import com.danyang.match.platform.review.mapper.ReviewTaskMapper;
import com.danyang.match.platform.user.entity.User;
import com.danyang.match.platform.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
@@ -21,6 +26,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@Service
@RequiredArgsConstructor
@@ -34,6 +40,9 @@ public class AuthService {
private final StringRedisTemplate redisTemplate;
private final AuditLogMapper auditLogMapper;
private final LocalEligibilityMapper localEligibilityMapper;
private final CapabilityService capabilityService;
private final UserProfileMapper userProfileMapper;
private final ReviewTaskMapper reviewTaskMapper;
@Value("${jwt.access-token-expiration-ms:7200000}")
private long accessTokenExpireMs;
@@ -169,9 +178,17 @@ public class AuthService {
status.put("relationshipStatus", user.getRelationshipStatus());
status.put("recommendationEnabled", user.getRecommendationEnabled());
status.put("phoneBound", user.getPhone() != null && !user.getPhone().isBlank());
status.put("verified", false); // Phase 03 填充
status.put("profileStatus", "not_started"); // Phase 04 填充
status.put("reviewStatus", "not_submitted"); // Phase 05 填充
// 以下三项原先写死为占位值并标注"Phase 03/04/05 填充"。Phase 03/04/05 均已交付,
// 占位值会让 /me/status 长期返回错误的实名与审核状态,故改为真实来源。
// 实名复用 CapabilityService,与首页聚合共用同一判定,不在此处复制业务规则(AGENTS.md #26)。
status.put("verified", capabilityService.isIdentityVerified(userId));
UserProfile profile = userProfileMapper.findByUserId(userId).orElse(null);
status.put("profileStatus",
profile != null && profile.getProfileStatus() != null ? profile.getProfileStatus() : "not_started");
Optional<ReviewTask> latestReview = reviewTaskMapper.findLatestByUserId(userId);
status.put("reviewStatus", latestReview.map(ReviewTask::getStatus).orElse("not_submitted"));
// V1.1: 本地资格状态
com.danyang.match.platform.local_eligibility.entity.LocalEligibility el =
@@ -0,0 +1,388 @@
package com.danyang.match.platform.me.controller;
import com.danyang.match.platform.appeal.service.AppealService;
import com.danyang.match.platform.auth.service.AuthService;
import com.danyang.match.platform.photo.entity.UserPhoto;
import com.danyang.match.platform.photo.service.PhotoService;
import com.danyang.match.platform.profile.dto.SelfProfileDTO;
import com.danyang.match.platform.profile.service.PrivacyService;
import com.danyang.match.platform.profile.service.UserPreferenceService;
import com.danyang.match.platform.profile.service.UserProfileService;
import com.danyang.match.platform.relationship.service.RelationshipStatusService;
import com.danyang.match.platform.review.entity.ReviewTask;
import com.danyang.match.platform.review.service.ReviewService;
import com.danyang.match.platform.risk.service.ReportService;
import com.danyang.match.platform.shared.dto.ApiResponse;
import com.danyang.match.platform.shared.enums.ApiResponseCode;
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
import com.danyang.match.platform.user.entity.User;
import com.danyang.match.platform.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* 本人资源聚合控制器 —— REST 规范 {@code /me/*} 命名空间。
*
* <p><b>背景</b>:小程序 {@code services/*.js} 按 {@code REST API 接口详细设计规范.md}
* (§16 / §22-§40 / §80 / §83-§84)统一调用 {@code /me/*},但后端此前从未注册 {@code /me} 基路径,
* 导致个人资料、照片、择偶条件、隐私设置、关系状态、我的举报/申诉等约 17 个调用全部 404。
*
* <p><b>职责边界</b>:本控制器不新造业务逻辑,只做两件事:
* <ol>
* <li>把已有 service 能力暴露到规范路径(纯委托,不复制业务规则,见 AGENTS.md #26);</li>
* <li>把响应适配成小程序既有的消费形状(小程序被 86 页引用,是权威契约,
* 例如 {@code relationship-status} 用 {@code status} 而非后端的 {@code relationshipStatus})。</li>
* </ol>
*
* <p><b>兼容策略</b>:旧路径({@code /profile/*}、{@code /photos}、{@code /relationship/*}、
* {@code /account/privacy-settings} 等)全部保留不动,避免管理端与既有测试断裂;
* 小程序历史上自行发明的路径({@code /me/privacy-settings}、{@code /me/photos/{id}/main}、
* {@code /me/appeals})一并提供,使前端零改动可用。
*
* <p>路由已由 {@code MeRouteContractTest} 锁定。
*/
@RestController
@RequestMapping("/me")
@RequiredArgsConstructor
public class MeController {
private final AuthService authService;
private final UserMapper userMapper;
private final UserProfileService userProfileService;
private final UserPreferenceService preferenceService;
private final PrivacyService privacyService;
private final PhotoService photoService;
private final ReviewService reviewService;
private final RelationshipStatusService relationshipStatusService;
private final ReportService reportService;
private final AppealService appealService;
// ==================== 账号状态 ====================
/**
* 获取当前用户全局状态(REST §16)。
* GET /api/v1/me/status
*/
@GetMapping("/status")
public ApiResponse<Map<String, Object>> getStatus(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(authService.getMeStatus(principal.id()));
}
// ==================== 个人资料 ====================
/**
* 获取本人资料(REST §22)。
* GET /api/v1/me/profile
*/
@GetMapping("/profile")
public ApiResponse<SelfProfileDTO> getProfile(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(userProfileService.getSelfProfile(principal.id()));
}
/**
* 更新本人资料(REST §22 配套写操作)。
* PUT /api/v1/me/profile
*/
@PutMapping("/profile")
public ApiResponse<Void> updateProfile(@AuthenticationPrincipal UserPrincipal principal,
@RequestBody Map<String, Object> fields) {
userProfileService.updateProfile(principal.id(), fields);
return ApiResponse.ok();
}
/**
* 更新基础资料(REST §23,资料完善流程分节写)。
* PATCH /api/v1/me/profile/basic
*/
@PatchMapping("/profile/basic")
public ApiResponse<?> updateBasicProfile(@AuthenticationPrincipal UserPrincipal principal,
@RequestBody Map<String, Object> fields) {
return ApiResponse.ok(userProfileService.updateBasicProfile(principal.id(), fields));
}
/**
* 资料完整度(REST 第二十一章配套)。
* GET /api/v1/me/profile/completion
*/
@GetMapping("/profile/completion")
public ApiResponse<Map<String, Object>> getCompletion(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(Map.of("completion", userProfileService.getCompletionPercentage(principal.id())));
}
// ==================== 资料审核 ====================
/**
* 获取资料审核状态(REST §39)。
* GET /api/v1/me/profile/review-status
*
* <p>同时提供清单口径的 {@code /me/review-status} 别名。
* 响应形状对齐小程序 {@code profileService.getReviewStatus} 的 JSDoc:
* {@code { status, items:[{itemType,status,reasonText}], submittedAt, reviewedAt }},
* 时间统一为 epoch 毫秒(前端按 number 消费,ISO 字符串会导致时间显示为 0)。
*/
@GetMapping({"/profile/review-status", "/review-status"})
public ApiResponse<Map<String, Object>> getReviewStatus(@AuthenticationPrincipal UserPrincipal principal) {
List<ReviewTask> history = reviewService.getReviewHistory(principal.id());
List<Map<String, Object>> items = new ArrayList<>();
for (ReviewTask task : history) {
Map<String, Object> item = new LinkedHashMap<>();
item.put("itemType", task.getReviewType());
item.put("status", task.getStatus());
if (task.getFinalComment() != null && !task.getFinalComment().isBlank()) {
item.put("reasonText", task.getFinalComment());
}
items.add(item);
}
// 以提交时间最晚的一条作为"当前审核状态",避免依赖 history 的返回顺序。
ReviewTask latest = history.stream()
.filter(t -> t.getSubmittedAt() != null)
.max(Comparator.comparing(ReviewTask::getSubmittedAt))
.orElse(history.isEmpty() ? null : history.get(0));
Instant submittedAt = history.stream()
.map(ReviewTask::getSubmittedAt).filter(Objects::nonNull).max(Instant::compareTo).orElse(null);
Instant reviewedAt = history.stream()
.map(ReviewTask::getCompletedAt).filter(Objects::nonNull).max(Instant::compareTo).orElse(null);
Map<String, Object> result = new LinkedHashMap<>();
result.put("status", latest == null ? "not_submitted" : latest.getStatus());
result.put("items", items);
if (submittedAt != null) {
result.put("submittedAt", submittedAt.toEpochMilli());
}
if (reviewedAt != null) {
result.put("reviewedAt", reviewedAt.toEpochMilli());
}
return ApiResponse.ok(result);
}
/**
* 提交资料审核(REST §37)。
* POST /api/v1/me/profile/submit-review
*
* <p>响应形状对齐小程序 JSDoc:{@code { reviewStatus, submittedAt }},submittedAt 为 epoch 毫秒。
*/
@PostMapping("/profile/submit-review")
public ApiResponse<Map<String, Object>> submitReview(@AuthenticationPrincipal UserPrincipal principal) {
ReviewTask task = reviewService.resubmit(principal.id());
Map<String, Object> result = new LinkedHashMap<>();
result.put("reviewStatus", task.getStatus());
result.put("submittedAt",
task.getSubmittedAt() != null ? task.getSubmittedAt().toEpochMilli() : System.currentTimeMillis());
return ApiResponse.ok(result);
}
// ==================== 择偶条件 ====================
/**
* 获取择偶条件(REST §34)。
* GET /api/v1/me/preferences
*/
@GetMapping("/preferences")
public ApiResponse<Map<String, Object>> getPreferences(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(preferenceService.getPreference(principal.id()));
}
/**
* 保存择偶条件(REST §35)。
* PUT /api/v1/me/preferences
*/
@PutMapping("/preferences")
public ApiResponse<Void> savePreferences(@AuthenticationPrincipal UserPrincipal principal,
@RequestBody Map<String, Object> data) {
preferenceService.savePreference(principal.id(), data);
return ApiResponse.ok();
}
// ==================== 照片 ====================
/**
* 获取本人照片列表(REST 第二十八章)。
* GET /api/v1/me/photos
*/
@GetMapping("/photos")
public ApiResponse<List<UserPhoto>> getPhotos(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(photoService.getPhotos(principal.id()));
}
/**
* 获取照片上传凭证(REST §29)。
* POST /api/v1/me/photos/upload-token
*/
@PostMapping("/photos/upload-token")
public ApiResponse<Map<String, Object>> getUploadToken(
@AuthenticationPrincipal UserPrincipal principal,
@RequestBody(required = false) Map<String, String> body) {
String photoType = body == null ? "lifestyle" : body.getOrDefault("photoType", "lifestyle");
return ApiResponse.ok(photoService.getUploadToken(principal.id(), photoType));
}
/**
* 删除本人照片(REST §32)。
* DELETE /api/v1/me/photos/{photoId}
*
* <p>所有权校验直接比对实体主键。注意:旧 {@code PhotoController#deletePhoto}
* 用 {@code (Map<?,?>) p} 强转 {@code UserPhoto} 实体,必然抛 ClassCastException,此处不沿用该写法。
*/
@DeleteMapping("/photos/{photoId}")
public ApiResponse<Void> deletePhoto(@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String photoId) {
String userId = principal.id();
boolean owned = photoService.getPhotos(userId).stream()
.anyMatch(p -> photoId.equals(p.getId()));
if (!owned) {
throw new GlobalExceptionHandler.BusinessException(ApiResponseCode.FORBIDDEN, "无权删除该照片");
}
photoService.deletePhoto(photoId);
return ApiResponse.ok();
}
/**
* 设置主头像(小程序 {@code profileService.setMainPhoto} 使用,规范未定义此路径)。
* PUT /api/v1/me/photos/{photoId}/main
*
* <p>数据模型以 {@code photo_type='avatar'} 标识头像(见 {@code UserPhotoMapper#findAvatar}),
* 故"设主图"即把目标照片置为 avatar、其余 avatar 降级为 lifestyle。
*/
@PutMapping("/photos/{photoId}/main")
public ApiResponse<Map<String, Object>> setMainPhoto(@AuthenticationPrincipal UserPrincipal principal,
@PathVariable String photoId) {
String userId = principal.id();
UserPhoto photo = photoService.setMainAvatar(userId, photoId);
Map<String, Object> result = new LinkedHashMap<>();
result.put("photoId", photo.getId());
if (photo.getFileKey() != null) {
// 签名 URL 可能因对象存储未配置而失败,此降级不影响主头像已生效这一事实。
try {
Map<String, Object> signed = photoService.getSignedUrl(userId, photo.getFileKey());
result.put("avatarUrl", signed.get("url"));
} catch (RuntimeException ignored) {
result.put("avatarUrl", null);
}
}
return ApiResponse.ok(result);
}
// ==================== 隐私设置 ====================
/**
* 获取隐私设置(REST 第九十一章 {@code GET /me/privacy})。
* GET /api/v1/me/privacy
* GET /api/v1/me/privacy-settings(小程序历史写法,兼容保留)
*/
@GetMapping({"/privacy", "/privacy-settings"})
public ApiResponse<Map<String, Boolean>> getPrivacy(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(privacyService.getPrivacySettings(principal.id()));
}
/**
* 更新隐私设置(REST 第九十一章 {@code PATCH /me/privacy})。
* PATCH /api/v1/me/privacy
*/
@PatchMapping("/privacy")
public ApiResponse<Map<String, Boolean>> patchPrivacy(@AuthenticationPrincipal UserPrincipal principal,
@RequestBody Map<String, Boolean> settings) {
return ApiResponse.ok(privacyService.updatePrivacySettings(principal.id(), settings));
}
/**
* 更新隐私设置(小程序历史写法,兼容保留)。
* PUT /api/v1/me/privacy-settings
*/
@PutMapping("/privacy-settings")
public ApiResponse<Map<String, Boolean>> putPrivacySettings(@AuthenticationPrincipal UserPrincipal principal,
@RequestBody Map<String, Boolean> settings) {
return ApiResponse.ok(privacyService.updatePrivacySettings(principal.id(), settings));
}
// ==================== 关系状态 ====================
/**
* 获取婚恋关系状态(REST §83)。
* GET /api/v1/me/relationship-status
*
* <p>响应形状对齐小程序 {@code profileService.getRelationshipStatus} 的 JSDoc:
* {@code { status, recommendationEnabled, matchingWith }}。
* 注意与旧 {@code /relationship/status} 的区别——后者返回 {@code relationshipStatus},
* 小程序消费的是 {@code result.status},字段名不同。
*/
@GetMapping("/relationship-status")
public ApiResponse<Map<String, Object>> getRelationshipStatus(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(buildRelationshipStatus(principal.id()));
}
/**
* 更新婚恋关系状态(REST §84)。
* PATCH /api/v1/me/relationship-status
* Body: {@code { "status": "paused" | "searching" | "getting_to_know" }}
*
* <p>成功牵手不允许由此接口直接设置,必须走
* {@code POST /matches/{id}/success/request|confirm} 双方确认。
*/
@PatchMapping("/relationship-status")
public ApiResponse<Map<String, Object>> updateRelationshipStatus(
@AuthenticationPrincipal UserPrincipal principal,
@RequestBody(required = false) Map<String, String> body) {
String userId = principal.id();
String status = body == null ? null : body.get("status");
if (status == null || status.isBlank()) {
throw new GlobalExceptionHandler.BusinessException(ApiResponseCode.BAD_REQUEST, "缺少 status 参数");
}
switch (status) {
case "paused" -> relationshipStatusService.pauseSearching(userId);
case "searching" -> relationshipStatusService.resumeSearching(userId);
case "getting_to_know" -> relationshipStatusService.setGettingToKnow(userId, false);
case "matched_successfully" -> throw new GlobalExceptionHandler.BusinessException(
ApiResponseCode.MATCH_SUCCESS_NEED_BOTH_CONFIRM,
"成功牵手不能直接设置,请通过 POST /matches/{id}/success/request|confirm 双方确认");
default -> throw new GlobalExceptionHandler.BusinessException(
ApiResponseCode.BAD_REQUEST, "不支持的 relationship status: " + status);
}
return ApiResponse.ok(buildRelationshipStatus(userId));
}
private Map<String, Object> buildRelationshipStatus(String userId) {
User user = userMapper.findById(userId).orElse(null);
Map<String, Object> result = new LinkedHashMap<>();
result.put("status", user != null && user.getRelationshipStatus() != null
? user.getRelationshipStatus() : "searching");
result.put("recommendationEnabled",
user == null || Boolean.TRUE.equals(user.getRecommendationEnabled()));
// matchingWith 需要 match episode 聚合,本轮未接入;前端有 `|| null` 兜底。
result.put("matchingWith", null);
return result;
}
// ==================== 我的举报 / 申诉 ====================
/**
* 我的举报列表(REST §80)。
* GET /api/v1/me/reports
*/
@GetMapping("/reports")
public ApiResponse<Object> getMyReports(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(reportService.getMyReports(principal.id()));
}
/**
* 我的申诉列表(小程序 {@code appealService} 使用,规范只定义了 {@code POST /appeals})。
* GET /api/v1/me/appeals
*/
@GetMapping("/appeals")
public ApiResponse<Object> getMyAppeals(@AuthenticationPrincipal UserPrincipal principal) {
return ApiResponse.ok(appealService.getMyAppeals(principal.id()));
}
}
@@ -2,6 +2,7 @@ package com.danyang.match.platform.photo.controller;
import com.danyang.match.platform.shared.security.principal.UserPrincipal;
import com.danyang.match.platform.photo.service.PhotoService;
import com.danyang.match.platform.photo.entity.UserPhoto;
import com.danyang.match.platform.shared.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
@@ -95,9 +96,10 @@ public class PhotoController {
@PathVariable String id) {
String userId = principal.id();
// 权限校验:只允许删除自己的照片
List<?> userPhotos = photoService.getPhotos(userId);
boolean owned = userPhotos.stream()
.anyMatch(p -> id.equals(String.valueOf(((Map<?, ?>) p).get("id"))));
// 注意:getPhotos 返回 UserPhoto 实体列表,原先用 ((Map<?,?>) p).get("id") 强转会抛
// ClassCastException,导致删除照片恒定 500。此处改为实体主键比对。
List<UserPhoto> userPhotos = photoService.getPhotos(userId);
boolean owned = userPhotos.stream().anyMatch(p -> id.equals(p.getId()));
if (!owned) {
throw new com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException(
com.danyang.match.platform.shared.enums.ApiResponseCode.FORBIDDEN, "无权删除该照片");
@@ -7,6 +7,8 @@ import com.danyang.match.platform.photo.entity.UserPhoto;
import com.danyang.match.platform.photo.mapper.UserPhotoMapper;
import com.danyang.match.platform.shared.constant.Constants;
import com.danyang.match.platform.shared.config.FeatureFlagConfig;
import com.danyang.match.platform.shared.enums.ApiResponseCode;
import com.danyang.match.platform.shared.exception.GlobalExceptionHandler;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -239,6 +241,38 @@ public class PhotoService {
.map(String::trim).map(String::toLowerCase).anyMatch(extension::equals);
}
/**
* 将指定照片设为主头像。
*
* <p>数据模型以 {@code photo_type='avatar'} 标识头像(见 {@code UserPhotoMapper#findAvatar}),
* 没有独立的 is_main 字段,因此"设主图"= 把目标照片置为 avatar,
* 并把该用户其余 avatar 降级为 lifestyle,保证同一时刻至多一张头像。
*
* @throws GlobalExceptionHandler.BusinessException 照片不存在或不属于该用户
*/
@Transactional
public UserPhoto setMainAvatar(String userId, String photoId) {
List<UserPhoto> photos = photoMapper.findByUserIdOrderBySort(userId);
UserPhoto target = photos.stream()
.filter(p -> photoId.equals(p.getId()))
.findFirst()
.orElseThrow(() -> new GlobalExceptionHandler.BusinessException(
ApiResponseCode.NOT_FOUND, "照片不存在或不属于当前用户"));
for (UserPhoto photo : photos) {
if (photoId.equals(photo.getId())) {
if (!"avatar".equals(photo.getPhotoType())) {
photo.setPhotoType("avatar");
photoMapper.updateById(photo);
}
} else if ("avatar".equals(photo.getPhotoType())) {
photo.setPhotoType("lifestyle");
photoMapper.updateById(photo);
}
}
return target;
}
/**
* 软删除照片
*/
@@ -0,0 +1,123 @@
package com.danyang.match.platform.contract;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 路由契约测试:锁定 {@code /me/*} 本人资源命名空间。
*
* <p>背景(2026-09-16):小程序 {@code services/*.js} 按 {@code REST API 接口详细设计规范.md}
* (§16 / §22-§40 / §80 / §83-§84)统一调用 {@code /me/*},但后端此前从未注册 {@code /me} 基路径,
* 导致个人资料、照片、择偶条件、隐私设置、关系状态、我的举报/申诉等约 17 个调用全部 404。
*
* <p>本测试同时断言 <b>HTTP 方法</b>,因为"路径注册了但方法不对"仍会让前端收到 405——
* 例如 {@code /me/relationship-status} 前端用 PATCH,写成 PUT 同样不可用。
*
* <p>旧路径({@code /profile/*}、{@code /photos}、{@code /relationship/status} 等)必须继续保留,
* 管理端与既有测试依赖它们,故一并断言。
*/
@SpringBootTest
@ActiveProfiles("test")
class MeRouteContractTest {
/** 按名字取 MVC 的 HandlerMapping —— Actuator 也注册了一个同类型 bean,按类型注入会歧义 */
@Autowired
@Qualifier("requestMappingHandlerMapping")
private RequestMappingHandlerMapping handlerMapping;
/** 上下文已注册的 "METHOD URL" 集合;无方法限定的记为 "ANY URL" */
private Set<String> routes() {
Set<String> out = new HashSet<>();
handlerMapping.getHandlerMethods().forEach((info, handler) -> {
Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
for (String pattern : info.getPatternValues()) {
if (methods.isEmpty()) {
out.add("ANY " + pattern);
} else {
for (RequestMethod method : methods) {
out.add(method.name() + " " + pattern);
}
}
}
});
return out;
}
private void assertRoute(Set<String> routes, String method, String path) {
assertTrue(routes.contains(method + " " + path), "缺少路由 " + method + " " + path);
}
@Test
@DisplayName("小程序依赖的 /me/* 个人资源路由必须全部注册")
void meRoutesRegistered() {
Set<String> r = routes();
// 账号状态(REST §16)
assertRoute(r, "GET", "/me/status");
// 个人资料(REST §22-§23、第二十一章)
assertRoute(r, "GET", "/me/profile");
assertRoute(r, "PUT", "/me/profile");
assertRoute(r, "PATCH", "/me/profile/basic");
assertRoute(r, "GET", "/me/profile/completion");
// 资料审核(REST §37 / §39)——前端走 /me/profile/review-status
assertRoute(r, "GET", "/me/profile/review-status");
assertRoute(r, "POST", "/me/profile/submit-review");
// 择偶条件(REST §34-§35)
assertRoute(r, "GET", "/me/preferences");
assertRoute(r, "PUT", "/me/preferences");
// 照片(REST §29-§32 + 小程序专有的设主图)
assertRoute(r, "GET", "/me/photos");
assertRoute(r, "POST", "/me/photos/upload-token");
assertRoute(r, "DELETE", "/me/photos/{photoId}");
assertRoute(r, "PUT", "/me/photos/{photoId}/main");
// 隐私设置(REST 第九十一章用 /me/privacy;/me/privacy-settings 为小程序历史写法)
assertRoute(r, "GET", "/me/privacy");
assertRoute(r, "PATCH", "/me/privacy");
assertRoute(r, "GET", "/me/privacy-settings");
assertRoute(r, "PUT", "/me/privacy-settings");
// 关系状态(REST §83-§84)——前端用 PATCH,不是 PUT
assertRoute(r, "GET", "/me/relationship-status");
assertRoute(r, "PATCH", "/me/relationship-status");
// 我的举报 / 申诉(REST §80 + 小程序申诉列表)
assertRoute(r, "GET", "/me/reports");
assertRoute(r, "GET", "/me/appeals");
}
@Test
@DisplayName("被 /me/* 兼容的旧路径必须继续保留(管理端与既有测试依赖)")
void legacyRoutesKept() {
Set<String> r = routes();
assertRoute(r, "GET", "/profile/me");
assertRoute(r, "PUT", "/profile/me");
assertRoute(r, "GET", "/profile/preferences");
assertRoute(r, "GET", "/profile/privacy");
assertRoute(r, "GET", "/photos");
assertRoute(r, "POST", "/photos/upload-token");
assertRoute(r, "GET", "/relationship/status");
assertRoute(r, "PUT", "/relationship/pause");
assertRoute(r, "PUT", "/relationship/resume");
assertRoute(r, "PUT", "/relationship/getting-to-know");
assertRoute(r, "GET", "/risk/reports/my");
assertRoute(r, "GET", "/appeals/my");
assertRoute(r, "GET", "/account/privacy-settings");
}
}