Skip to content

Commit

Permalink
✨ [FEAT] 봉사활동 주민번호 포함되도록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
20210815 committed Dec 2, 2024
1 parent 5285f6f commit afc5049
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
@Setter
@Builder
public class VolunteerListDTO {
private String identity;
private String username;
private String userId;
private String volunteerSessionsId;
//유저타입도 따로
private String date;
private Integer volunteerHours;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
@Setter
@Builder
public class volunteerDTO {
private String volunteerSessionId;
private String identity;
private String username;
private Integer volunteerHours;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,12 @@ public void createVolunteerSession(volunteerDTO volunteer) throws Exception {
String userAddress = credentials.getAddress(); // 개인키에서 주소를 추출

// 봉사 세션 생성
// 세션 id를 통해서 volunteer 가져올 수 있음
Function function = new Function(
"createVolunteerSession",
Arrays.asList(
new Utf8String(user.getIdentity()),
new Utf8String(volunteer.getUsername()),
new Utf8String(user.getId().toString()), // userId
new Utf8String(volunteer.getVolunteerSessionId()), //volunteer 세선 ID
new Uint256(BigInteger.valueOf(volunteer.getVolunteerHours())),
new Utf8String(volunteer.getDate().toString()),
new Utf8String(volunteer.getVolunteerType()),
Expand All @@ -112,7 +113,7 @@ public List<VolunteerListDTO> getVolunteerSessionsByUserId(String userId) {

Function function = new Function(
"getVolunteerSessionsByUserId",
List.of(new Utf8String(user.getIdentity())), // 함수 입력값
List.of(new Utf8String(user.getId().toString())), // userId를 통해서 가져올 수 있도록
List.of(
new TypeReference<DynamicArray<Utf8String>>() {}, // userIds
new TypeReference<DynamicArray<Utf8String>>() {}, // usernames
Expand Down Expand Up @@ -142,23 +143,23 @@ public List<VolunteerListDTO> getVolunteerSessionsByUserId(String userId) {


// 각각의 배열 추출
DynamicArray<Utf8String> userIdentities = (DynamicArray<Utf8String>) decoded.get(0);
DynamicArray<Utf8String> usernames = (DynamicArray<Utf8String>) decoded.get(1);
DynamicArray<Utf8String> userIds = (DynamicArray<Utf8String>) decoded.get(0);
DynamicArray<Utf8String> volunteerSessions = (DynamicArray<Utf8String>) decoded.get(1);
DynamicArray<Uint256> volunteerHours = (DynamicArray<Uint256>) decoded.get(2);
DynamicArray<Utf8String> dates = (DynamicArray<Utf8String>) decoded.get(3);
DynamicArray<Utf8String> volunteerTypes = (DynamicArray<Utf8String>) decoded.get(4);
DynamicArray<Address> userAddresses = (DynamicArray<Address>) decoded.get(5);

System.out.println(userIdentities.getValue());
if (userIdentities.getValue().isEmpty()) {
System.out.println(userIds.getValue());
if (userIds.getValue().isEmpty()) {
throw new ListEmptyException("비었음");
}
// VolunteerListDTO 리스트 생성
List<VolunteerListDTO> sessions = new ArrayList<>();
for (int i = 0; i < userIdentities.getValue().size(); i++) {
for (int i = 0; i < userIds.getValue().size(); i++) {
VolunteerListDTO dto = VolunteerListDTO.builder().build();
dto.setIdentity(userIdentities.getValue().get(i).getValue());
dto.setUsername(usernames.getValue().get(i).getValue());
dto.setUserId(userIds.getValue().get(i).getValue());
dto.setVolunteerSessionsId(volunteerSessions.getValue().get(i).getValue());
dto.setVolunteerHours(volunteerHours.getValue().get(i).getValue().intValue());
dto.setDate(dates.getValue().get(i).getValue());
dto.setVolunteerType(volunteerTypes.getValue().get(i).getValue());
Expand Down Expand Up @@ -228,6 +229,9 @@ public CertificateDTO issueCertificate(String certificateId, String userId) thro
throw new RuntimeException("Failed to retrieve certificate details.");
}

//발급 즉시 인증으로 확인
user.updateCertificateCheck();

// 반환 데이터 매핑
return CertificateDTO.builder()
.certificateId(getDecoded.get(0).getValue().toString())
Expand Down Expand Up @@ -328,11 +332,11 @@ public CertificateDTO getCertificateById(String certificateId) throws Exception
}


public int calculateTotalVolunteerHours(String identity) {
public int calculateTotalVolunteerHours(String userId) {
// Solidity 함수 호출을 위한 Function 객체 생성
Function function = new Function(
"calculateTotalVolunteerHours",
Collections.singletonList(new Utf8String(identity)), // 사용자 주민번호
Collections.singletonList(new Utf8String(userId)), // 사용자 id
Collections.singletonList(new TypeReference<Uint256>() {
}) // 반환값: 총 봉사 시간
);
Expand Down Expand Up @@ -373,7 +377,7 @@ public List<VolunteerListDTO> getVolunteerSessionsByUserIdAndType(String volunte
// Solidity 함수 정의
Function function = new Function(
"getVolunteerSessionsByUserIdAndType",
Arrays.asList(new Utf8String(user_volunteer.getIdentity()), new Utf8String(userType.name())),
Arrays.asList(new Utf8String(userId), new Utf8String(userType.name())),
List.of(
new TypeReference<DynamicArray<Utf8String>>() {
}, // userIds
Expand Down Expand Up @@ -416,8 +420,8 @@ public List<VolunteerListDTO> getVolunteerSessionsByUserIdAndType(String volunte
log.info("Decoded Result: {}", decoded);

// 디코딩된 각 배열
DynamicArray<Utf8String> userIdentities = (DynamicArray<Utf8String>) decoded.get(0);
DynamicArray<Utf8String> usernames = (DynamicArray<Utf8String>) decoded.get(1);
DynamicArray<Utf8String> userIds = (DynamicArray<Utf8String>) decoded.get(0);
DynamicArray<Utf8String> volunteerSessions = (DynamicArray<Utf8String>) decoded.get(1);
DynamicArray<Uint256> volunteerHours = (DynamicArray<Uint256>) decoded.get(2);
DynamicArray<Utf8String> dates = (DynamicArray<Utf8String>) decoded.get(3);
DynamicArray<Address> userAddresses = (DynamicArray<Address>) decoded.get(4);
Expand All @@ -428,19 +432,19 @@ public List<VolunteerListDTO> getVolunteerSessionsByUserIdAndType(String volunte
// }

// 배열 크기 확인
if (userIdentities.getValue().size() != usernames.getValue().size()
|| usernames.getValue().size() != volunteerHours.getValue().size()
if (userIds.getValue().size() != volunteerSessions.getValue().size()
|| volunteerSessions.getValue().size() != volunteerHours.getValue().size()
|| volunteerHours.getValue().size() != dates.getValue().size()
|| dates.getValue().size() != userAddresses.getValue().size()) {
throw new RuntimeException("Mismatched array sizes in Solidity response");
}

// 결과 매핑
List<VolunteerListDTO> sessions = new ArrayList<>();
for (int i = 0; i < userIdentities.getValue().size(); i++) {
for (int i = 0; i < userIds.getValue().size(); i++) {
sessions.add(VolunteerListDTO.builder()
.identity(userIdentities.getValue().get(i).getValue())
.username(usernames.getValue().get(i).getValue())
.userId(userIds.getValue().get(i).getValue())
.volunteerSessionsId(volunteerSessions.getValue().get(i).getValue())
.volunteerHours(volunteerHours.getValue().get(i).getValue().intValue())
.date(dates.getValue().get(i).getValue())
.volunteerType(userType.name())
Expand Down Expand Up @@ -577,6 +581,7 @@ else if (volunteer.getVolunteer().getUserType().equals(UserType.CARE_WORKER) &&
}

createVolunteerSession(volunteerDTO.builder()
.volunteerSessionId(volunteer.getId().toString())
.identity(volunteer.getVolunteer().getIdentity())
.username(volunteer.getVolunteer().getUsername())
.date(volunteer.getDate().toString())
Expand All @@ -585,6 +590,5 @@ else if (volunteer.getVolunteer().getUserType().equals(UserType.CARE_WORKER) &&
.build());
}


}

151 changes: 78 additions & 73 deletions src/main/java/com/carely/backend/service/ocr/OCRService.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,79 +34,84 @@ public class OCRService {
@Value("${google.vision.api-key}")
private String apiKey;

@Transactional
public CertificateDTO extractTextAlreadyUser(MultipartFile imageFile, String kakaoId) throws Exception {
// 유저 확인
User user = userRepository.findByKakaoId(kakaoId)
.orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다."));

// 이미지 파일을 Base64로 인코딩
byte[] imageBytes = imageFile.getBytes();
String base64Image = Base64.getEncoder().encodeToString(imageBytes);

// Google Vision API URL
String visionApiUrl = "https://vision.googleapis.com/v1/images:annotate?key=" + apiKey;

// 요청 본문 생성
JSONObject image = new JSONObject();
image.put("content", base64Image);

JSONObject feature = new JSONObject();
feature.put("type", "TEXT_DETECTION");

JSONObject request = new JSONObject();
request.put("image", image);
request.put("features", new JSONArray().put(feature));

JSONObject requestBody = new JSONObject();
requestBody.put("requests", new JSONArray().put(request));

// HTTP 요청 전송
URL url = new URL(visionApiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setDoOutput(true);

try (OutputStream os = connection.getOutputStream()) {
os.write(requestBody.toString().getBytes("UTF-8"));
}

// 응답 처리
InputStream responseStream = connection.getInputStream();
byte[] responseBytes = responseStream.readAllBytes();
String jsonResponse = new String(responseBytes, "UTF-8");

// JSON에서 텍스트 추출
String extractedText = parseResponse(jsonResponse);
System.out.println(extractedText);
// 텍스트에서 필요한 정보 추출
OCRResponseDto ocrResponseDto = extractFieldsUsingKeywords(extractedText);
System.out.println(ocrResponseDto.getName());

// 생년 월 일 분리
String extractedYear = ocrResponseDto.getBirth().substring(0, 4); // "1987"
String extractedMonth = ocrResponseDto.getBirth().substring(6, 8); // "05"
String extractedDay = ocrResponseDto.getBirth().substring(10, 12); // "23"

//OCR 정보와 현재 유저 정보가 일치하는지 확인
if (ocrResponseDto.getName().equals(user.getUsername()) && extractedYear.equals(user.getBirthyear()) && extractedMonth.equals(user.getBirthmonth()) && extractedDay.equals(user.getBirthday())) {
// 자격증 인증 서비스 호출
CertificateDTO certificateDTO = certificateService.getCertificateById(ocrResponseDto.getCertificateNum());

// 자격증에 적힌 정보와 OCR과 동일한지 확인
if (Objects.equals(certificateDTO.getCertificateId(), ocrResponseDto.getCertificateNum()) && Objects.equals(certificateDTO.getUsername(), ocrResponseDto.getName()) && Objects.equals(certificateDTO.getUserId(), user.getId().toString())) {
// 자격증 검증 성공
user.updateCertificateCheck();
return certificateDTO;
}

}
else {
throw new UserNotMatchException("유저 안 맞음");
}
return null;
}
// @Transactional
// public CertificateDTO extractTextAlreadyUser(MultipartFile imageFile, String kakaoId) throws Exception {
// // 유저 확인
// User user = userRepository.findByKakaoId(kakaoId)
// .orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다."));
//
// // 이미지 파일을 Base64로 인코딩
// byte[] imageBytes = imageFile.getBytes();
// String base64Image = Base64.getEncoder().encodeToString(imageBytes);
//
// // Google Vision API URL
// String visionApiUrl = "https://vision.googleapis.com/v1/images:annotate?key=" + apiKey;
//
// // 요청 본문 생성
// JSONObject image = new JSONObject();
// image.put("content", base64Image);
//
// JSONObject feature = new JSONObject();
// feature.put("type", "TEXT_DETECTION");
//
// JSONObject request = new JSONObject();
// request.put("image", image);
// request.put("features", new JSONArray().put(feature));
//
// JSONObject requestBody = new JSONObject();
// requestBody.put("requests", new JSONArray().put(request));
//
// // HTTP 요청 전송
// URL url = new URL(visionApiUrl);
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// connection.setDoOutput(true);
//
// try (OutputStream os = connection.getOutputStream()) {
// os.write(requestBody.toString().getBytes("UTF-8"));
// }
//
// // 응답 처리
// InputStream responseStream = connection.getInputStream();
// byte[] responseBytes = responseStream.readAllBytes();
// String jsonResponse = new String(responseBytes, "UTF-8");
//
// // JSON에서 텍스트 추출
// String extractedText = parseResponse(jsonResponse);
// System.out.println(extractedText);
// // 텍스트에서 필요한 정보 추출
// OCRResponseDto ocrResponseDto = extractFieldsUsingKeywords(extractedText);
// System.out.println(ocrResponseDto.getName());
//
// // 생년 월 일 분리
// String extractedYear = ocrResponseDto.getBirth().substring(0, 4); // "1987"
// String extractedMonth = ocrResponseDto.getBirth().substring(6, 8); // "05"
// String extractedDay = ocrResponseDto.getBirth().substring(10, 12); // "23"
//
//
// String userYear = user.getIdentity().substring(0,2);
// String userMonth = user.getIdentity().substring(2,4);
// String userDay = user.getIdentity(
//
// //OCR 정보와 현재 유저 정보가 일치하는지 확인
// if (ocrResponseDto.getName().equals(user.getUsername()) && extractedYear.equals(user.getBirthyear()) && extractedMonth.equals(user.getBirthmonth()) && extractedDay.equals(user.getBirthday())) {
// // 자격증 인증 서비스 호출
// CertificateDTO certificateDTO = certificateService.getCertificateById(ocrResponseDto.getCertificateNum());
//
// // 자격증에 적힌 정보와 OCR과 동일한지 확인
// if (Objects.equals(certificateDTO.getCertificateId(), ocrResponseDto.getCertificateNum()) && Objects.equals(certificateDTO.getUsername(), ocrResponseDto.getName()) && Objects.equals(certificateDTO.getUserId(), user.getId().toString())) {
// // 자격증 검증 성공
// user.updateCertificateCheck();
// return certificateDTO;
// }
//
// }
// else {
// throw new UserNotMatchException("유저 안 맞음");
// }
// return null;
// }


// JSON 응답에서 텍스트 추출
Expand Down

0 comments on commit afc5049

Please sign in to comment.