Merge pull request #58 from SlimusMinus/fix-posts_api_stage2
All checks were successful
deploy-backend / deploy (push) Successful in 1m25s

Posts API stage 2: /posts/{id} is one post, drop userEmail and /posts…
This commit is contained in:
SlimusMinus
2026-10-21 00:10:42 +03:00
committed by GitHub
10 changed files with 59 additions and 112 deletions

View File

@@ -388,21 +388,20 @@ DTO (MapStruct / ручной маппинг) → JSON; ошибки → GlobalE
| Метод и путь | Что делает |
|---|---|
| `POST /` (multipart: поля `PostRequest` + `images[]`) | создать; статус `MODERATION`. Ответ — **201** с созданным `PostResponse` и `Location: /api/v1/posts/detail/{id}` |
| `POST /` (multipart: поля `PostRequest` + `images[]`) | создать; статус `MODERATION`. Ответ — **201** с созданным `PostResponse` и `Location: /api/v1/posts/{id}` |
| `GET /?search=&type=&category=&city=` | лента `Page<PostResponse>` (ACTIVE и CLOSED); с `search` — поиск по релевантности |
| `GET /search/suggest?q=` | подсказки для последнего слова |
| `GET /{userId}` | **устарело**: объявления пользователя списком. Замена — `GET /api/v1/users/{userId}/posts`; после перехода фронта маршрут станет «одно объявление» (сейчас это `/detail/{postId}`) |
| `GET /detail/{postId}` | одно объявление |
| `GET /{postId}` | одно объявление; неопубликованное видит только владелец, остальным — 404. Объявления пользователя — `GET /api/v1/users/{userId}/posts` |
| `GET /detail/{postId}` | то же, прежний адрес (алиас) |
| `PUT /{id}` (multipart: `type, title, address, latitude, longitude, description, category, phone, reward, rewardText, images[], existingImages`) | правка владельцем; снова `MODERATION`. `existingImages` — JSON-массив ключей картинок, которые остаются |
| `PATCH /{id}/status` `{status}` | владелец переводит опубликованное объявление в `ACTIVE`/`CLOSED` |
| `DELETE /{id}` | удаление владельцем (с избранным, ссылками чатов и файлами) |
| `GET /search?city=` | **устарело**: объявления по подстроке города/района, `Page<PostResponse>`. Тот же фильтр — `GET /?city=` |
| `GET /cities` | список городов опубликованных объявлений |
| `GET /map?minLat=&maxLat=&minLng=&maxLng=&type=&category=` | метки карты |
`PostResponse`: `id, title, description, category (название), city, district,
address, latitude, longitude, type, status, createdAt, userLogin (логин
автора; `userEmail` — то же значение, устаревшее имя), phone, images (ключи файлов), userId, userRole, rulesAccepted,
автора), phone, images (ключи файлов), userId, userRole, rulesAccepted,
reward, rewardText`.
Ограничения полей: `title` обязателен, ≤ 255; `address` ≤ 500; `phone`,
@@ -642,14 +641,11 @@ Redis и MinIO в тестах не нужны: в профиле `test` MinIO
Что остаётся и требует решения или отдельной задачи:
- **API-контракт, второй этап** (после деплоя фронта, который ходит на
`/users/{userId}/posts` и читает `userLogin`): `GET /api/v1/posts/{id}`
должен отдавать одно объявление (`/detail/{id}` оставить алиасом), убрать
`userEmail` из `PostResponse` и `GET /api/v1/posts/search`.
- **Фронт должен подхватить** новые поля: `impressionToken` в ответе
`/api/ads/next` (вернуть в `/impression` и `/click`, затем включить
`ADS_REQUIRE_TRACKING_TOKEN`), `token`/`refreshToken` в ответе правки профиля
при смене логина, пароль от 8 символов, 429 от лимитов.
- **Смена API объявлений** (без переходного периода, приложение в тестовом
режиме): `GET /api/v1/posts/{id}` теперь одно объявление, а не объявления
пользователя (они — `GET /api/v1/users/{userId}/posts`); `userEmail` в
`PostResponse` заменён на `userLogin`; `GET /api/v1/posts/search?city=`
удалён (тот же фильтр — `GET /api/v1/posts?city=`).
- **Отметка владельца файла** (`files:owner:*`) хранит логин: после смены
логина свои недавние загрузки можно удалить только через админа.
- **Транскодинг**: если экземпляр упал во время ffmpeg, объявление остаётся

View File

@@ -48,9 +48,8 @@ public class PostController {
public ResponseEntity<PostResponse> create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
log.info("create post type={}, title='{}'", request.getType(), request.getTitle());
PostResponse created = service.create(request, images);
// Одно объявление пока отдаёт /detail/{id}; /posts/{id} поменяет смысл вторым этапом
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/detail/{id}").buildAndExpand(created.getId()).toUri();
.path("/{id}").buildAndExpand(created.getId()).toUri();
return ResponseEntity.created(location).body(created);
}
@@ -78,15 +77,14 @@ public class PostController {
}
/**
* Объявления ПОЛЬЗОВАТЕЛЯ с id {@code id} (историческое имя маршрута).
* Новый маршрут — GET /api/v1/users/{userId}/posts (постранично). Этот
* останется до деплоя фронта, затем /posts/{id} станет одним объявлением.
* Одно объявление. Неопубликованное (MODERATION, REJECTED) видит только
* владелец, остальным — 404. Объявления пользователя —
* GET /api/v1/users/{userId}/posts.
*/
@Deprecated
@GetMapping("/{id:\\d+}")
public List<PostResponse> getById(@PathVariable Long id) {
log.info("get feed by id {}", id);
return service.getPostsByUserId(id);
public PostResponse getById(@PathVariable Long id) {
log.info("get post by id {}", id);
return service.getPostById(id);
}
@PutMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@@ -111,25 +109,17 @@ public class PostController {
return service.updateStatus(id, request.getStatus());
}
/** Устарело: используйте GET /api/v1/posts?city= (лента с тем же фильтром). */
@Deprecated
@GetMapping("/search")
public Page<PostResponse> search(@RequestParam(required = false) String city,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("search posts by city {}", city);
return service.searchByCity(city, pageable);
}
@GetMapping("/cities")
public List<String> getCities() {
log.info("get distinct cities");
return service.getCities();
}
/** Прежний адрес одного объявления — алиас GET /api/v1/posts/{id}. */
@GetMapping("/detail/{postId}")
public PostResponse getPostOnMapById(@PathVariable Long postId) {
log.info("get post on map by id {}", postId);
return service.getPostOnMapById(postId);
public PostResponse getPostDetail(@PathVariable Long postId) {
log.info("get post detail {}", postId);
return service.getPostById(postId);
}
}

View File

@@ -1,15 +0,0 @@
package com.krylov.refound.dto;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class DialogResponse {
private Long userId;
private String userEmail;
private String lastMessage;
private LocalDateTime lastMessageTime;
private Long unreadCount;
}

View File

@@ -27,12 +27,6 @@ public class PostResponse {
private LocalDateTime createdAt;
/** Логин автора. */
private String userLogin;
/**
* Тот же логин под старым (ошибочным) именем — для клиентов, которые ещё
* читают userEmail. Удалить после перехода фронта на userLogin.
*/
@Deprecated
private String userEmail;
private String phone;
private List<String> images;
private Long userId;

View File

@@ -20,7 +20,6 @@ public interface PostMapper {
@Mapping(source = "user.id", target = "userId")
@Mapping(source = "user.login", target = "userLogin")
@Mapping(source = "user.login", target = "userEmail")
@Mapping(source = "images", target = "images", qualifiedByName = "imagesToUrls")
// Категория необязательна: без проверки на null пост без категории ронял ленту с 500
@Mapping(target = "category", expression = "java(post.getCategory() == null ? null : post.getCategory().getDisplayName())")

View File

@@ -17,8 +17,6 @@ import org.springframework.data.domain.Page;
public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {
List<Post> findByUserId(Long userId);
Page<Post> findByUserId(Long userId, Pageable pageable);
Page<Post> findByUserIdAndStatusIn(Long userId, Collection<PostStatus> statuses, Pageable pageable);

View File

@@ -56,7 +56,7 @@ import java.util.Set;
@Slf4j
public class PostService {
// Статусы, которые показываются в публичной ленте. MODERATION и REJECTED видны
// только владельцу (getPostsByUserId, getPostOnMapById), но не в общем фиде.
// только владельцу (getPostsByUser, getPostById), но не в общем фиде.
private static final Set<PostStatus> FEED_VISIBLE_STATUSES = PostVisibility.FEED_VISIBLE_STATUSES;
private final PostRepository postRepository;
@@ -190,13 +190,6 @@ public class PostService {
.toList();
}
/**
* Возвращает посты указанного пользователя (это НЕ поиск поста по его собственному id,
* несмотря на то, как метод назывался раньше — getById). Если у вас уже есть контроллер,
* вызывающий старое имя getById, переименуйте вызов на getPostsByUserId.
* Владелец видит все свои посты (включая MODERATION и REJECTED), остальные — только
* опубликованные (ACTIVE и CLOSED).
*/
/**
* Объявления пользователя постранично (GET /api/v1/users/{userId}/posts).
* Владелец видит все свои посты, остальные — только опубликованные.
@@ -209,22 +202,6 @@ public class PostService {
return posts.map(post -> toResponse(post, false));
}
public List<PostResponse> getPostsByUserId(Long userId) {
boolean owner = isCurrentUser(userId);
List<Post> posts = postRepository.findByUserId(userId).stream()
.filter(post -> owner || FEED_VISIBLE_STATUSES.contains(post.getStatus()))
.toList();
if (posts.isEmpty()) {
return List.of();
}
return posts.stream()
.map(post -> toResponse(post, false))
.toList();
}
/**
* Правка объявления владельцем; multipart-поля приходят по отдельности.
* Как и при создании, геокодер и загрузка фото выполняются до транзакции.
@@ -332,23 +309,6 @@ public class PostService {
return mapper.toResponse(updated);
}
/**
* Устаревший поиск по подстроке города/района — тот же фильтр есть в ленте
* (GET /api/v1/posts?city=). Оставлен на переходный период, уже постранично.
*/
@Deprecated
@Transactional(readOnly = true)
public Page<PostResponse> searchByCity(String city, Pageable pageable) {
if (!StringUtils.hasText(city)) {
return Page.empty(pageable);
}
Specification<Post> spec = Specification.where(PostSpecification.cityOrDistrictLike(city))
.and((root, query, cb) -> root.get("status").in(FEED_VISIBLE_STATUSES));
return postRepository.findAll(spec, pageable).map(post -> toResponse(post, true));
}
public List<String> getCities() {
return postRepository.findDistinctCities(FEED_VISIBLE_STATUSES);
}
@@ -482,7 +442,9 @@ public class PostService {
}
}
public PostResponse getPostOnMapById(Long postId) {
/** Одно объявление: GET /api/v1/posts/{id} (и алиас /detail/{id}). */
@Transactional(readOnly = true)
public PostResponse getPostById(Long postId) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND));

View File

@@ -60,15 +60,4 @@ public class PostSpecification {
cb.lower(root.get("district")).in(filter.cities()))
);
}
public static Specification<Post> cityOrDistrictLike(String query) {
if (!StringUtils.hasText(query)) {
return null;
}
String pattern = "%" + query.toLowerCase() + "%";
return (root, cq, cb) -> cb.or(
cb.like(cb.lower(root.get("city")), pattern),
cb.like(cb.lower(root.get("district")), pattern)
);
}
}

View File

@@ -7,7 +7,7 @@ import java.util.Set;
public final class PostVisibility {
// Статусы, видимые всем: в публичной ленте и на карте. MODERATION и REJECTED
// видны только владельцу поста (getPostsByUserId, getPostOnMapById в PostService)
// видны только владельцу поста (getPostsByUser, getPostById в PostService)
public static final Set<PostStatus> FEED_VISIBLE_STATUSES = EnumSet.of(PostStatus.ACTIVE, PostStatus.CLOSED);
private PostVisibility() {

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
@@ -11,11 +12,13 @@ import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.mapper.PostMapper;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.util.PostVisibility;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
@@ -73,6 +76,37 @@ class PostServiceUserPostsTest {
verify(postRepository, never()).findByUserId(5L, pageable);
}
@Test
void singlePostUnderModerationIsHiddenFromOthers() {
User owner = new User();
owner.setId(5L);
Post post = new Post();
post.setUser(owner);
post.setStatus(PostStatus.MODERATION);
when(postRepository.findById(7L)).thenReturn(Optional.of(post));
when(userService.getCurrentUser())
.thenThrow(new ApiException(ErrorCode.UNAUTHORIZED, "Unauthorized", HttpStatus.UNAUTHORIZED));
assertThatThrownBy(() -> service.getPostById(7L))
.isInstanceOfSatisfying(ApiException.class,
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
}
@Test
void singlePostUnderModerationIsVisibleToOwner() {
User owner = new User();
owner.setId(5L);
Post post = new Post();
post.setUser(owner);
post.setStatus(PostStatus.MODERATION);
when(postRepository.findById(7L)).thenReturn(Optional.of(post));
when(userService.getCurrentUser()).thenReturn(owner);
PostResponse dto = new PostResponse();
when(mapper.toResponse(post)).thenReturn(dto);
assertThat(service.getPostById(7L)).isSameAs(dto);
}
@Test
void anonymousGetsOnlyPublishedPosts() {
when(userService.getCurrentUser())