start backend

This commit is contained in:
SlimusMinus
2026-03-26 00:21:30 +03:00
parent 611b1c82ad
commit 263242e469
56 changed files with 1524 additions and 23 deletions

View File

@@ -0,0 +1,79 @@
package com.krylov.refound.service;
import com.krylov.refound.entity.Favorite;
import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.FavoriteRepository;
import com.krylov.refound.repository.PostRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class FavoriteService {
private final FavoriteRepository repository;
private final PostRepository postRepository;
private final UserService userService;
public void addToFavorites(Long postId) {
User user = userService.getCurrentUser();
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND));
if (repository.existsByUserAndPost(user, post)) {
return; // уже есть
}
Favorite favorite = new Favorite();
favorite.setUser(user);
favorite.setPost(post);
repository.save(favorite);
}
public void removeFromFavorites(Long postId) {
User user = userService.getCurrentUser();
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND));
repository.deleteByUserAndPost(user, post);
}
public List<Post> getFavorites() {
User user = userService.getCurrentUser();
return repository.findByUser(user)
.stream()
.map(Favorite::getPost)
.toList();
}
public void toggle(Long postId) {
User user = userService.getCurrentUser();
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(
ErrorCode.NOT_FOUND,
"Post not found",
HttpStatus.NOT_FOUND
));
if (repository.existsByUserAndPost(user, post)) {
repository.deleteByUserAndPost(user, post);
} else {
Favorite f = new Favorite();
f.setUser(user);
f.setPost(post);
repository.save(f);
}
}
}

View File

@@ -0,0 +1,42 @@
package com.krylov.refound.service;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class FileStorageService {
@Value("${file.upload-dir}")
private String uploadDir;
public String save(MultipartFile file) {
try {
if (file.isEmpty()) {
throw new RuntimeException("File is empty");
}
String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
Path path = Paths.get(uploadDir).toAbsolutePath().normalize();
Files.createDirectories(path);
Path target = path.resolve(fileName);
Files.copy(file.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
return "/files/" + fileName; // URL
} catch (IOException e) {
throw new ApiException(ErrorCode.BAD_REQUEST, "Only image files are allowed", HttpStatus.BAD_REQUEST);
}
}
}

View File

@@ -0,0 +1,58 @@
package com.krylov.refound.service;
import com.krylov.refound.dto.DialogResponse;
import com.krylov.refound.entity.Message;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.MessageRepository;
import com.krylov.refound.repository.UserRepository;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class MessageService {
private final MessageRepository repository;
private final UserRepository userRepository;
private final UserService userService;
public Message send(Long receiverId, String content) {
User sender = userService.getCurrentUser();
User receiver = userRepository.findById(receiverId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
Message message = new Message();
message.setSender(sender);
message.setReceiver(receiver);
message.setContent(content);
message.setCreatedAt(LocalDateTime.now());
message.setRead(false);
return repository.save(message);
}
public List<Message> getChat(Long userId) {
User current = userService.getCurrentUser();
return repository.findChat(current.getId(), userId);
}
public List<DialogResponse> getDialogs() {
User current = userService.getCurrentUser();
return repository.findDialogsWithUnread(current.getId());
}
@Transactional
public void markAsRead(Long otherUserId) {
User current = userService.getCurrentUser();
repository.markAsRead(current.getId(), otherUserId);
}
}

View File

@@ -1,4 +1,149 @@
package com.krylov.refound.service;
import com.krylov.refound.dto.PostFilter;
import com.krylov.refound.dto.PostRequest;
import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.entity.Image;
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.FavoriteRepository;
import com.krylov.refound.repository.ImageRepository;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.util.PostSpecification;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository repository;
private final ImageRepository imageRepository;
private final FileStorageService storageService;
private final PostMapper mapper;
private final UserService userService;
private final FavoriteRepository favoriteRepository;
@CacheEvict(value = "posts", allEntries = true)
public PostResponse create(PostRequest request, List<MultipartFile> files) {
User user = userService.getCurrentUser();
Post post = mapper.toEntity(request);
post.setCreatedAt(LocalDateTime.now());
post.setStatus(PostStatus.ACTIVE);
post.setUser(user);
Post savedPost = repository.save(post);
if (files != null) {
for (MultipartFile file : files) {
String url = storageService.save(file);
Image image = new Image();
image.setUrl(url);
image.setPost(savedPost);
imageRepository.save(image);
}
}
return mapper.toResponse(savedPost);
}
@Cacheable(value = "posts", key = "#filter.toString() + '_' + #pageable.pageNumber")
public Page<PostResponse> getFeed(PostFilter filter, Pageable pageable) {
User user = userService.getCurrentUser();
Page<Post> posts;
if (filter.getLat() != null) {
posts = repository.searchWithGeo(
filter.getType() != null ? filter.getType().name() : null,
filter.getCity(),
filter.getCategory(),
filter.getLat(),
filter.getLng(),
filter.getRadius(),
pageable
);
} else {
posts = repository.findAll(PostSpecification.withFilter(filter), pageable);
}
// 🔥 собираем id всех постов
List<Long> postIds = posts.getContent()
.stream()
.map(Post::getId)
.toList();
// 🔥 одним запросом получаем избранные
Set<Long> favoriteIds = new HashSet<>(
favoriteRepository.findFavoritePostIds(user.getId(), postIds)
);
return posts.map(post -> {
PostResponse response = mapper.toResponse(post);
response.setFavorite(favoriteIds.contains(post.getId()));
return response;
});
}
@Cacheable(value = "post", key = "#id")
public PostResponse getById(Long id) {
Post post = repository.findById(id)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND));
return mapper.toResponse(post);
}
@CacheEvict(value = {"posts", "post"}, allEntries = true)
public PostResponse update(Long id, PostRequest request) {
Post post = repository.findById(id)
.orElseThrow(() -> new ApiException(
ErrorCode.NOT_FOUND,
"Post not found",
HttpStatus.NOT_FOUND
));
post.setTitle(request.getTitle());
post.setDescription(request.getDescription());
post.setCategory(request.getCategory());
post.setCity(request.getCity());
post.setDistrict(request.getDistrict());
post.setType(request.getType());
Post updated = repository.save(post);
return mapper.toResponse(updated);
}
@CacheEvict(value = {"posts", "post"}, allEntries = true)
public void delete(Long id) {
Post post = repository.findById(id)
.orElseThrow(() -> new ApiException(
ErrorCode.NOT_FOUND,
"Post not found",
HttpStatus.NOT_FOUND
));
repository.delete(post);
}
}

View File

@@ -1,4 +1,27 @@
package com.krylov.refound.service;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.UserRepository;
import com.krylov.refound.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository repository;
public User getCurrentUser() {
String email = SecurityUtils.getCurrentUserEmail();
return repository.findByEmail(email)
.orElseThrow(() -> new ApiException(
ErrorCode.NOT_FOUND,
"User not found",
HttpStatus.NOT_FOUND
));
}
}

View File

@@ -1,4 +1,4 @@
package com.krylov.refound.service;
package com.krylov.refound.service.security;
import com.krylov.refound.dto.AuthRequest;
import com.krylov.refound.dto.AuthResponse;

View File

@@ -1,4 +1,4 @@
package com.krylov.refound.service;
package com.krylov.refound.service.security;
import com.krylov.refound.entity.User;
import com.krylov.refound.repository.UserRepository;

View File

@@ -1,4 +1,4 @@
package com.krylov.refound.service;
package com.krylov.refound.service.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;

View File

@@ -1,4 +1,4 @@
package com.krylov.refound.service;
package com.krylov.refound.service.security;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;