Skip to content

Commit

Permalink
add collections
Browse files Browse the repository at this point in the history
  • Loading branch information
AlinaMoon123 committed Dec 1, 2024
1 parent 0bdfcbe commit bc731dd
Show file tree
Hide file tree
Showing 13 changed files with 16,903 additions and 69 deletions.
16,630 changes: 16,630 additions & 0 deletions lake-catalog/records.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@

import jakarta.servlet.http.HttpSession;
import com.example.lake_catalog.model.*;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;

@Controller
public class AuthController {
Expand Down Expand Up @@ -51,39 +56,63 @@ public String mainPage() {

// Обработка формы входа
@PostMapping("/perform_login")
public String performLogin(String email, String password, HttpSession session) {
public String performLogin(String email, String password, HttpSession session, Model model) {
if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
model.addAttribute("error", "Введите email и пароль.");
return "login/login"; // Вернуть страницу входа с сообщением об ошибке
}

try {
User user = authService.loginUser(email, password);
session.setAttribute("currentUser", user);
System.out.println("Пользователь вошел: " + user.getEmail());
return "redirect:/lakes/main"; // Редирект на страницу озёр после успешного входа
return "redirect:/lakes/main"; // Редирект при успешном входе
} catch (RuntimeException e) {
return "redirect:/login?error"; // Переход обратно на страницу входа с ошибкой
model.addAttribute("error", e.getMessage()); // Передача текста ошибки в шаблон
return "login/login"; // Вернуть страницу входа
}
}


// Обработка формы регистрации
@PostMapping("/perform_register")
public String performRegister(String username, String email, String password, String confirm, HttpSession session) {
public String performRegister(String username, String email, String password, String confirm, HttpSession session, Model model) {
if (username == null || username.isEmpty() || email == null || email.isEmpty() ||
password == null || password.isEmpty() || confirm == null || confirm.isEmpty()) {
model.addAttribute("error", "Заполните все поля.");
return "register/register"; // Вернуть страницу регистрации с сообщением об ошибке
}

if (!password.equals(confirm)) {
return "redirect:/register?error=password_mismatch";
model.addAttribute("error", "Пароли не совпадают.");
return "register/register";
}

try {
authService.registerUser(username, email, password);
User user = authService.loginUser(email, password); // Автоматический вход после регистрации
User user = authService.loginUser(email, password); // Автоматический вход
session.setAttribute("currentUser", user);
System.out.println("Новый пользователь зарегистрирован: " + user.getEmail());
return "redirect:/lakes/main";
} catch (RuntimeException e) {
return "redirect:/register?error=password_mismatch";
model.addAttribute("error", e.getMessage()); // Передача текста ошибки в шаблон
return "register/register";
}
}


// Выход из профиля
@GetMapping("/logout")
public String logout(HttpSession session) {
session.invalidate(); // Уничтожение текущей сессии
return "redirect:/"; // Перенаправление на главную страницу после выхода
}

@GetMapping("/check-auth")
@ResponseBody
public Map<String, Boolean> checkAuth(HttpSession session) {
User currentUser = (User) session.getAttribute("currentUser");
return Map.of("authenticated", currentUser != null);
}

}
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// LakeController.java
package com.example.lake_catalog.controller;

import com.example.lake_catalog.model.Lake;
import com.example.lake_catalog.model.Review;
import com.example.lake_catalog.service.LakeService;
import com.example.lake_catalog.service.UserService;

import jakarta.servlet.http.HttpSession;

Expand All @@ -23,13 +22,17 @@
import com.example.lake_catalog.model.*;
import java.net.URI;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/lakes")
public class LakeController {

private final LakeService lakeService;

@Autowired
private UserService userService;

@Autowired
public LakeController(LakeService lakeService) {
this.lakeService = lakeService;
Expand Down Expand Up @@ -81,6 +84,40 @@ public String showLakeDetails(@PathVariable("id") Long id, Model model) {
}
}

@PostMapping("/{lakeId}/action")
public ResponseEntity<?> handleLakeAction(@PathVariable Long lakeId, @RequestBody Map<String, String> request, HttpSession session) {
User currentUser = (User) session.getAttribute("currentUser");
if (currentUser == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("message", "Вы не авторизованы."));
}

String action = request.get("action");
Optional<Lake> optionalLake = lakeService.findLakeById(lakeId);

if (optionalLake.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("message", "Озеро не найдено."));
}

Lake lake = optionalLake.get();

switch (action) {
case "want_visit":
userService.addWantVisitLake(currentUser, lake);
return ResponseEntity.ok(Map.of("message", "Добавлено в 'Хочу посетить'."));
case "remove_want_visit":
userService.removeWantVisitLake(currentUser, lake);
return ResponseEntity.ok(Map.of("message", "Удалено из 'Хочу посетить'."));
case "visited":
userService.addVisitedLake(currentUser, lake);
return ResponseEntity.ok(Map.of("message", "Добавлено в 'Уже посетил'."));
case "remove_visited":
userService.removeVisitedLake(currentUser, lake);
return ResponseEntity.ok(Map.of("message", "Удалено из 'Уже посетил'."));
default:
return ResponseEntity.badRequest().body(Map.of("message", "Неизвестное действие."));
}
}


@GetMapping()
public List<Lake> getAllLakes() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import jakarta.servlet.http.HttpSession;

import java.net.URI;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -49,7 +50,9 @@ public String getUserProfile(@PathVariable Long userId, Model model) {
User user = userOptional.get();
model.addAttribute("user", user);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.forLanguageTag("ru"));
String formattedDate = user.getCreationDate().format(formatter);
LocalDate creationDate = user.getCreationDate();
String formattedDate = (creationDate != null) ? creationDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) : "Дата не указана";

model.addAttribute("formattedDate", formattedDate);

//Lake lakePage = lakeService.getLakePageByUserId(userId); // Например, метод для получения lakePage
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import org.springframework.data.annotation.Id;
import org.springframework.data.neo4j.core.schema.GeneratedValue;
import org.springframework.data.neo4j.core.schema.Node;
import org.springframework.data.neo4j.core.schema.Relationship;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Node
public class User {
Expand All @@ -19,6 +21,12 @@ public class User {
private LocalDate creationDate;
private LocalDateTime editDate;

@Relationship(type = "WANT_VISIT", direction = Relationship.Direction.OUTGOING)
private List<Lake> wantVisitLakes;

@Relationship(type = "VISITED", direction = Relationship.Direction.OUTGOING)
private List<Lake> visitedLakes;

public User(){

}
Expand All @@ -34,6 +42,23 @@ public User(Long id, String email, String password, String nickname, String phot
}

// Геттеры и сеттеры
public List<Lake> getWantVisitLakes() {
return wantVisitLakes;
}

public void setWantVisitLakes(List<Lake> wantVisitLakes) {
this.wantVisitLakes = wantVisitLakes;
}

public List<Lake> getVisitedLakes() {
return visitedLakes;
}

public void setVisitedLakes(List<Lake> visitedLakes) {
this.visitedLakes = visitedLakes;
}


public Long getId() {
return id;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ public void registerUser(String nickname, String email, String password) {
public User loginUser(String email, String password){
System.out.println(email);
System.out.println(password);
if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
throw new RuntimeException("Введите email и пароль.");
}
Optional<User> optionalUser = userService.findUserByEmail(email);
if (optionalUser.isEmpty())
throw new RuntimeException("Пользователя с такой почтой не существует!");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ public Review addReview(Long lakeId, Long userId, String text, Integer rating) {
review.setStars(rating);
review.setMessage(text);
review.setDate(LocalDate.now());

updateLakeRating(lake);
return reviewRepository.save(review);
//updateLakeRating(lake);

}

public List<Review> getReviewsForLake(Long lakeId) {
Expand All @@ -60,15 +60,19 @@ public List<Review> getReviewsForLake(Long lakeId) {
return reviews;
}

private void updateLakeRating(Lake lake) {
// Получаем все отзывы для озера
List<Review> reviews = reviewRepository.findByLakeId(lake.getId());

// Считаем средний рейтинг
double averageRating = reviews.stream()
.mapToInt(Review::getStars)
.average()
.orElse(0.0);

// Обновляем рейтинг озера
lake.setRating(averageRating);
lakeRepository.save(lake);
}


// private void updateLakeRating(Lake lake) {
// double averageRating = lake.getReviews().stream()
// .mapToInt(Review::getStars)
// .average()
// .orElse(0);

// lake.setRating(averageRating);
// lakeRepository.save(lake);
// }
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.lake_catalog.service;

import com.example.lake_catalog.model.Lake;
import com.example.lake_catalog.model.User;
import com.example.lake_catalog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -24,4 +25,43 @@ public Optional<User> findUserById(Long id) {
return userRepository.findById(id);
}

public void addWantVisitLake(Long userId, Lake lake) {
Optional<User> userOptional = userRepository.findById(userId);
if (userOptional.isPresent()) {
User user = userOptional.get();
user.getWantVisitLakes().add(lake);
userRepository.save(user);
}
}

public void addVisitedLake(Long userId, Lake lake) {
Optional<User> userOptional = userRepository.findById(userId);
if (userOptional.isPresent()) {
User user = userOptional.get();
user.getVisitedLakes().add(lake);
userRepository.save(user);
}
}

public void addWantVisitLake(User user, Lake lake) {
user.getWantVisitLakes().add(lake);
userRepository.save(user);
}

public void removeWantVisitLake(User user, Lake lake) {
user.getWantVisitLakes().remove(lake);
userRepository.save(user);
}

public void addVisitedLake(User user, Lake lake) {
user.getVisitedLakes().add(lake);
userRepository.save(user);
}

public void removeVisitedLake(User user, Lake lake) {
user.getVisitedLakes().remove(lake);
userRepository.save(user);
}


}
Loading

0 comments on commit bc731dd

Please sign in to comment.