Skip to content

Commit 60491bf

Browse files
committed
feat: 지원자 API 와 구글 스프레드 시트 연동
1 parent 2235282 commit 60491bf

File tree

4 files changed

+103
-17
lines changed

4 files changed

+103
-17
lines changed

src/main/java/dmu/dasom/api/domain/applicant/dto/ApplicantCreateRequestDto.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ public class ApplicantCreateRequestDto {
6161

6262
public Applicant toEntity() {
6363
return Applicant.builder()
64+
.name(this.name)
6465
.studentNo(this.studentNo)
6566
.contact(this.contact)
6667
.email(this.email)

src/main/java/dmu/dasom/api/domain/applicant/service/ApplicantServiceImpl.java

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,28 +46,52 @@ public void apply(final ApplicantCreateRequestDto request) {
4646
throw new CustomException(ErrorCode.DUPLICATED_STUDENT_NO);
4747

4848
// 기존 지원자 정보 갱신 수행
49+
Applicant existingApplicant = applicant.get();
4950
applicant.get().overwrite(request);
51+
52+
// 구글 시트 업데이트를 위한 데이터 구성
53+
List<List<Object>> values = List.of(List.of(
54+
existingApplicant.getId(),
55+
existingApplicant.getName(),
56+
existingApplicant.getStudentNo(),
57+
existingApplicant.getContact(),
58+
existingApplicant.getEmail(),
59+
existingApplicant.getGrade(),
60+
existingApplicant.getReasonForApply(),
61+
existingApplicant.getActivityWish(),
62+
existingApplicant.getIsPrivacyPolicyAgreed(),
63+
existingApplicant.getCreatedAt(),
64+
existingApplicant.getUpdatedAt()
65+
));
66+
67+
// 구글 시트에서 해당 지원자의 행 번호 조회(A열에 저장된 지원자 id 기준)
68+
int rowNumber = googleApiService.findRowByApplicantId(spreadsheetId, "Sheet1", existingApplicant.getId());
69+
70+
// 찾아낸 행 번호에 따라 범위를 지정
71+
String range = "Sheet1!A" + rowNumber + ":K" + rowNumber;
72+
googleApiService.updateSheet(spreadsheetId, range, values);
5073
return;
5174
}
5275

5376
// 새로운 지원자일 경우 저장
54-
Applicant applicant = applicantRepository.save(request.toEntity());
77+
Applicant newApplicant = applicantRepository.save(request.toEntity());
5578

5679
// 스프레드 시트에 기록할 데이터
5780
List<List<Object>> values = List.of(List.of(
58-
applicant.getId(),
59-
applicant.getStudentNo(),
60-
applicant.getContact(),
61-
applicant.getEmail(),
62-
applicant.getGrade(),
63-
applicant.getReasonForApply(),
64-
applicant.getActivityWish(),
65-
applicant.getIsPrivacyPolicyAgreed(),
66-
applicant.getCreatedAt(),
67-
applicant.getUpdatedAt()
81+
newApplicant.getId(),
82+
newApplicant.getName(),
83+
newApplicant.getStudentNo(),
84+
newApplicant.getContact(),
85+
newApplicant.getEmail(),
86+
newApplicant.getGrade(),
87+
newApplicant.getReasonForApply(),
88+
newApplicant.getActivityWish(),
89+
newApplicant.getIsPrivacyPolicyAgreed(),
90+
newApplicant.getCreatedAt(),
91+
newApplicant.getUpdatedAt()
6892
));
6993

70-
String range = "Sheet1!A:J";
94+
String range = "Sheet1!A:K";
7195

7296
googleApiService.writeToSheet(spreadsheetId, range, values);
7397
}

src/main/java/dmu/dasom/api/domain/google/service/GoogleApiService.java

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import java.io.IOException;
2525
import java.nio.charset.StandardCharsets;
2626
import java.security.GeneralSecurityException;
27+
import java.util.Base64;
2728
import java.util.Collections;
2829
import java.util.List;
2930

@@ -34,19 +35,27 @@ public class GoogleApiService {
3435
private static final Logger logger = LoggerFactory.getLogger(GoogleApiService.class);
3536
private static final String APPLICATION_NAME = "Recruit Form";
3637
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
38+
3739
@Value("${google.credentials.json}")
3840
private String credentialsJson;
3941
private Sheets sheetsService;
4042

4143
// Google Sheets API 서비스 객체를 생성하는 메소드
42-
private Sheets getSheetsService() throws IOException, GeneralSecurityException{
43-
if(sheetsService == null){
44+
private Sheets getSheetsService() throws IOException, GeneralSecurityException {
45+
if (sheetsService == null) {
46+
byte[] decodedBytes = Base64.getDecoder().decode(credentialsJson);
47+
String credentialsJson = new String(decodedBytes, StandardCharsets.UTF_8);
48+
49+
System.out.println(credentialsJson); // 디코딩된 JSON 출력
50+
4451
ByteArrayInputStream credentialsStream = new ByteArrayInputStream(credentialsJson.getBytes(StandardCharsets.UTF_8));
45-
GoogleCredentials credentials = GoogleCredentials
46-
.fromStream(credentialsStream)
52+
53+
GoogleCredentials credentials = GoogleCredentials.fromStream(credentialsStream)
4754
.createScoped(Collections.singletonList("https://www.googleapis.com/auth/spreadsheets"));
4855

49-
sheetsService = new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, new HttpCredentialsAdapter(credentials))
56+
sheetsService = new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(),
57+
JSON_FACTORY,
58+
new HttpCredentialsAdapter(credentials))
5059
.setApplicationName(APPLICATION_NAME)
5160
.build();
5261
}
@@ -72,4 +81,44 @@ public void writeToSheet(String spreadsheetId, String range, List<List<Object>>
7281
}
7382
}
7483

84+
// 지원자 ID를 기준으로 행번호 찾기
85+
public int findRowByApplicantId(String spreadsheetId, String sheetName, Long applicantId) {
86+
try {
87+
Sheets service = getSheetsService();
88+
String range = sheetName + "!A:A";
89+
ValueRange response = service.spreadsheets().values()
90+
.get(spreadsheetId, range)
91+
.execute();
92+
List<List<Object>> values = response.getValues();
93+
if (values != null) {
94+
for (int i = 0; i < values.size(); i++) {
95+
List<Object> row = values.get(i);
96+
if (!row.isEmpty() && row.get(0).toString().equals(applicantId.toString())) {
97+
return i + 1;
98+
}
99+
}
100+
}
101+
return values == null ? 1 : values.size() + 1;
102+
} catch (IOException | GeneralSecurityException e) {
103+
logger.error("Failed to find row by applicant id", e);
104+
throw new CustomException(ErrorCode.INTERNAL_SERVER_ERROR);
105+
}
106+
}
107+
108+
109+
public void updateSheet(String spreadsheetId, String range, List<List<Object>> values) {
110+
try {
111+
Sheets service = getSheetsService();
112+
ValueRange body = new ValueRange().setValues(values);
113+
UpdateValuesResponse response = service.spreadsheets().values()
114+
.update(spreadsheetId, range, body)
115+
.setValueInputOption("USER_ENTERED")
116+
.execute();
117+
logger.info("Updated rows: {}", response.getUpdatedRows());
118+
} catch (IOException | GeneralSecurityException e) {
119+
logger.error("Failed to update data in the spreadsheet", e);
120+
throw new CustomException(ErrorCode.WRITE_FAIL);
121+
}
122+
}
123+
75124
}

src/main/resources/application-credentials.yml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,18 @@ spring:
1515
redis:
1616
host: ${REDIS_HOST}
1717
port: ${REDIS_PORT}
18+
mail:
19+
host: ${MAIL_HOST}
20+
port: ${MAIL_PORT}
21+
username: ${MAIL_USERNAME}
22+
password: ${MAIL_PASSWORD}
23+
properties:
24+
mail:
25+
smtp:
26+
auth: true
27+
starttls:
28+
enable: true
29+
required: true
1830
jwt:
1931
secret: ${JWT_SECRET}
2032
access-token-expiration: ${JWT_ACCESS_TOKEN_EXPIRATION}

0 commit comments

Comments
 (0)