Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Be bug#97 #100

Closed
wants to merge 9 commits into from
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ build/

## 서버 설정 정보 ##
!**/src/main/resources/application.yml
!**/src/main/resources/application-dev.yml
src/main/resources/application-dev.yml

### STS ###
.apt_generated
Expand Down
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ dependencies {
implementation 'com.sun.xml.bind:jaxb-impl:4.0.1'
implementation 'com.sun.xml.bind:jaxb-core:4.0.1'
implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359'

implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'commons-io:commons-io:2.6'
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,19 @@ public String saveFile(MultipartFile file) {
}
}

public byte[] loadImage(String path) throws IOException {
String allPath = fileStorageDir +"images"+ path;
log.info(allPath);
File imageFile = new File(allPath);
if (imageFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(imageFile);
byte[] imageBytes = IOUtils.toByteArray(fileInputStream);
fileInputStream.close();
return imageBytes;
} else{
throw new CustomException("이미지가 존재하지 않습니다.", ErrorCode.IMAGE_NOT_FOUND);
}
public byte[] loadFile(String fileName) throws IOException {
String allPath = fileStorageDir + File.separator + fileName;
return readFileBytes(allPath);
}

public MultipartFile sendFile(String dir) {
//todo: 파일 전송
return null;
private byte[] readFileBytes(String filePath) throws IOException {
File file = new File(filePath);
if (file.exists()) {
try (FileInputStream fileInputStream = new FileInputStream(file)) {
return IOUtils.toByteArray(fileInputStream);
}
} else {
throw new CustomException("파일이 존재하지 않습니다.", ErrorCode.FILE_NOT_FOUND);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@ public enum ErrorCode {
ALREADY_APPROVE_PROGRAM(400, "이미 등록된 프로그램입니다."),
ALREADY_EXIST_EMAIL(400, "이미 존재하는 이메일입니다."),
INVALID_PASSWORD(400, "비밀번호가 틀렸습니다."),
INVALID_EMAIL_AUTH(400, "인증번호가 틀렸습니다."),
NOT_PT(400, "PT이용권이 아닙니다."),
NOT_YOUR_TRAINER(400, "예약 가능한 트레이너가 아닙니다."),
ALREADY_RESERVATION(400, "이미 예약 되어있습니다."),



//401
INVALID_ACCESS_TOKEN(401, "ACCESS TOKEN 오류"),
INVALID_REFRESH_TOKEN(401, "REFRESH TOKEN 오류"),
Expand Down
22 changes: 19 additions & 3 deletions src/main/java/com/sideProject/PlanIT/common/util/RedisUtil.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
package com.sideProject.PlanIT.common.util;

import lombok.AllArgsConstructor;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@AllArgsConstructor
@RequiredArgsConstructor
public class RedisUtil {

@Value("${spring.email.redis-timeLimit}")
private Long emailExpire;

@Value("${spring.jwt.refresh-token-expire}")
private Long refreshExpire;

private final RedisTemplate<String, String> redisTemplate;


public void setMailValidation(String email, String validationCode) {
ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
valueOperations.set(email, validationCode, Duration.ofMillis(emailExpire));
}
public void setRefreshToken(String refreshToken, Long member_id)
{
ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
redisTemplate.delete(refreshToken);
valueOperations.set(refreshToken, member_id.toString());
valueOperations.set(refreshToken, member_id.toString(), refreshExpire);
}

public String getData(String key) {
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/sideProject/PlanIT/config/EmailConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.sideProject.PlanIT.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

@Configuration
public class EmailConfig {
@Value("${spring.email.app-key}")
private String appKey;
@Bean
public JavaMailSender mailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("[email protected]");
mailSender.setPassword(appKey);

Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.transport.protocol", "smtp");
javaMailProperties.put("mail.smtp.auth", "true");
javaMailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");//SSL 소켓 팩토리 클래스 사용
javaMailProperties.put("mail.smtp.starttls.enable", "true");//STARTTLS(TLS를 시작하는 명령)를 사용하여 암호화된 통신을 활성화
javaMailProperties.put("mail.debug", "true");//디버깅 정보 출력
javaMailProperties.put("mail.smtp.ssl.trust", "smtp.naver.com");//smtp 서버의 ssl 인증서를 신뢰
javaMailProperties.put("mail.smtp.ssl.protocols", "TLSv1.2");//사용할 ssl 프로토콜 버젼

mailSender.setJavaMailProperties(javaMailProperties);

return mailSender;
}
}
Original file line number Diff line number Diff line change
@@ -1,44 +1,50 @@
package com.sideProject.PlanIT.domain.file.controller;

import com.sideProject.PlanIT.common.response.ApiResponse;
import com.sideProject.PlanIT.domain.file.service.FileService;
import com.sideProject.PlanIT.domain.post.dto.request.NoticeRequestDto;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import com.sideProject.PlanIT.common.modules.FileHandler;
import com.sideProject.PlanIT.common.response.CustomException;
import com.sideProject.PlanIT.common.response.ErrorCode;
import lombok.RequiredArgsConstructor;
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.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {
@Autowired
FileService fileService;
private final FileHandler fileHandler;

@PostMapping
public ApiResponse<String> saveFile(@ModelAttribute NoticeRequestDto noticeRequestDto) {
return ApiResponse.ok(fileService.saveFile(noticeRequestDto.getImage()));
}
@GetMapping("/{file_name:.+}")
public ResponseEntity<?> sendFile(@PathVariable String file_name, HttpServletRequest request) {
Resource resource = fileService.sendFile(file_name);

String contentType = null;
@GetMapping("/image/{image_name}")
public ResponseEntity<byte[]> loadImage(@PathVariable String image_name) {
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
byte[] imageBytes = fileHandler.loadFile(image_name);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);

return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
throw new CustomException(ErrorCode.IMAGE_NOT_FOUND);
}
}

if (contentType == null) {
contentType = "application/octet-stream";
}
@GetMapping("/file/{file_name}")
public ResponseEntity<byte[]> loadFile(@PathVariable String file_name) {
try {
byte[] fileBytes = fileHandler.loadFile(file_name);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file_name);

return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.body(resource);
return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
} catch (IOException e) {
throw new CustomException(ErrorCode.FILE_NOT_FOUND);
}
}
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,23 @@ public ApiResponse<Map<LocalDate, List<ReservationResponse>>> findReservation(
);
}

@GetMapping("/trainer/{employeeId}")
public ApiResponse<Map<LocalDate, List<ReservationResponse>>> findReservationByEmployee(
@RequestParam(value = "date", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
@PathVariable("employeeId") Long employeeId
) {
if (date == null) {
date = LocalDate.now(); // 파라미터가 없을 경우 기본값으로 오늘 날짜를 사용
}
return ApiResponse.ok(
reservationService.findReservationForWeekByEmployee(
date,
employeeId
)
);
}

@DeleteMapping("/{reservationId}")
public ApiResponse<String> cancelReservation(
@PathVariable("reservationId") Long reservationId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ public static ReservationResponse of(Reservation reservation) {
if(reservation.getStatus() == ReservationStatus.POSSIBLE) {
return ReservationResponse.builder()
.id(reservation.getId())
.member(MemberSemiResponseDto.of(reservation.getMember()))
.employee(EmployeeSemiResponseDto.of(reservation.getEmployee()))
.status(reservation.getStatus())
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ public interface ReservationService {
String changeAvailability(List<LocalDateTime> times, Long employeeId, Long userId);
String reservation(Long reservationId, Long userId, Long programId);
Map<LocalDate, List<ReservationResponse>> findReservationForWeekByMember(LocalDate day, Long id);
List<ReservationResponse> findReservationForWeekByEmployee(LocalDate day, Long id);
Map<LocalDate, List<ReservationResponse>> findReservationForWeekByEmployee(LocalDate day, Long id);
String cancel(Long userId, Long reservationId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public String changeAvailability(List<LocalDateTime> reservedTimes, Long employe
// 기존 예약 삭제
List<Reservation> reservedReservations = existingReservations.stream()
.filter(reservation -> reservation.getStatus() == ReservationStatus.POSSIBLE)
.collect(Collectors.toList());
.toList();
reservedReservations.forEach(reservationRepository::delete);

// 새 예약 추가 (기존 예약이 없는 reservedTimes에 대해서만)
Expand Down Expand Up @@ -141,15 +141,26 @@ public Map<LocalDate, List<ReservationResponse>> findReservationForWeekByMember(
reservations = reservationRepository.findByMemberAndDateTimeBetween(member,startOfWeek,endOfWeek);
}

Map<LocalDate, List<ReservationResponse>> reservationMap = reservations.stream()
return reservations.stream()
.map(ReservationResponse::of)
.collect(Collectors.groupingBy(response -> response.getReservationTime().toLocalDate()));
return reservationMap;
}

@Override
public List<ReservationResponse> findReservationForWeekByEmployee(LocalDate date, Long employeeId) {
return List.of(ReservationResponse.builder().build(), ReservationResponse.builder().build());
public Map<LocalDate, List<ReservationResponse>> findReservationForWeekByEmployee(LocalDate date, Long employeeId) {
LocalDateTime startOfWeek = calStartOfWeek(date);
LocalDateTime endOfWeek = calEndOfWeek(date);

List<Reservation> reservations;
//트레이너이면
Employee employee = employeeRepository.findById(employeeId).orElseThrow(() ->
new CustomException("존재하지 않는 트레이너입니다.", ErrorCode.MEMBER_NOT_FOUND)
);
reservations = reservationRepository.findByEmployeeAndDateTimeBetween(employee,startOfWeek,endOfWeek);

return reservations.stream()
.map(ReservationResponse::of)
.collect(Collectors.groupingBy(response -> response.getReservationTime().toLocalDate()));
}

//그 주의 월요일 00:00:00
Expand Down
Loading
Loading