Skip to content

Commit

Permalink
Merge pull request #21 from 7th-UMC-Hackathon-TeamV/feat/post
Browse files Browse the repository at this point in the history
Feat/post
  • Loading branch information
chaechaen authored Jan 11, 2025
2 parents 8c5eaed + 0c6902c commit e57ff45
Show file tree
Hide file tree
Showing 8 changed files with 210 additions and 4 deletions.
16 changes: 16 additions & 0 deletions src/main/java/banban/springboot/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package banban.springboot.config;

import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://on-air.netlify.app")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@EnableWebSecurity
@Configuration
Expand All @@ -15,6 +20,7 @@ public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configure(http)) // CORS 설정 추가
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/**").permitAll()
.anyRequest().authenticated()
Expand All @@ -23,4 +29,18 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
return http.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://on-air.netlify.app"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
configuration.setMaxAge(3600L);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

}
3 changes: 1 addition & 2 deletions src/main/java/banban/springboot/domain/entity/News.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ public class News {
@Column(nullable = false)
private boolean isBreakingNews;

@Column(nullable = false)
private LocalDateTime createdAt = LocalDateTime.now();
private LocalDateTime createdAt;

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

Expand All @@ -27,5 +28,8 @@ public interface NewsRepository extends JpaRepository<News,Long> {

// 특정 그룹의 일반 뉴스 조회
List<News> findByTeamGroupAndIsBreakingNewsFalse(TeamGroup teamGroup);

List<News> findByTeamGroupAndCreatedAtBetween(TeamGroup teamGroup, LocalDateTime start, LocalDateTime end);
void deleteByCreatedAtBetween(LocalDateTime start, LocalDateTime end);
}

75 changes: 74 additions & 1 deletion src/main/java/banban/springboot/service/NewsService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,19 @@
import banban.springboot.s3.AmazonS3Manager;
import banban.springboot.s3.Uuid;
import banban.springboot.s3.UuidRepository;
import banban.springboot.web.controller.NewsTestController;
import banban.springboot.web.dto.request.NewsRequestDTO;
import banban.springboot.web.dto.response.NewsResponseDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -57,8 +61,8 @@ public NewsResponseDTO.NewsCreateResponseDTO createNews(String groupKey, Long me
.isBreakingNews(newsRequestDTO.isBreakingNews())
.likes(0)
.newsCategories(newsRequestDTO.getNewsCategories())
.createdAt(newsRequestDTO.getCreatedAt())
.thumbnail_URL(pictureUrl)
.createdAt(getCurrentTime())
.build();

news = newsRepository.save(news);
Expand Down Expand Up @@ -139,4 +143,73 @@ public List<NewsResponseDTO.NewsReadResponseDTO> getRegularNewsByGroupKey(String
.map(NewsResponseDTO.NewsReadResponseDTO::from)
.toList();
}

// private LocalDateTime getCurrentTime() {
// if (isTestMode()) {
// return NewsTestController.getMockCurrentTime();
// }
// return LocalDateTime.now();
// }

// private boolean isTestMode() {
// return Arrays.asList(environment.getActiveProfiles()).contains("test");
// }

private LocalDateTime getCurrentTime() {
return NewsTestController.getMockCurrentTime(); // 항상 테스트 시간 반환
}

public List<NewsResponseDTO.NewsTodayResponseDTO> getTodayNews(String groupKey, Long memberId) {
// 그룹과 멤버 존재 확인
TeamGroup teamGroup = groupRepository.findByGroupKey(groupKey)
.orElseThrow(() -> new GeneralException(ErrorStatus.TEAMGROUP_NOT_FOUND));

Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));

//LocalDateTime now = LocalDateTime.now();
LocalDateTime now = getCurrentTime();
// LocalDateTime startOfDay = now.toLocalDate().atStartOfDay();
LocalDateTime startOfDay = now.minusDays(1).withHour(18).withMinute(0).withSecond(0);
LocalDateTime endOfToday = now.toLocalDate().atTime(17, 59, 59);

List<News> todayNews = newsRepository.findByTeamGroupAndCreatedAtBetween(
teamGroup, startOfDay, endOfToday);

return todayNews.stream()
.map(NewsResponseDTO.NewsTodayResponseDTO::from)
.collect(Collectors.toList());
}

public List<NewsResponseDTO.NewsYesterdayResponseDTO> getYesterdayNews(String groupKey, Long memberId) {
// 그룹과 멤버 존재 확인
TeamGroup teamGroup = groupRepository.findByGroupKey(groupKey)
.orElseThrow(() -> new GeneralException(ErrorStatus.TEAMGROUP_NOT_FOUND));

Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));

//LocalDateTime now = LocalDateTime.now();
LocalDateTime now = getCurrentTime();
LocalDateTime twoYesterdayAt6PM = now.minusDays(1).withHour(00).withMinute(0).withSecond(0);
LocalDateTime yesterdayAt6PM = now.minusDays(1).withHour(17).withMinute(59).withSecond(59);

List<News> yesterdayNews = newsRepository.findByTeamGroupAndCreatedAtBetween(
teamGroup, twoYesterdayAt6PM, yesterdayAt6PM);

return yesterdayNews.stream()
.map(NewsResponseDTO.NewsYesterdayResponseDTO::from)
.collect(Collectors.toList());
}

@Scheduled(cron = "0 0 18 * * *")
@Transactional
public void deleteOldNews() {
LocalDateTime now = getCurrentTime(); // 수정된 부분
// LocalDateTime yesterdayAt6PM = now.minusDays(1)
// .withHour(18).withMinute(0).withSecond(0);
LocalDateTime twoYesterdayAt6PM = now.minusDays(1).withHour(00).withMinute(0).withSecond(0);
LocalDateTime yesterdayAt6PM = now.minusDays(1).withHour(17).withMinute(59).withSecond(59);
newsRepository.deleteByCreatedAtBetween(twoYesterdayAt6PM, yesterdayAt6PM);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package banban.springboot.web.controller;

import banban.springboot.apiPayload.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Tag(name = "뉴스-테스트")
@RestController
@RequiredArgsConstructor
@Validated
@RequestMapping("/api/test")
public class NewsTestController {

private static LocalDateTime mockCurrentTime;

@Operation(summary = "테스트용 현재 시간 설정")
@PostMapping("/set-time")
public ApiResponse<String> setTestTime(
@RequestParam @Parameter(example = "2024-01-02T14:00:00", description = "설정할 시간 (yyyy-MM-dd'T'HH:mm:ss 형식)")
String dateTime) {
mockCurrentTime = LocalDateTime.parse(dateTime);
return ApiResponse.onSuccess("현재 시간이 " + dateTime + "으로 설정되었습니다.");
}

@Operation(summary = "현재 설정된 테스트 시간 조회")
@GetMapping("/current-time")
public ApiResponse<String> getCurrentTestTime() {
return ApiResponse.onSuccess(mockCurrentTime.toString());
}

public static LocalDateTime getMockCurrentTime() {
return mockCurrentTime;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ public class NewsRequestDTO {
@NotNull(message = "긍정인지 부정인지 작성해주세요")
private NewsCategories newsCategories;

private LocalDateTime createdAt = LocalDateTime.now();
//private LocalDateTime createdAt;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import lombok.*;
import org.springframework.web.multipart.MultipartFile;

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


Expand All @@ -20,6 +21,7 @@ public static class NewsCreateResponseDTO {
private String content;
private String images;
private boolean isBreakingNews;
private LocalDateTime createdAt;

public static NewsCreateResponseDTO from(News news) {
return NewsCreateResponseDTO.builder()
Expand All @@ -28,6 +30,7 @@ public static NewsCreateResponseDTO from(News news) {
.content(news.getContent())
.isBreakingNews(news.isBreakingNews())
.images(news.getThumbnail_URL())
.createdAt(news.getCreatedAt())
.build();
}
}
Expand Down Expand Up @@ -56,4 +59,55 @@ public static NewsReadResponseDTO from(News news) {
.build();
}
}


@Getter
@Setter
@NoArgsConstructor
@Builder
@AllArgsConstructor
public static class NewsTodayResponseDTO {
private Long newsId;
private String headline;
private String content;
private boolean isBreakingNews;
private int likes;
private LocalDateTime createdAt;

public static NewsTodayResponseDTO from(News news) {
return NewsTodayResponseDTO.builder()
.newsId(news.getId())
.headline(news.getHeadline())
.content(news.getContent())
.isBreakingNews(news.isBreakingNews())
.likes(news.getLikes())
.createdAt(news.getCreatedAt())
.build();
}
}

@Getter
@Setter
@NoArgsConstructor
@Builder
@AllArgsConstructor
public static class NewsYesterdayResponseDTO {
private Long newsId;
private String headline;
private String content;
private boolean isBreakingNews;
private int likes;
private LocalDateTime createdAt;

public static NewsYesterdayResponseDTO from(News news) {
return NewsYesterdayResponseDTO.builder()
.newsId(news.getId())
.headline(news.getHeadline())
.content(news.getContent())
.isBreakingNews(news.isBreakingNews())
.likes(news.getLikes())
.createdAt(news.getCreatedAt())
.build();
}
}
}

0 comments on commit e57ff45

Please sign in to comment.