Skip to content

Commit

Permalink
fix dates for trainings
Browse files Browse the repository at this point in the history
  • Loading branch information
Alikohd committed Dec 11, 2024
1 parent e6e0399 commit 273e4b4
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
Expand All @@ -18,13 +16,11 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand All @@ -33,12 +29,10 @@
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
Expand Down Expand Up @@ -122,64 +116,60 @@ public ResponseEntity<ByteArrayResource> exportDatabase() throws IOException, Js
}

@PostMapping("/import")
public ResponseEntity<String> importDatabase(@RequestParam("file") MultipartFile file) throws IOException, StreamReadException, DatabindException, java.io.IOException {
// Создаем экземпляр MongoClient
MongoClient mongoClient = MongoClients.create(uri);

// Получаем экземпляр MongoDatabase
MongoDatabase database = mongoClient.getDatabase(uri.split("/")[uri.split("/").length - 1].split("\\?")[0]);
public ResponseEntity<String> importDatabase(@RequestParam("file") MultipartFile file) throws IOException, StreamReadException, DatabindException {
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase(uri.split("/")[uri.split("/").length - 1].split("\\?")[0]);

MongoIterable<String> collectionNamesToDelete = database.listCollectionNames();
for (String collectionName : collectionNamesToDelete) {
database.getCollection(collectionName).drop();
}
MongoIterable<String> collectionNamesToDelete = database.listCollectionNames();
for (String collectionName : collectionNamesToDelete) {
database.getCollection(collectionName).drop();
}

// Читаем JSON-файл
ObjectMapper mapper = new ObjectMapper();
Map<String, List<Map<String, Object>>> importData = mapper.readValue(file.getInputStream(), Map.class);
ObjectMapper mapper = new ObjectMapper();
Map<String, List<Map<String, Object>>> importData = mapper.readValue(file.getInputStream(), Map.class);

// Заполняем базу данных
for (Map.Entry<String, List<Map<String, Object>>> entry : importData.entrySet()) {
String collectionName = entry.getKey();
List<Map<String, Object>> documents = entry.getValue();
for (Map.Entry<String, List<Map<String, Object>>> entry : importData.entrySet()) {
String collectionName = entry.getKey();
List<Map<String, Object>> documents = entry.getValue();

// Проверяем, существует ли коллекция
MongoIterable<String> collectionNames = database.listCollectionNames();
boolean collectionExists = false;
for (String name : collectionNames) {
if (name.equals(collectionName)) {
collectionExists = true;
break;
MongoCollection<Document> collection = database.getCollection(collectionName);
if (collection == null) {
database.createCollection(collectionName);
collection = database.getCollection(collectionName);
}
}

// Создаем коллекцию, если она не существует
if (!collectionExists) {
database.createCollection(collectionName);
}

// Заполняем коллекцию
MongoCollection<Document> collection = database.getCollection(collectionName);
for (Map<String, Object> document : documents) {
Document doc = new Document();
for (Map.Entry<String, Object> entryDoc : document.entrySet()) {
if (entryDoc.getKey().equals("_id")) {
// Если ключ "_id" существует, устанавливаем его как ObjectId
doc.put(entryDoc.getKey(), new ObjectId((String) entryDoc.getValue()));
} else {
doc.put(entryDoc.getKey(), entryDoc.getValue());
}
for (Map<String, Object> document : documents) {
Document doc = new Document();
for (Map.Entry<String, Object> entryDoc : document.entrySet()) {
if (entryDoc.getKey().equals("_id")) {
doc.put(entryDoc.getKey(), new ObjectId((String) entryDoc.getValue()));
} else {
Object transformedValue = transformValueIfDate(entryDoc.getKey(), entryDoc.getValue());
doc.put(entryDoc.getKey(), transformedValue);
}
}
if (!doc.containsKey("_id")) {
// Если ключ "_id" не существует, устанавливаем его как новый ObjectId
doc.put("_id", new ObjectId());
}
collection.insertOne(doc);
}
}

return ResponseEntity.ok("База данных успешно заполнена");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Ошибка при импорте базы данных: " + e.getMessage());
}
}

// Возвращаем ответ
return ResponseEntity.status(HttpStatus.OK).body("База данных успешно заполнена");
private Object transformValueIfDate(String key, Object value) {
if (value instanceof String) {
try {
LocalDateTime dateTime = LocalDateTime.parse((String) value, DateTimeFormatter.ISO_DATE_TIME);
return dateTime;
} catch (DateTimeParseException e) {
}
}
return value;
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.gym.model.dto.statistics.admin;

import java.time.LocalDate;
import java.time.LocalDateTime;

import com.example.gym.model.client.ClientPojo;
import com.example.gym.model.subscription.SubscriptionStatus;
Expand All @@ -20,9 +21,9 @@ public class SubscriptionDetailDto {

private ClientPojo client;
@Schema(description = "Дата покупки", example = "2023-10-01")
private LocalDate startDate;
private LocalDateTime startDate;
@Schema(description = "Дата окончания", example = "2023-12-01")
private LocalDate endDate;
private LocalDateTime endDate;
@Schema(description = "Статус", enumAsRef = true)
private SubscriptionStatus status;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@ public interface TrainingRepository extends MongoRepository<Training, String> {
@Query("{ 'room.id': ?0 }")
List<Training> findAllByRoomId(String roomId);

@Query("{ 'startTime': { $gte: ?0, $lte: ?1 }, 'endTime': { $lt: ?2 } }")
List<Training> findAllByStartTimeBetweenAndEndTimeBefore(LocalDateTime startTime, LocalDateTime endTime, LocalDateTime now);
@Query("{ 'endTime': { $lt: ?0 }, 'startTime': { $gte: ?1, $lt: ?2 } }")
List<Training> findAllByEndTimeBeforeAndStartTimeBetween(LocalDateTime now, LocalDateTime startTime, LocalDateTime endTime);

@Query("{ 'startTime': { $gte: ?0, $lte: ?1 }, 'endTime': { $lt: ?2 }, 'trainer.id': ?3 }")
@Query("{ 'startTime': { $gte: ?0, $lte: ?1 }, 'endTime': { $lt: ?1 }, 'trainer.id': ?2 }")
List<Training> findAllByStartTimeBetweenAndTrainerIdAndEndTimeBefore(
LocalDateTime startTime, LocalDateTime endTime, LocalDateTime now, String trainerId);
LocalDateTime startTime, LocalDateTime endTime, String trainerId);

@Query("{ 'startTime': { $gte: ?0, $lte: ?1 }, 'endTime': { $lt: ?2 }, 'trainer.id': ?3, 'id': ?4 }")
@Query("{ 'startTime': { $gte: ?0, $lte: ?1 }, 'endTime': { $lt: ?1 }, 'trainer.id': ?2, 'id': ?3 }")
Training findByStartTimeBetweenAndTrainerIdAndIdAndEndTimeBefore(
LocalDateTime startTime, LocalDateTime endTime, LocalDateTime now, String trainerId, String trainingId);
LocalDateTime startTime, LocalDateTime endTime, String trainerId, String trainingId);

@Query("{ 'endTime': { $lt: ?0 }, 'trainer.id': ?1, 'id': ?2 }")
Training findByEndTimeBeforeAndTrainerIdAndId(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ public List<SectionStatistics> getFinishedTrainings(LocalDate startDate, LocalDa
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.plusDays(1).atStartOfDay();

List<Training> trainings = trainingRepository.findAllByStartTimeBetweenAndEndTimeBefore(startDateTime, endDateTime, LocalDateTime.now());
List<Training> trainings = trainingRepository.findAllByEndTimeBeforeAndStartTimeBetween(LocalDateTime.now(), startDateTime, endDateTime);

log.info("Start Date: {}", startDateTime);
log.info("End Date: {}", endDateTime);
Expand Down Expand Up @@ -316,13 +316,9 @@ public PurchasedSubcriptions getPurchasedSubscriptions(
SubscriptionStatus status,
int page,
int size
) {
System.out.println(startDate);
System.out.println(endDate);
) {
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
System.out.println(startDateTime);
System.out.println(endDateTime);
PurchasedSubcriptions purchasedSubcriptions = new PurchasedSubcriptions();
List<User> clients = userRepository.findAllByRoles("ROLE_USER");
List<User> filteredClients = clients.stream()
Expand Down Expand Up @@ -398,7 +394,7 @@ public RoomsActive getRoomsActive(LocalDate startDate, LocalDate endDate) {
List<Room> rooms = roomRepository.findAll();
System.out.println("Количество комнат: " + rooms.size());

List<Training> trainings = trainingRepository.findAllByStartTimeBetweenAndEndTimeBefore(startDateTime, endDateTime, LocalDateTime.now());
List<Training> trainings = trainingRepository.findAllByEndTimeBeforeAndStartTimeBetween(LocalDateTime.now(), startDateTime, endDateTime);
System.out.println("Количество тренировок: " + trainings.size());

System.out.println("Start Date: " + startDateTime);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
Expand Down

0 comments on commit 273e4b4

Please sign in to comment.