Compare commits
13 Commits
master
...
9eae82f6df
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9eae82f6df | ||
|
|
cd0d2a4081 | ||
|
|
73463f6c5b | ||
|
|
da7d68c31a | ||
|
|
45c4273ea8 | ||
|
|
008852c781 | ||
|
|
d19f03d412 | ||
|
|
5ea7b438f5 | ||
|
|
9dbf2dd043 | ||
|
|
e321fa4c60 | ||
|
|
4119b767c3 | ||
|
|
68d53fadf3 | ||
|
|
818c8f6a11 |
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
.git
|
||||||
|
.gradle
|
||||||
|
build
|
||||||
|
target
|
||||||
|
.idea
|
||||||
39
.env.example
Normal file
39
.env.example
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
# Шаблон переменных окружения. Скопируй в .env и заполни значениями.
|
||||||
|
# Сам .env добавлен в .gitignore и не должен попадать в репозиторий.
|
||||||
|
#
|
||||||
|
# Как приложение их получает:
|
||||||
|
# docker compose читает .env автоматически;
|
||||||
|
# Spring Boot — нет. Нужно экспортировать переменные в терминал
|
||||||
|
# или прописать их в Environment variables в настройках запуска IDE.
|
||||||
|
|
||||||
|
# --- Обязательные: без них приложение не стартует ---
|
||||||
|
|
||||||
|
# Ключи доступа к MinIO (S3-совместимое хранилище).
|
||||||
|
# ВНИМАНИЕ: они должны совпадать с MINIO_ACCESS_KEY / MINIO_SECRET_KEY
|
||||||
|
# в docker-compose.yaml, иначе приложение не подключится к MinIO.
|
||||||
|
MINIO_ACCESS_KEY=
|
||||||
|
MINIO_SECRET_KEY=
|
||||||
|
|
||||||
|
# Пароль Redis. Тот же, что в docker-compose.yaml.
|
||||||
|
# docker-compose падает с понятной ошибкой, если переменная пустая.
|
||||||
|
REDIS_PASSWORD=
|
||||||
|
|
||||||
|
# --- Рекомендуется задать ---
|
||||||
|
|
||||||
|
# Секрет подписи JWT. Без переменной берётся захардкоженное значение
|
||||||
|
# из application.yaml — подделать такой токен может кто угодно.
|
||||||
|
# Сгенерировать, например, так:
|
||||||
|
# openssl rand -base64 48
|
||||||
|
JWT_SECRET=
|
||||||
|
|
||||||
|
# --- Необязательно: есть значения по умолчанию ---
|
||||||
|
|
||||||
|
# REDIS_HOST=localhost
|
||||||
|
# MINIO_ENDPOINT=http://localhost:9010
|
||||||
|
# MINIO_BUCKET=refound-images
|
||||||
|
# MINIO_ADS_BUCKET=ads-media
|
||||||
|
# MINIO_REGION=us-east-1
|
||||||
|
# AI_SERVICE_URL=http://localhost:8000
|
||||||
|
# JWT_ACCESS_EXPIRATION=900000
|
||||||
|
# JWT_REFRESH_EXPIRATION=604800000
|
||||||
|
# JPA_DDL_AUTO=validate
|
||||||
16
.gitea/workflows/deploy.yml
Normal file
16
.gitea/workflows/deploy.yml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
name: deploy-backend
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: host
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Build image
|
||||||
|
run: docker build -t nakhodka-backend:latest -t nakhodka-backend:${{ github.sha }} .
|
||||||
|
- name: Restart backend
|
||||||
|
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d backend
|
||||||
|
- name: Cleanup
|
||||||
|
run: docker image prune -f
|
||||||
18
Dockerfile
Normal file
18
Dockerfile
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
FROM eclipse-temurin:25-jdk AS build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY . .
|
||||||
|
RUN sed -i 's/\r$//' gradlew \
|
||||||
|
&& chmod +x gradlew \
|
||||||
|
&& ./gradlew bootJar --no-daemon -x test \
|
||||||
|
&& cp "$(ls build/libs/*.jar | grep -v plain | head -n1)" /app/app.jar
|
||||||
|
|
||||||
|
FROM eclipse-temurin:25-jre
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends ffmpeg \
|
||||||
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
|
&& useradd -r -u 1001 app
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=build /app/app.jar app.jar
|
||||||
|
USER app
|
||||||
|
EXPOSE 8080
|
||||||
|
ENTRYPOINT ["java", "-Xmx768m", "-jar", "app.jar"]
|
||||||
32
src/main/java/com/krylov/refound/config/TimeZoneFilter.java
Normal file
32
src/main/java/com/krylov/refound/config/TimeZoneFilter.java
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
package com.krylov.refound.config;
|
||||||
|
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Кладёт таймзону из заголовка {@code X-Timezone} в {@link TimeZoneContext} на
|
||||||
|
* время обработки запроса. Благодаря этому время создания сущностей
|
||||||
|
* (createdAt и т.п.) ставится по зоне клиента, а не по зоне сервера.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||||
|
public class TimeZoneFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||||
|
try {
|
||||||
|
TimeZoneContext.set(request.getHeader(TimeZoneContext.HEADER));
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
} finally {
|
||||||
|
TimeZoneContext.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package com.krylov.refound.controller;
|
|||||||
|
|
||||||
import com.krylov.refound.dto.ChatDto;
|
import com.krylov.refound.dto.ChatDto;
|
||||||
import com.krylov.refound.dto.MessageDto;
|
import com.krylov.refound.dto.MessageDto;
|
||||||
|
import com.krylov.refound.dto.StartChatRequest;
|
||||||
import com.krylov.refound.service.ChatService;
|
import com.krylov.refound.service.ChatService;
|
||||||
import com.krylov.refound.service.UserService;
|
import com.krylov.refound.service.UserService;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -11,11 +12,13 @@ import org.springframework.data.domain.Page;
|
|||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.domain.Sort;
|
import org.springframework.data.domain.Sort;
|
||||||
import org.springframework.data.web.PageableDefault;
|
import org.springframework.data.web.PageableDefault;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
@@ -29,12 +32,21 @@ public class ChatController {
|
|||||||
private final UserService userService;
|
private final UserService userService;
|
||||||
private final ChatService chatService;
|
private final ChatService chatService;
|
||||||
|
|
||||||
// Создать чат с пользователем или получить существующий
|
// Существующий чат с пользователем по объявлению; 404, если переписки ещё нет (чат не создаётся)
|
||||||
@PostMapping("/with/{otherUserId}")
|
@GetMapping("/with/{otherUserId}")
|
||||||
public ChatDto createOrGetChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
|
public ResponseEntity<ChatDto> findChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
|
||||||
Long currentUserId = extractUserId(auth);
|
Long currentUserId = extractUserId(auth);
|
||||||
log.info("createOrGetChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
|
log.info("findChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
|
||||||
return chatService.getOrCreateChat(currentUserId, otherUserId, postId);
|
return ResponseEntity.of(chatService.findChat(currentUserId, otherUserId, postId));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Первое сообщение: чат создаётся (или находится) вместе с сообщением — пустых чатов не бывает
|
||||||
|
@PostMapping("/with/{otherUserId}/messages")
|
||||||
|
public ChatDto startChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId,
|
||||||
|
@RequestBody StartChatRequest request, Authentication auth) {
|
||||||
|
Long currentUserId = extractUserId(auth);
|
||||||
|
log.info("startChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
|
||||||
|
return chatService.startChat(currentUserId, otherUserId, postId, request.getContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Список всех чатов текущего пользователя
|
// Список всех чатов текущего пользователя
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package com.krylov.refound.controller;
|
package com.krylov.refound.controller;
|
||||||
|
|
||||||
import com.krylov.refound.dto.SendMessageRequest;
|
import com.krylov.refound.dto.SendMessageRequest;
|
||||||
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.service.ChatService;
|
import com.krylov.refound.service.ChatService;
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -43,10 +45,14 @@ public class ChatWebSocketController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
Object timezone = sessionAttributes.get(TimeZoneContext.SESSION_ATTRIBUTE);
|
||||||
|
TimeZoneContext.set(timezone instanceof String tz ? tz : null);
|
||||||
chatService.sendMessage(senderId, request.getChatId(), request.getContent());
|
chatService.sendMessage(senderId, request.getChatId(), request.getContent());
|
||||||
} catch (SecurityException | IllegalArgumentException e) {
|
} catch (ApiException | IllegalArgumentException e) {
|
||||||
messagingTemplate.convertAndSendToUser(senderId.toString(), "/queue/errors", e.getMessage()
|
messagingTemplate.convertAndSendToUser(senderId.toString(), "/queue/errors", e.getMessage()
|
||||||
);
|
);
|
||||||
|
} finally {
|
||||||
|
TimeZoneContext.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.krylov.refound.controller;
|
package com.krylov.refound.controller;
|
||||||
|
|
||||||
import com.krylov.refound.service.FileStorageService;
|
import com.krylov.refound.service.FileStorageService;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Map;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -34,6 +36,32 @@ public class FileStorageController {
|
|||||||
return fileStorageService.downloadFile(key);
|
return fileStorageService.downloadFile(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Редирект на presigned URL для прямой загрузки файла с MinIO (Вариант B).
|
||||||
|
* Браузер перейдёт по 302 на временную ссылку и скачает картинку напрямую с MinIO.
|
||||||
|
*/
|
||||||
|
@GetMapping(value = "/{*objectName}", params = "presigned=true")
|
||||||
|
public ResponseEntity<Void> redirectToPresigned(@PathVariable String objectName) {
|
||||||
|
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||||
|
String url = fileStorageService.generatePresignedDownloadUrl(key, Duration.ofHours(24));
|
||||||
|
return ResponseEntity.status(302)
|
||||||
|
.header("Location", url)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Возвращает presigned URL в JSON.
|
||||||
|
* PathPatternParser не допускает ничего после {*...}, поэтому "url" вынесен в префикс:
|
||||||
|
* GET /api/v1/files/url/avatars/cf80aebe-...jpg?ttlHours=24
|
||||||
|
*/
|
||||||
|
@GetMapping("/url/{*objectName}")
|
||||||
|
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
|
||||||
|
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||||
|
Duration ttl = ttlHours > 0 ? Duration.ofHours(ttlHours) : Duration.ofHours(24);
|
||||||
|
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
|
||||||
|
return ResponseEntity.ok(Map.of("url", url));
|
||||||
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{*objectName}")
|
@DeleteMapping("/{*objectName}")
|
||||||
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
|
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
|
||||||
log.info("deleteFile {}", objectName);
|
log.info("deleteFile {}", objectName);
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** Первое сообщение, с которым создаётся чат. */
|
||||||
|
@Data
|
||||||
|
public class StartChatRequest {
|
||||||
|
private String content;
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.krylov.refound.entity;
|
package com.krylov.refound.entity;
|
||||||
|
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import jakarta.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
@@ -18,7 +19,7 @@ import lombok.ToString;
|
|||||||
import org.hibernate.proxy.HibernateProxy;
|
import org.hibernate.proxy.HibernateProxy;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "chats", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_one_id", "user_two_id"})})
|
@Table(name = "chats", uniqueConstraints = {@UniqueConstraint(name = "uq_chat_users_post", columnNames = {"user_one_id", "user_two_id", "post_id"})})
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@ToString
|
@ToString
|
||||||
@@ -42,7 +43,7 @@ public class Chat {
|
|||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
createdAt = LocalDateTime.now();
|
createdAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.krylov.refound.entity;
|
package com.krylov.refound.entity;
|
||||||
|
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import jakarta.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
@@ -38,6 +39,6 @@ public class Message {
|
|||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
createdAt = LocalDateTime.now();
|
createdAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import jakarta.persistence.GenerationType;
|
|||||||
import jakarta.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import jakarta.persistence.ManyToOne;
|
import jakarta.persistence.ManyToOne;
|
||||||
import jakarta.persistence.OneToMany;
|
import jakarta.persistence.OneToMany;
|
||||||
|
import jakarta.persistence.OrderBy;
|
||||||
import jakarta.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -58,7 +59,9 @@ public class Post {
|
|||||||
@JsonIgnore
|
@JsonIgnore
|
||||||
private User user;
|
private User user;
|
||||||
|
|
||||||
|
// Порядок загрузки: первая картинка (обложка в ленте, чатах, на карте) должна быть стабильной
|
||||||
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
|
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
|
@OrderBy("id ASC")
|
||||||
private List<Image> images = new ArrayList<>();
|
private List<Image> images = new ArrayList<>();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.krylov.refound.entity;
|
package com.krylov.refound.entity;
|
||||||
|
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import jakarta.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
@@ -34,6 +35,6 @@ public class Review {
|
|||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
createdAt = LocalDateTime.now();
|
createdAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.krylov.refound.entity;
|
package com.krylov.refound.entity;
|
||||||
|
|
||||||
import com.krylov.refound.enums.Role;
|
import com.krylov.refound.enums.Role;
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import jakarta.persistence.EnumType;
|
import jakarta.persistence.EnumType;
|
||||||
@@ -36,6 +37,6 @@ public class User {
|
|||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
public void prePersist() {
|
public void prePersist() {
|
||||||
this.createdAt = LocalDateTime.now();
|
this.createdAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.krylov.refound.entity.advertising;
|
|||||||
|
|
||||||
import com.krylov.refound.enums.advertising.AdvertisingType;
|
import com.krylov.refound.enums.advertising.AdvertisingType;
|
||||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
@@ -60,7 +61,7 @@ public class Advertising {
|
|||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
if (createdAt == null) {
|
if (createdAt == null) {
|
||||||
createdAt = LocalDateTime.now();
|
createdAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.krylov.refound.entity.advertising;
|
package com.krylov.refound.entity.advertising;
|
||||||
|
|
||||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
@@ -48,7 +49,7 @@ public class Campaign {
|
|||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
if (createdAt == null) {
|
if (createdAt == null) {
|
||||||
createdAt = LocalDateTime.now();
|
createdAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.krylov.refound.entity.advertising;
|
package com.krylov.refound.entity.advertising;
|
||||||
|
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
@@ -32,7 +33,7 @@ public class Click {
|
|||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
if (clickedAt == null) {
|
if (clickedAt == null) {
|
||||||
clickedAt = LocalDateTime.now();
|
clickedAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ package com.krylov.refound.entity.advertising;
|
|||||||
|
|
||||||
import com.krylov.refound.enums.advertising.FullscreenAdStatus;
|
import com.krylov.refound.enums.advertising.FullscreenAdStatus;
|
||||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
@@ -38,7 +39,7 @@ public class FullscreenAdvertising {
|
|||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
if (createdAt == null) {
|
if (createdAt == null) {
|
||||||
createdAt = LocalDateTime.now();
|
createdAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.krylov.refound.entity.advertising;
|
package com.krylov.refound.entity.advertising;
|
||||||
|
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
@@ -32,7 +33,7 @@ public class Impression {
|
|||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
if (shownAt == null) {
|
if (shownAt == null) {
|
||||||
shownAt = LocalDateTime.now();
|
shownAt = TimeZoneContext.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,16 +10,20 @@ import org.springframework.data.repository.query.Param;
|
|||||||
|
|
||||||
public interface ChatRepository extends JpaRepository<Chat, Long> {
|
public interface ChatRepository extends JpaRepository<Chat, Long> {
|
||||||
|
|
||||||
@Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2")
|
/** Чат пары пользователей по конкретному объявлению (postId == null — чат без объявления). */
|
||||||
Optional<Chat> findByUsers(Long u1, Long u2);
|
@Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2 "
|
||||||
|
+ "AND ((:postId IS NULL AND c.postId IS NULL) OR c.postId = :postId)")
|
||||||
|
List<Chat> findByUsersAndPost(Long u1, Long u2, Long postId);
|
||||||
|
|
||||||
/** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */
|
/** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */
|
||||||
@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c "
|
@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c "
|
||||||
+ "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)")
|
+ "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)")
|
||||||
boolean isParticipantOfChat(Long chatId, Long userId);
|
boolean isParticipantOfChat(Long chatId, Long userId);
|
||||||
|
|
||||||
@Query("SELECT c FROM Chat c WHERE c.userOneId = :userId OR c.userTwoId = :userId ORDER BY c.createdAt DESC")
|
/** Чаты пользователя, в которых есть хотя бы одно сообщение (пустые в списке не показываем). */
|
||||||
List<Chat> findAllByUserId(Long userId); // Changed from Optional to List
|
@Query("SELECT c FROM Chat c WHERE (c.userOneId = :userId OR c.userTwoId = :userId) "
|
||||||
|
+ "AND EXISTS (SELECT 1 FROM Message m WHERE m.chatId = c.id) ORDER BY c.createdAt DESC")
|
||||||
|
List<Chat> findAllByUserId(Long userId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась.
|
* Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась.
|
||||||
|
|||||||
@@ -6,43 +6,86 @@ import com.krylov.refound.dto.MessageDto;
|
|||||||
import com.krylov.refound.entity.Chat;
|
import com.krylov.refound.entity.Chat;
|
||||||
import com.krylov.refound.entity.Image;
|
import com.krylov.refound.entity.Image;
|
||||||
import com.krylov.refound.entity.Message;
|
import com.krylov.refound.entity.Message;
|
||||||
|
import com.krylov.refound.entity.Post;
|
||||||
|
import com.krylov.refound.enums.ErrorCode;
|
||||||
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.repository.ChatRepository;
|
import com.krylov.refound.repository.ChatRepository;
|
||||||
import com.krylov.refound.repository.MessageRepository;
|
import com.krylov.refound.repository.MessageRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
import com.krylov.refound.repository.UserRepository;
|
import com.krylov.refound.repository.UserRepository;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.transaction.support.TransactionSynchronization;
|
||||||
|
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class ChatService {
|
public class ChatService {
|
||||||
|
|
||||||
|
/** Максимальная длина сообщения в символах. */
|
||||||
|
public static final int MAX_MESSAGE_LENGTH = 4000;
|
||||||
|
|
||||||
private final ChatRepository chatRepository;
|
private final ChatRepository chatRepository;
|
||||||
private final MessageRepository messageRepository;
|
private final MessageRepository messageRepository;
|
||||||
private final SimpMessagingTemplate messagingTemplate;
|
private final SimpMessagingTemplate messagingTemplate;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final PostRepository postRepository;
|
private final PostRepository postRepository;
|
||||||
|
|
||||||
// Создать чат с пользователем (или вернуть существующий)
|
/**
|
||||||
|
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
|
||||||
|
* Пустой чат «на будущее» не заводим: он появляется только с первым сообщением.
|
||||||
|
*/
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Optional<ChatDto> findChat(Long currentUserId, Long otherUserId, Long postId) {
|
||||||
|
Long userId1 = Math.min(currentUserId, otherUserId);
|
||||||
|
Long userId2 = Math.max(currentUserId, otherUserId);
|
||||||
|
return chatRepository.findByUsersAndPost(userId1, userId2, postId).stream()
|
||||||
|
.findFirst()
|
||||||
|
.map(chat -> toDto(chat, currentUserId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Первое сообщение собеседнику по объявлению: в одной транзакции находит или создаёт
|
||||||
|
* чат и сохраняет сообщение. Так в базе не остаётся чатов без сообщений.
|
||||||
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public ChatDto getOrCreateChat(Long currentUserId, Long otherUserId, Long postId) {
|
public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) {
|
||||||
|
validateContent(content);
|
||||||
if (currentUserId.equals(otherUserId)) {
|
if (currentUserId.equals(otherUserId)) {
|
||||||
throw new IllegalArgumentException("Нельзя создать чат с самим собой");
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
if (!userRepository.existsById(otherUserId)) {
|
||||||
|
throw new ApiException(ErrorCode.NOT_FOUND, "Пользователь не найден", HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
if (postId != null) {
|
||||||
|
// Иначе клиент мог прикрепить к чату любое чужое объявление
|
||||||
|
Post post = postRepository.findById(postId)
|
||||||
|
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Объявление не найдено", HttpStatus.NOT_FOUND));
|
||||||
|
Long ownerId = post.getUser().getId();
|
||||||
|
if (!ownerId.equals(currentUserId) && !ownerId.equals(otherUserId)) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Объявление не принадлежит участнику чата", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Long userId1 = Math.min(currentUserId, otherUserId);
|
Long userId1 = Math.min(currentUserId, otherUserId);
|
||||||
Long userId2 = Math.max(currentUserId, otherUserId);
|
Long userId2 = Math.max(currentUserId, otherUserId);
|
||||||
|
|
||||||
Chat chat = chatRepository.findByUsers(userId1, userId2).orElseGet(() -> {
|
// Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому
|
||||||
|
// объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов)
|
||||||
|
Chat chat = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst().orElseGet(() -> {
|
||||||
Chat newChat = new Chat();
|
Chat newChat = new Chat();
|
||||||
newChat.setUserOneId(userId1);
|
newChat.setUserOneId(userId1);
|
||||||
newChat.setUserTwoId(userId2);
|
newChat.setUserTwoId(userId2);
|
||||||
@@ -50,14 +93,23 @@ public class ChatService {
|
|||||||
return chatRepository.save(newChat);
|
return chatRepository.save(newChat);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
saveAndBroadcast(chat, currentUserId, content);
|
||||||
return toDto(chat, currentUserId);
|
return toDto(chat, currentUserId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Все чаты пользователя
|
// Все чаты пользователя: сверху чаты с самым свежим сообщением (или самые новые, если сообщений нет)
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public List<ChatDto> getUserChats(Long userId) {
|
public List<ChatDto> getUserChats(Long userId) {
|
||||||
|
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
|
||||||
|
}
|
||||||
|
|
||||||
return chatRepository.findAllByUserId(userId).stream()
|
return chatRepository.findAllByUserId(userId).stream()
|
||||||
.map(c -> toDto(c, userId))
|
.map(c -> {
|
||||||
|
ChatDto dto = toDto(c, userId);
|
||||||
|
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : c.getCreatedAt());
|
||||||
|
})
|
||||||
|
.sorted(Comparator.comparing(ChatWithActivity::lastActivity, Comparator.nullsLast(Comparator.reverseOrder())))
|
||||||
|
.map(ChatWithActivity::dto)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,9 +125,26 @@ public class ChatService {
|
|||||||
// Отправка сообщения (вызывается из WebSocket контроллера)
|
// Отправка сообщения (вызывается из WebSocket контроллера)
|
||||||
@Transactional
|
@Transactional
|
||||||
public void sendMessage(Long senderId, Long chatId, String content) {
|
public void sendMessage(Long senderId, Long chatId, String content) {
|
||||||
|
validateContent(content);
|
||||||
|
|
||||||
Chat chat = getChatOrThrow(chatId);
|
Chat chat = getChatOrThrow(chatId);
|
||||||
checkParticipant(chat, senderId);
|
checkParticipant(chat, senderId);
|
||||||
|
|
||||||
|
saveAndBroadcast(chat, senderId, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateContent(String content) {
|
||||||
|
if (content == null || content.isBlank()) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Пустое сообщение", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
if (content.length() > MAX_MESSAGE_LENGTH) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||||
|
"Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveAndBroadcast(Chat chat, Long senderId, String content) {
|
||||||
|
Long chatId = chat.getId();
|
||||||
Message message = new Message();
|
Message message = new Message();
|
||||||
message.setChatId(chatId);
|
message.setChatId(chatId);
|
||||||
message.setSenderId(senderId);
|
message.setSenderId(senderId);
|
||||||
@@ -84,8 +153,6 @@ public class ChatService {
|
|||||||
|
|
||||||
MessageDto dto = toMessageDto(message);
|
MessageDto dto = toMessageDto(message);
|
||||||
|
|
||||||
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
|
|
||||||
|
|
||||||
// Уведомляем получателя об непрочитанных
|
// Уведомляем получателя об непрочитанных
|
||||||
Long recipientId = chat.getUserOneId().equals(senderId)
|
Long recipientId = chat.getUserOneId().equals(senderId)
|
||||||
? chat.getUserTwoId()
|
? chat.getUserTwoId()
|
||||||
@@ -93,11 +160,28 @@ public class ChatService {
|
|||||||
|
|
||||||
long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId);
|
long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId);
|
||||||
|
|
||||||
|
// Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
|
||||||
|
// историю, мог не увидеть ещё не закоммиченное сообщение
|
||||||
|
afterCommit(() -> {
|
||||||
|
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
|
||||||
messagingTemplate.convertAndSend(
|
messagingTemplate.convertAndSend(
|
||||||
"/topic/user/" + recipientId + "/unread",
|
"/topic/user/" + recipientId + "/unread",
|
||||||
Map.of("chatId", chatId, "unreadCount", unreadCount)
|
Map.of("chatId", chatId, "unreadCount", unreadCount)
|
||||||
);
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void afterCommit(Runnable action) {
|
||||||
|
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||||
|
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||||
|
@Override
|
||||||
|
public void afterCommit() {
|
||||||
|
action.run();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
action.run();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -128,12 +212,13 @@ public class ChatService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Chat getChatOrThrow(Long chatId) {
|
private Chat getChatOrThrow(Long chatId) {
|
||||||
return chatRepository.findById(chatId).orElseThrow(() -> new IllegalArgumentException("Чат не найден"));
|
return chatRepository.findById(chatId)
|
||||||
|
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Чат не найден", HttpStatus.NOT_FOUND));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void checkParticipant(Chat chat, Long userId) {
|
private void checkParticipant(Chat chat, Long userId) {
|
||||||
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
|
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
|
||||||
throw new SecurityException("Вы не участник этого чата");
|
throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,12 +38,15 @@ import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
|||||||
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||||
import software.amazon.awssdk.services.s3.model.S3Exception;
|
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||||
import software.amazon.awssdk.core.exception.SdkClientException;
|
import software.amazon.awssdk.core.exception.SdkClientException;
|
||||||
|
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
||||||
|
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class FileStorageService {
|
public class FileStorageService {
|
||||||
private final S3Client s3Client;
|
private final S3Client s3Client;
|
||||||
|
private final S3Presigner s3Presigner;
|
||||||
private final MinioProperties properties;
|
private final MinioProperties properties;
|
||||||
private final StringRedisTemplate redisTemplate;
|
private final StringRedisTemplate redisTemplate;
|
||||||
|
|
||||||
@@ -126,6 +129,38 @@ public class FileStorageService {
|
|||||||
.body(file.content());
|
.body(file.content());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Генерирует presigned URL для скачивания файла напрямую из MinIO/S3.
|
||||||
|
* Браузер будет загружать картинку по этому URL, минуя backend (меньше нагрузки).
|
||||||
|
*/
|
||||||
|
public String generatePresignedDownloadUrl(String objectName, Duration ttl) {
|
||||||
|
try {
|
||||||
|
GetObjectRequest getRequest = GetObjectRequest.builder()
|
||||||
|
.bucket(properties.bucket())
|
||||||
|
.key(objectName)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()
|
||||||
|
.signatureDuration(ttl)
|
||||||
|
.getObjectRequest(getRequest)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
String url = s3Presigner.presignGetObject(presignRequest).url().toString();
|
||||||
|
log.debug("Сгенерирован presigned URL для файла '{}', TTL={}", objectName, ttl);
|
||||||
|
return url;
|
||||||
|
} catch (S3Exception | SdkClientException e) {
|
||||||
|
log.error("Ошибка при генерации presigned URL для файла '{}': {}", objectName, e.getMessage(), e);
|
||||||
|
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при формировании ссылки на файл.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Генерирует presigned URL со стандартным TTL.
|
||||||
|
*/
|
||||||
|
public String generatePresignedDownloadUrl(String objectName) {
|
||||||
|
return generatePresignedDownloadUrl(objectName, Duration.ofHours(24));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Скачивает файл из MinIO без HTTP-обёртки — оригинальное имя, content-type и байты.
|
* Скачивает файл из MinIO без HTTP-обёртки — оригинальное имя, content-type и байты.
|
||||||
* Используется там, где нет HTTP-контекста (например, в PostModerationScheduler,
|
* Используется там, где нет HTTP-контекста (например, в PostModerationScheduler,
|
||||||
|
|||||||
@@ -55,6 +55,12 @@ public class PostModerationExecutorService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!approved) {
|
||||||
|
postRepository.updateStatus(postId, PostStatus.REJECTED);
|
||||||
|
log.info("Пост {} отклонён модерацией.", post.getId());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
postRepository.updateStatus(postId, PostStatus.ACTIVE);
|
postRepository.updateStatus(postId, PostStatus.ACTIVE);
|
||||||
log.info("Пост {} прошёл модерацию.", post.getId());
|
log.info("Пост {} прошёл модерацию.", post.getId());
|
||||||
|
|
||||||
|
|||||||
@@ -22,17 +22,14 @@ import com.krylov.refound.service.redis.PostCacheKeyGenerator;
|
|||||||
import com.krylov.refound.service.redis.PostCacheService;
|
import com.krylov.refound.service.redis.PostCacheService;
|
||||||
import com.krylov.refound.util.PostSpecification;
|
import com.krylov.refound.util.PostSpecification;
|
||||||
import com.krylov.refound.util.PostVisibility;
|
import com.krylov.refound.util.PostVisibility;
|
||||||
import java.time.Duration;
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.EnumSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Set;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.PageImpl;
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
import org.springframework.data.jpa.domain.Specification;
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -40,6 +37,11 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -66,7 +68,7 @@ public class PostService {
|
|||||||
User currentUser = userService.getCurrentUser();
|
User currentUser = userService.getCurrentUser();
|
||||||
|
|
||||||
Post post = mapper.toEntity(request);
|
Post post = mapper.toEntity(request);
|
||||||
post.setCreatedAt(LocalDateTime.now());
|
post.setCreatedAt(TimeZoneContext.now());
|
||||||
post.setStatus(PostStatus.MODERATION);
|
post.setStatus(PostStatus.MODERATION);
|
||||||
post.setUser(currentUser);
|
post.setUser(currentUser);
|
||||||
post.setIsReward(request.getReward());
|
post.setIsReward(request.getReward());
|
||||||
@@ -92,6 +94,13 @@ public class PostService {
|
|||||||
|
|
||||||
public Page<PostResponse> getFeed(String search, Pageable pageable) {
|
public Page<PostResponse> getFeed(String search, Pageable pageable) {
|
||||||
|
|
||||||
|
// Без уникального ключа в сортировке порядок постов с одинаковым createdAt
|
||||||
|
// недетерминирован, и при LIMIT/OFFSET посты дублируются или пропадают между страницами
|
||||||
|
if (pageable.getSort().getOrderFor("id") == null) {
|
||||||
|
pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(),
|
||||||
|
pageable.getSort().and(Sort.by(Sort.Direction.DESC, "id")));
|
||||||
|
}
|
||||||
|
|
||||||
// Ключ содержит версию ленты, она читается до запроса в БД
|
// Ключ содержит версию ленты, она читается до запроса в БД
|
||||||
String cacheKey = postCacheKeyGenerator.feedKey(search, pageable);
|
String cacheKey = postCacheKeyGenerator.feedKey(search, pageable);
|
||||||
|
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ import com.krylov.refound.dto.ReviewRequestDto;
|
|||||||
import com.krylov.refound.dto.ReviewResponseDto;
|
import com.krylov.refound.dto.ReviewResponseDto;
|
||||||
import com.krylov.refound.entity.Review;
|
import com.krylov.refound.entity.Review;
|
||||||
import com.krylov.refound.repository.ReviewRepository;
|
import com.krylov.refound.repository.ReviewRepository;
|
||||||
import jakarta.validation.Valid;
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.List;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class ReviewService {
|
public class ReviewService {
|
||||||
@@ -28,7 +28,7 @@ public class ReviewService {
|
|||||||
review.setAuthorName(username); // или firstName из User
|
review.setAuthorName(username); // или firstName из User
|
||||||
review.setRating(request.getRating());
|
review.setRating(request.getRating());
|
||||||
review.setText(request.getText());
|
review.setText(request.getText());
|
||||||
review.setCreatedAt(LocalDateTime.now());
|
review.setCreatedAt(TimeZoneContext.now());
|
||||||
|
|
||||||
Review saved = reviewRepository.save(review);
|
Review saved = reviewRepository.save(review);
|
||||||
return toResponse(saved);
|
return toResponse(saved);
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import com.krylov.refound.entity.Post;
|
|||||||
import com.krylov.refound.enums.PostStatus;
|
import com.krylov.refound.enums.PostStatus;
|
||||||
import com.krylov.refound.repository.FavoriteRepository;
|
import com.krylov.refound.repository.FavoriteRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
|
import com.krylov.refound.service.redis.MapCacheService;
|
||||||
|
import com.krylov.refound.service.redis.PostCacheService;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -20,6 +22,8 @@ public class SchedulerService {
|
|||||||
private final PostRepository postRepository;
|
private final PostRepository postRepository;
|
||||||
private final FavoriteRepository favoriteRepository;
|
private final FavoriteRepository favoriteRepository;
|
||||||
private final PostModerationExecutorService postModerationExecutorService;
|
private final PostModerationExecutorService postModerationExecutorService;
|
||||||
|
private final PostCacheService postCacheService;
|
||||||
|
private final MapCacheService mapCacheService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runs every day at 00:01 to delete:
|
* Runs every day at 00:01 to delete:
|
||||||
@@ -55,6 +59,12 @@ public class SchedulerService {
|
|||||||
log.info("Deleted {} posts older than 6 months", oldPosts.size());
|
log.info("Deleted {} posts older than 6 months", oldPosts.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!closedPosts.isEmpty() || !oldPosts.isEmpty()) {
|
||||||
|
// Иначе удалённые посты висят в ленте и на карте до TTL кэша
|
||||||
|
postCacheService.invalidatePosts();
|
||||||
|
mapCacheService.clearMapMarkersCache();
|
||||||
|
}
|
||||||
|
|
||||||
log.info("Scheduled cleanup completed successfully");
|
log.info("Scheduled cleanup completed successfully");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
84
src/main/java/com/krylov/refound/util/TimeZoneContext.java
Normal file
84
src/main/java/com/krylov/refound/util/TimeZoneContext.java
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
package com.krylov.refound.util;
|
||||||
|
|
||||||
|
import java.time.DateTimeException;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хранит таймзону текущего пользователя в ThreadLocal и отдаёт локальное время
|
||||||
|
* в этой зоне. Значение выставляет {@link com.krylov.refound.config.TimeZoneFilter}
|
||||||
|
* из заголовка {@code X-Timezone}; для WebSocket — из CONNECT-заголовка.
|
||||||
|
*
|
||||||
|
* <p>Принимаются IANA-идентификаторы ("Europe/Moscow"), offset ("+03:00") и
|
||||||
|
* смещение в минутах ("180"). Если клиент таймзону не прислал, используется
|
||||||
|
* зона сервера.
|
||||||
|
*/
|
||||||
|
public final class TimeZoneContext {
|
||||||
|
|
||||||
|
public static final String HEADER = "X-Timezone";
|
||||||
|
public static final String WS_HEADER = "timezone";
|
||||||
|
public static final String SESSION_ATTRIBUTE = "timezone";
|
||||||
|
|
||||||
|
private static final ThreadLocal<ZoneId> CURRENT = new ThreadLocal<>();
|
||||||
|
|
||||||
|
private TimeZoneContext() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void set(String rawZone) {
|
||||||
|
ZoneId zone = parse(rawZone);
|
||||||
|
if (zone == null) {
|
||||||
|
CURRENT.remove();
|
||||||
|
} else {
|
||||||
|
CURRENT.set(zone);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void clear() {
|
||||||
|
CURRENT.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ZoneId get() {
|
||||||
|
ZoneId zone = CURRENT.get();
|
||||||
|
return zone != null ? zone : ZoneId.systemDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return текущее время в зоне пользователя (или сервера, если зона не задана).
|
||||||
|
*/
|
||||||
|
public static LocalDateTime now() {
|
||||||
|
return LocalDateTime.now(get());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return распознанная зона или {@code null}, если значение не задано/невалидно.
|
||||||
|
*/
|
||||||
|
public static ZoneId parse(String raw) {
|
||||||
|
if (raw == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String value = raw.trim();
|
||||||
|
if (value.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// смещение в минутах от UTC: "180", "-300"
|
||||||
|
try {
|
||||||
|
int minutes = Integer.parseInt(value);
|
||||||
|
return ZoneId.ofOffset("UTC", ZoneOffset.ofTotalSeconds(minutes * 60));
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
// значение не число — пробуем другие форматы
|
||||||
|
}
|
||||||
|
// offset: "+03:00", "+0300", "+03"
|
||||||
|
try {
|
||||||
|
return ZoneOffset.of(value);
|
||||||
|
} catch (DateTimeException ignored) {
|
||||||
|
// не offset — пробуем IANA
|
||||||
|
}
|
||||||
|
// IANA-идентификатор: "Europe/Moscow", "UTC+3"
|
||||||
|
try {
|
||||||
|
return ZoneId.of(value);
|
||||||
|
} catch (DateTimeException ignored) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -82,6 +82,12 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
|||||||
accessor.getSessionAttributes().put(USER_ID_ATTR, userId);
|
accessor.getSessionAttributes().put(USER_ID_ATTR, userId);
|
||||||
accessor.getSessionAttributes().put(ROLE_ATTR, role);
|
accessor.getSessionAttributes().put(ROLE_ATTR, role);
|
||||||
|
|
||||||
|
// Таймзону присылает клиент на CONNECT; применяется при сохранении Message
|
||||||
|
String timezone = accessor.getFirstNativeHeader(TimeZoneContext.WS_HEADER);
|
||||||
|
if (timezone != null) {
|
||||||
|
accessor.getSessionAttributes().put(TimeZoneContext.SESSION_ATTRIBUTE, timezone);
|
||||||
|
}
|
||||||
|
|
||||||
log.info("WS connected: userId={} role={}", userId, role);
|
log.info("WS connected: userId={} role={}", userId, role);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
ffmpeg:
|
ffmpeg:
|
||||||
binary-path: C:\ffmpeg\ffmpeg-9.0.2-essentials_build\bin\ffmpeg.exe
|
binary-path: ${FFMPEG_PATH:C:\ffmpeg\ffmpeg-9.0.2-essentials_build\bin\ffmpeg.exe}
|
||||||
|
|
||||||
spring:
|
spring:
|
||||||
servlet:
|
servlet:
|
||||||
@@ -8,9 +8,9 @@ spring:
|
|||||||
max-request-size: 20MB
|
max-request-size: 20MB
|
||||||
|
|
||||||
datasource:
|
datasource:
|
||||||
url: jdbc:postgresql://localhost:5432/nahodka
|
url: ${DB_URL:jdbc:postgresql://localhost:5432/nahodka}
|
||||||
username: user
|
username: ${DB_USER:user}
|
||||||
password: pass
|
password: ${DB_PASSWORD:pass}
|
||||||
driver-class-name: org.postgresql.Driver
|
driver-class-name: org.postgresql.Driver
|
||||||
|
|
||||||
jpa:
|
jpa:
|
||||||
@@ -19,7 +19,7 @@ spring:
|
|||||||
# из-за чего базы расходились. Для разработки можно переопределить
|
# из-за чего базы расходились. Для разработки можно переопределить
|
||||||
# переменной окружения JPA_DDL_AUTO=update.
|
# переменной окружения JPA_DDL_AUTO=update.
|
||||||
ddl-auto: ${JPA_DDL_AUTO:validate}
|
ddl-auto: ${JPA_DDL_AUTO:validate}
|
||||||
show-sql: true
|
show-sql: ${JPA_SHOW_SQL:true}
|
||||||
properties:
|
properties:
|
||||||
hibernate:
|
hibernate:
|
||||||
format_sql: true
|
format_sql: true
|
||||||
@@ -55,10 +55,10 @@ ai:
|
|||||||
multiplier: 2
|
multiplier: 2
|
||||||
|
|
||||||
jwt:
|
jwt:
|
||||||
secret: ${JWT_SECRET:mySuperSecretKeyForJwtTokenGenerationThatIsLongEnough2024!ReFound}
|
secret: ${JWT_SECRET}
|
||||||
access-expiration: ${JWT_ACCESS_EXPIRATION:900000} # 15 минут
|
access-expiration: ${JWT_ACCESS_EXPIRATION:900000} # 15 минут
|
||||||
refresh-expiration: ${JWT_REFRESH_EXPIRATION:604800000} # 7 дней
|
refresh-expiration: ${JWT_REFRESH_EXPIRATION:604800000} # 7 дней
|
||||||
|
|
||||||
app:
|
app:
|
||||||
cors:
|
cors:
|
||||||
allowed-origins: http://localhost:5173,http://localhost:3000,http://192.168.1.76:3000
|
allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:5173,http://localhost:3000,http://192.168.1.76:3000}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
databaseChangeLog:
|
||||||
|
- changeSet:
|
||||||
|
id: 015-chats-unique-per-post
|
||||||
|
author: krylov
|
||||||
|
comment: >
|
||||||
|
Чат теперь уникален для пары пользователей И объявления. Раньше уникальной была
|
||||||
|
только пара, и при обращении к тому же автору по другому объявлению возвращался
|
||||||
|
старый чат со старым post_id (не та картинка во вкладке чатов).
|
||||||
|
Имя старого ограничения может отличаться (таблицу раньше создавал Hibernate),
|
||||||
|
поэтому удаляем любое unique-ограничение ровно по (user_one_id, user_two_id).
|
||||||
|
preConditions:
|
||||||
|
onFail: MARK_RAN
|
||||||
|
tableExists:
|
||||||
|
tableName: chats
|
||||||
|
changes:
|
||||||
|
- sql:
|
||||||
|
splitStatements: false
|
||||||
|
sql: |
|
||||||
|
DO $$
|
||||||
|
DECLARE r record;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN
|
||||||
|
SELECT con.conname
|
||||||
|
FROM pg_constraint con
|
||||||
|
JOIN pg_class t ON t.oid = con.conrelid
|
||||||
|
WHERE t.relname = 'chats'
|
||||||
|
AND con.contype = 'u'
|
||||||
|
AND (SELECT array_agg(a.attname::text ORDER BY a.attname::text)
|
||||||
|
FROM pg_attribute a
|
||||||
|
WHERE a.attrelid = t.oid AND a.attnum = ANY (con.conkey))
|
||||||
|
= ARRAY['user_one_id', 'user_two_id']
|
||||||
|
LOOP
|
||||||
|
EXECUTE format('ALTER TABLE chats DROP CONSTRAINT %I', r.conname);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
- addUniqueConstraint:
|
||||||
|
tableName: chats
|
||||||
|
columnNames: user_one_id, user_two_id, post_id
|
||||||
|
constraintName: uq_chat_users_post
|
||||||
@@ -29,3 +29,4 @@ databaseChangeLog:
|
|||||||
- include: { file: db/changelog/create/006-create-chats.yaml }
|
- include: { file: db/changelog/create/006-create-chats.yaml }
|
||||||
- include: { file: db/changelog/add/017-messages-chat-id.yaml }
|
- include: { file: db/changelog/add/017-messages-chat-id.yaml }
|
||||||
- include: { file: db/changelog/alter/014-posts-rules-accepted-type.yaml }
|
- include: { file: db/changelog/alter/014-posts-rules-accepted-type.yaml }
|
||||||
|
- include: { file: db/changelog/alter/015-chats-unique-per-post.yaml }
|
||||||
|
|||||||
115
src/test/java/com/krylov/refound/service/ChatServiceTest.java
Normal file
115
src/test/java/com/krylov/refound/service/ChatServiceTest.java
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
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.anyLong;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import com.krylov.refound.dto.ChatDto;
|
||||||
|
import com.krylov.refound.entity.Chat;
|
||||||
|
import com.krylov.refound.entity.Message;
|
||||||
|
import com.krylov.refound.entity.Post;
|
||||||
|
import com.krylov.refound.entity.User;
|
||||||
|
import com.krylov.refound.exception.ApiException;
|
||||||
|
import com.krylov.refound.repository.ChatRepository;
|
||||||
|
import com.krylov.refound.repository.MessageRepository;
|
||||||
|
import com.krylov.refound.repository.PostRepository;
|
||||||
|
import com.krylov.refound.repository.UserRepository;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||||
|
|
||||||
|
class ChatServiceTest {
|
||||||
|
|
||||||
|
private ChatRepository chatRepository;
|
||||||
|
private UserRepository userRepository;
|
||||||
|
private PostRepository postRepository;
|
||||||
|
private MessageRepository messageRepository;
|
||||||
|
private ChatService chatService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
chatRepository = mock(ChatRepository.class);
|
||||||
|
userRepository = mock(UserRepository.class);
|
||||||
|
postRepository = mock(PostRepository.class);
|
||||||
|
messageRepository = mock(MessageRepository.class);
|
||||||
|
chatService = new ChatService(chatRepository, messageRepository, mock(SimpMessagingTemplate.class),
|
||||||
|
userRepository, postRepository);
|
||||||
|
|
||||||
|
when(userRepository.existsById(anyLong())).thenReturn(true);
|
||||||
|
when(messageRepository.findFirstByChatIdOrderByCreatedAtDesc(any())).thenReturn(Optional.empty());
|
||||||
|
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
|
||||||
|
when(chatRepository.save(any(Chat.class))).thenAnswer(inv -> {
|
||||||
|
Chat chat = inv.getArgument(0);
|
||||||
|
chat.setId(100L);
|
||||||
|
return chat;
|
||||||
|
});
|
||||||
|
when(messageRepository.save(any(Message.class))).thenAnswer(inv -> {
|
||||||
|
Message message = inv.getArgument(0);
|
||||||
|
message.setId(500L);
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void postOwnedBy(long postId, long ownerId) {
|
||||||
|
User owner = new User();
|
||||||
|
owner.setId(ownerId);
|
||||||
|
Post post = new Post();
|
||||||
|
post.setId(postId);
|
||||||
|
post.setUser(owner);
|
||||||
|
when(postRepository.findById(postId)).thenReturn(Optional.of(post));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void startChatCreatesChatTogetherWithFirstMessage() {
|
||||||
|
postOwnedBy(41L, 19L);
|
||||||
|
|
||||||
|
ChatDto chat = chatService.startChat(14L, 19L, 41L, "Здравствуйте");
|
||||||
|
|
||||||
|
assertThat(chat.getPostId()).isEqualTo(41L);
|
||||||
|
assertThat(chat.getOtherUserId()).isEqualTo(19L);
|
||||||
|
ArgumentCaptor<Message> saved = ArgumentCaptor.forClass(Message.class);
|
||||||
|
verify(messageRepository).save(saved.capture());
|
||||||
|
assertThat(saved.getValue().getChatId()).isEqualTo(100L);
|
||||||
|
assertThat(saved.getValue().getContent()).isEqualTo("Здравствуйте");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void findChatDoesNotCreateChat() {
|
||||||
|
assertThat(chatService.findChat(14L, 19L, 41L)).isEmpty();
|
||||||
|
verify(chatRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsEmptyFirstMessageWithoutCreatingChat() {
|
||||||
|
postOwnedBy(41L, 19L);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> chatService.startChat(14L, 19L, 41L, " "))
|
||||||
|
.isInstanceOf(ApiException.class);
|
||||||
|
verify(chatRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsPostOfThirdUser() {
|
||||||
|
postOwnedBy(41L, 7L);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> chatService.startChat(14L, 19L, 41L, "Здравствуйте"))
|
||||||
|
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||||
|
verify(chatRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsChatWithYourself() {
|
||||||
|
assertThatThrownBy(() -> chatService.startChat(19L, 19L, 41L, "Здравствуйте"))
|
||||||
|
.isInstanceOf(ApiException.class)
|
||||||
|
.hasMessageContaining("самим собой");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,377 @@
|
|||||||
|
package com.krylov.refound.service.admin;
|
||||||
|
|
||||||
|
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.anyCollection;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyList;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
import static org.mockito.Mockito.withSettings;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.krylov.refound.dto.AddressInfo;
|
||||||
|
import com.krylov.refound.dto.admin.AdminPostResponse;
|
||||||
|
import com.krylov.refound.entity.Image;
|
||||||
|
import com.krylov.refound.entity.Post;
|
||||||
|
import com.krylov.refound.entity.User;
|
||||||
|
import com.krylov.refound.enums.PostCategory;
|
||||||
|
import com.krylov.refound.enums.PostStatus;
|
||||||
|
import com.krylov.refound.enums.PostType;
|
||||||
|
import com.krylov.refound.exception.ApiException;
|
||||||
|
import com.krylov.refound.repository.ChatRepository;
|
||||||
|
import com.krylov.refound.repository.FavoriteRepository;
|
||||||
|
import com.krylov.refound.repository.ImageRepository;
|
||||||
|
import com.krylov.refound.repository.PostRepository;
|
||||||
|
import com.krylov.refound.service.FileStorageService;
|
||||||
|
import com.krylov.refound.service.GeocodingService;
|
||||||
|
import com.krylov.refound.service.StatisticsService;
|
||||||
|
import com.krylov.refound.service.redis.MapCacheService;
|
||||||
|
import com.krylov.refound.service.redis.PostCacheService;
|
||||||
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
|
import jakarta.persistence.criteria.Expression;
|
||||||
|
import jakarta.persistence.criteria.Path;
|
||||||
|
import jakarta.persistence.criteria.Predicate;
|
||||||
|
import jakarta.persistence.criteria.Root;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.Spy;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class AdminPostServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private PostRepository postRepository;
|
||||||
|
@Mock
|
||||||
|
private ImageRepository imageRepository;
|
||||||
|
@Mock
|
||||||
|
private FavoriteRepository favoriteRepository;
|
||||||
|
@Mock
|
||||||
|
private ChatRepository chatRepository;
|
||||||
|
@Mock
|
||||||
|
private FileStorageService fileStorageService;
|
||||||
|
@Mock
|
||||||
|
private GeocodingService geocodingService;
|
||||||
|
@Mock
|
||||||
|
private PostCacheService postCacheService;
|
||||||
|
@Mock
|
||||||
|
private MapCacheService mapCacheService;
|
||||||
|
@Mock
|
||||||
|
private StatisticsService statisticsService;
|
||||||
|
|
||||||
|
@Spy
|
||||||
|
private ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private AdminPostService service;
|
||||||
|
|
||||||
|
private static Post post(Long id, PostStatus status) {
|
||||||
|
User owner = new User();
|
||||||
|
owner.setId(7L);
|
||||||
|
owner.setLogin("ivan");
|
||||||
|
owner.setName("Иван");
|
||||||
|
owner.setLastName("Петров");
|
||||||
|
|
||||||
|
Post post = new Post();
|
||||||
|
post.setId(id);
|
||||||
|
post.setStatus(status);
|
||||||
|
post.setType(PostType.LOSS);
|
||||||
|
post.setTitle("Кот");
|
||||||
|
post.setCategory(PostCategory.ANIMAL);
|
||||||
|
post.setCity("Москва");
|
||||||
|
post.setUser(owner);
|
||||||
|
return post;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getPosts_fillsOwnerAndImages() {
|
||||||
|
Post post = post(1L, PostStatus.ACTIVE);
|
||||||
|
Image image = new Image();
|
||||||
|
image.setId(5L);
|
||||||
|
image.setUrl("images/cat.png");
|
||||||
|
image.setPost(post);
|
||||||
|
|
||||||
|
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(post)));
|
||||||
|
when(imageRepository.findByPostIdIn(anyCollection())).thenReturn(List.of(image));
|
||||||
|
|
||||||
|
List<AdminPostResponse> content = service
|
||||||
|
.getPosts(null, null, null, PageRequest.of(0, 20))
|
||||||
|
.getContent();
|
||||||
|
|
||||||
|
assertThat(content).hasSize(1);
|
||||||
|
AdminPostResponse dto = content.get(0);
|
||||||
|
assertThat(dto.getOwnerLogin()).isEqualTo("ivan");
|
||||||
|
assertThat(dto.getOwnerFirstName()).isEqualTo("Иван");
|
||||||
|
assertThat(dto.getOwnerLastName()).isEqualTo("Петров");
|
||||||
|
assertThat(dto.getImages()).containsExactly("images/cat.png");
|
||||||
|
assertThat(dto.getStatus()).isEqualTo(PostStatus.ACTIVE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getPosts_rejectsUnknownFilterValue() {
|
||||||
|
assertThatThrownBy(() -> service.getPosts(null, "WRONG", null, PageRequest.of(0, 20)))
|
||||||
|
.isInstanceOf(ApiException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getPosts_clampsPageSize() {
|
||||||
|
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of()));
|
||||||
|
|
||||||
|
service.getPosts(null, null, null, PageRequest.of(0, 5000));
|
||||||
|
|
||||||
|
ArgumentCaptor<Pageable> captor = ArgumentCaptor.forClass(Pageable.class);
|
||||||
|
verify(postRepository).findAll(any(Specification.class), captor.capture());
|
||||||
|
assertThat(captor.getValue().getPageSize()).isEqualTo(100);
|
||||||
|
assertThat(captor.getValue().getSort().getOrderFor("createdAt")).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getPosts_limitsStatusesToActiveAndClosed() {
|
||||||
|
assertThat(statusesUsedByGetPosts()).containsExactlyInAnyOrder(PostStatus.ACTIVE, PostStatus.CLOSED);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getRejectedPosts_limitsStatusesToRejected() {
|
||||||
|
assertThat(statusesUsedByGetRejectedPosts()).containsExactly(PostStatus.REJECTED);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void feedsRejectStatusFromAnotherFeed() {
|
||||||
|
assertThatThrownBy(() -> service.getPosts(null, null, "REJECTED", PageRequest.of(0, 20)))
|
||||||
|
.isInstanceOf(ApiException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||||
|
assertThatThrownBy(() -> service.getRejectedPosts(null, null, "ACTIVE", PageRequest.of(0, 20)))
|
||||||
|
.isInstanceOf(ApiException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||||
|
verify(postRepository, never()).findAll(any(Specification.class), any(Pageable.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getRejectedPosts_returnsRejectedPostsWithOwnerAndImages() {
|
||||||
|
Post post = post(1L, PostStatus.REJECTED);
|
||||||
|
Image image = new Image();
|
||||||
|
image.setUrl("images/cat.png");
|
||||||
|
image.setPost(post);
|
||||||
|
|
||||||
|
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(post)));
|
||||||
|
when(imageRepository.findByPostIdIn(anyCollection())).thenReturn(List.of(image));
|
||||||
|
|
||||||
|
List<AdminPostResponse> content = service
|
||||||
|
.getRejectedPosts(null, null, null, PageRequest.of(0, 20))
|
||||||
|
.getContent();
|
||||||
|
|
||||||
|
assertThat(content).hasSize(1);
|
||||||
|
assertThat(content.get(0).getStatus()).isEqualTo(PostStatus.REJECTED);
|
||||||
|
assertThat(content.get(0).getOwnerLogin()).isEqualTo("ivan");
|
||||||
|
assertThat(content.get(0).getImages()).containsExactly("images/cat.png");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Статусы достаются из спецификации, которую сервис отдал в репозиторий: сам SQL
|
||||||
|
* без БД не проверить, а IN(...) собирается ровно из переданного allow-list.
|
||||||
|
*/
|
||||||
|
private Set<PostStatus> statusesUsedByGetPosts() {
|
||||||
|
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of()));
|
||||||
|
service.getPosts(null, null, null, PageRequest.of(0, 20));
|
||||||
|
return capturedStatuses();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<PostStatus> statusesUsedByGetRejectedPosts() {
|
||||||
|
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of()));
|
||||||
|
service.getRejectedPosts(null, null, null, PageRequest.of(0, 20));
|
||||||
|
return capturedStatuses();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Set<PostStatus> capturedStatuses() {
|
||||||
|
ArgumentCaptor<Specification<Post>> specCaptor = ArgumentCaptor.forClass(Specification.class);
|
||||||
|
verify(postRepository).findAll(specCaptor.capture(), any(Pageable.class));
|
||||||
|
|
||||||
|
Set<PostStatus> statuses = EnumSet.noneOf(PostStatus.class);
|
||||||
|
// Hibernate отдаёт из Path.in() объект, который ещё и Predicate, — в тесте так же.
|
||||||
|
Path<Object> path = (Path<Object>) mock(Path.class, withSettings().extraInterfaces(Predicate.class));
|
||||||
|
Expression<Integer> inExpression = (Expression<Integer>) (Expression<?>) path;
|
||||||
|
Root<Post> root = mock(Root.class);
|
||||||
|
// deep stubs: Specification.allOf комбинирует предикаты через CriteriaBuilder.and()
|
||||||
|
CriteriaBuilder cb = mock(CriteriaBuilder.class, RETURNS_DEEP_STUBS);
|
||||||
|
|
||||||
|
when(root.<Object>get(anyString())).thenReturn(path);
|
||||||
|
when(path.in(any(Collection.class))).thenAnswer(invocation -> {
|
||||||
|
statuses.addAll((Collection<PostStatus>) invocation.getArgument(0));
|
||||||
|
return inExpression;
|
||||||
|
});
|
||||||
|
|
||||||
|
specCaptor.getValue().toPredicate(root, mock(CriteriaQuery.class), cb);
|
||||||
|
return statuses;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updatePost_keepsStatusAndInvalidatesCache() {
|
||||||
|
Post post = post(1L, PostStatus.ACTIVE);
|
||||||
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
AdminPostResponse dto = service.updatePost(1L, "FOUND", "Найден кот", "Москва",
|
||||||
|
null, null, "описание", null, "+7", true, "100", List.of(), "[]");
|
||||||
|
|
||||||
|
assertThat(dto.getStatus()).isEqualTo(PostStatus.ACTIVE);
|
||||||
|
assertThat(post.getStatus()).isEqualTo(PostStatus.ACTIVE);
|
||||||
|
assertThat(post.getType()).isEqualTo(PostType.FOUND);
|
||||||
|
assertThat(post.getCity()).isEqualTo("Москва");
|
||||||
|
assertThat(post.getIsReward()).isTrue();
|
||||||
|
verify(postCacheService).invalidatePosts();
|
||||||
|
verify(mapCacheService).clearMapMarkersCache();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updatePost_dropsImagesMissingFromExistingList() {
|
||||||
|
Post post = post(1L, PostStatus.ACTIVE);
|
||||||
|
Image kept = new Image();
|
||||||
|
kept.setUrl("images/keep.png");
|
||||||
|
kept.setPost(post);
|
||||||
|
Image dropped = new Image();
|
||||||
|
dropped.setUrl("images/drop.png");
|
||||||
|
dropped.setPost(post);
|
||||||
|
post.getImages().addAll(List.of(kept, dropped));
|
||||||
|
|
||||||
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
service.updatePost(1L, "LOSS", "Кот", "Москва", null, null, null, null, null,
|
||||||
|
false, null, List.of(), "[\"images/keep.png\"]");
|
||||||
|
|
||||||
|
assertThat(post.getImages()).extracting(Image::getUrl).containsExactly("images/keep.png");
|
||||||
|
verify(fileStorageService).deleteFile("images/drop.png");
|
||||||
|
verify(fileStorageService, never()).deleteFile("images/keep.png");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updatePost_fallsBackToAddressWhenGeocodingUnavailable() {
|
||||||
|
Post post = post(1L, PostStatus.ACTIVE);
|
||||||
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
when(geocodingService.getAddress("55.0", "37.0"))
|
||||||
|
.thenThrow(new ApiException(com.krylov.refound.enums.ErrorCode.INTERNAL_ERROR,
|
||||||
|
"Сервис геокодирования недоступен.", HttpStatus.SERVICE_UNAVAILABLE));
|
||||||
|
|
||||||
|
service.updatePost(1L, "LOSS", "Кот", "Тверь", 55.0, 37.0, null, null, null,
|
||||||
|
false, null, List.of(), "[]");
|
||||||
|
|
||||||
|
assertThat(post.getCity()).isEqualTo("Тверь");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateStatus_closesPostAndIncrementsStatistics() {
|
||||||
|
Post post = post(1L, PostStatus.ACTIVE);
|
||||||
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
AdminPostResponse dto = service.updateStatus(1L, "CLOSED");
|
||||||
|
|
||||||
|
assertThat(dto.getStatus()).isEqualTo(PostStatus.CLOSED);
|
||||||
|
verify(statisticsService).incrementFound();
|
||||||
|
verify(postCacheService).invalidatePosts();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateStatus_reopeningDoesNotTouchStatistics() {
|
||||||
|
Post post = post(1L, PostStatus.CLOSED);
|
||||||
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
AdminPostResponse dto = service.updateStatus(1L, "active");
|
||||||
|
|
||||||
|
assertThat(dto.getStatus()).isEqualTo(PostStatus.ACTIVE);
|
||||||
|
verify(statisticsService, never()).incrementFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateStatus_sameStatusIsNoop() {
|
||||||
|
Post post = post(1L, PostStatus.ACTIVE);
|
||||||
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
|
||||||
|
AdminPostResponse dto = service.updateStatus(1L, "ACTIVE");
|
||||||
|
|
||||||
|
assertThat(dto.getStatus()).isEqualTo(PostStatus.ACTIVE);
|
||||||
|
verify(postRepository, never()).save(any(Post.class));
|
||||||
|
verify(statisticsService, never()).incrementFound();
|
||||||
|
verify(postCacheService, never()).invalidatePosts();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateStatus_rejectsGarbage() {
|
||||||
|
assertThatThrownBy(() -> service.updateStatus(1L, "banana"))
|
||||||
|
.isInstanceOf(ApiException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updatePost_throwsNotFoundForMissingPost() {
|
||||||
|
when(postRepository.findById(99L)).thenReturn(java.util.Optional.empty());
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.updatePost(99L, "LOSS", "t", null, null, null, null, null,
|
||||||
|
null, false, null, List.of(), "[]"))
|
||||||
|
.isInstanceOf(ApiException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deletePost_clearsFilesFavoritesAndChatLinks() {
|
||||||
|
Post post = post(1L, PostStatus.CLOSED);
|
||||||
|
Image image = new Image();
|
||||||
|
image.setUrl("images/cat.png");
|
||||||
|
image.setPost(post);
|
||||||
|
post.getImages().add(image);
|
||||||
|
|
||||||
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
|
||||||
|
service.deletePost(1L);
|
||||||
|
|
||||||
|
verify(fileStorageService).deleteFile("images/cat.png");
|
||||||
|
verify(favoriteRepository).deleteByPostIn(anyList());
|
||||||
|
verify(chatRepository).clearPostReference(1L);
|
||||||
|
verify(postRepository).delete(post);
|
||||||
|
verify(postCacheService).invalidatePosts();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deletePost_doesNotFailWhenFileStorageIsDown() {
|
||||||
|
Post post = post(1L, PostStatus.CLOSED);
|
||||||
|
Image image = new Image();
|
||||||
|
image.setUrl("images/cat.png");
|
||||||
|
image.setPost(post);
|
||||||
|
post.getImages().add(image);
|
||||||
|
|
||||||
|
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
|
||||||
|
org.mockito.Mockito.doThrow(new RuntimeException("MinIO недоступен"))
|
||||||
|
.when(fileStorageService).deleteFile(any());
|
||||||
|
|
||||||
|
service.deletePost(1L);
|
||||||
|
|
||||||
|
verify(postRepository).delete(post);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user