Skip to content

[Refactor] OCR 처방일 파싱 및 약물노트 그룹화 기준 전환 - #62

Merged
kangcheolung merged 5 commits into
developfrom
refactor/61
Jul 9, 2026
Merged

kangcheolung merged 5 commits into
developfrom
refactor/61

Conversation

@kangcheolung

@kangcheolung kangcheolung commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

🔍️ 작업 내용

✨ 상세 설명

OCR 처방일 파싱

  • OcrParser — extractPrescriptionDate() 추가, "처방일/처방일자/처방전발행일" 우선 파싱, 없으면 "조제일/조제일자" fallback (정규식 기반, YYYY년MM월DD일/YYYY.MM.DD/YYYY-MM-DD 등 포맷 대응)
  • OcrParseResult — LocalDate prescriptionDate 필드 추가 (파싱 실패 시 null)
  • OcrResultResponse — 프론트에 처방일 반환
  • OcrResultConverter / OcrCommandService — 파싱된 처방일을 응답까지 연결

약물노트 그룹화 기준 전환

  • 그룹 키를 startDate 단독 → **prescriptionDate ?? startDate**로 변경 (처방일 파싱 성공 시 우선 사용, 실패 시 복용 시작일 fallback)
  • MedicationNoteGroupResponse 필드명 startDate → prescriptionDate로 변경, 스키마 설명 업데이트
  • MedicationQueryService.toNoteGroupResponses() 그룹핑 로직 반영

🛠️ 추후 리팩토링 및 고도화 계획

  • "처방일" vs "조제일"이 텍스트에 동시에 존재하는 처방전 샘플로 우선순위 로직 검증 필요
  • 표 형식(좌표 기반) 처방전에서 날짜 위치가 다를 경우 파싱 실패 가능성 — 실제 샘플로 추가 검증 필요
  • 날짜 파싱 정규식이 커버하지 못하는 포맷 발견 시 패턴 추가

📸 스크린샷 (선택)

💬 리뷰 요구사항

  • 처방일이 null이어서 startDate로 fallback되는 케이스가 실제로 얼마나 되는지, 이 fallback 전략이 적절한지 확인 부탁
  • 정규식 패턴이 실제 처방전 텍스트 포맷을 충분히 커버하는지 (특히 "처방전발행일" 같은 변형 키워드) 검토 부탁

Summary by CodeRabbit

  • New Features
    • OCR 결과에 처방일 정보가 포함되어, 약 등록 및 조회 시 더 정확한 날짜 기준을 사용할 수 있게 되었습니다.
    • 약 메모 그룹 기준이 복용 시작일에서 처방일 우선(실패 시 기존 날짜로 대체) 방식으로 바뀌었습니다.
  • Bug Fixes
    • 날짜 파싱 결과가 반영되지 않던 흐름을 개선해, OCR 응답과 그룹화 날짜가 일관되게 표시됩니다.

kangcheolung and others added 5 commits July 9, 2026 23:27
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
처방일 키워드("처방일", "처방일자", "처방전발행일") 우선 파싱
없으면 조제일("조제일", "조제일자") fallback
YYYY.MM.DD / YYYY-MM-DD / YYYY년MM월DD일 포맷 지원

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
OcrResultConverter — prescriptionDate 파라미터 추가
OcrCommandService — parseResult.prescriptionDate() 전달

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
startDate → prescriptionDate (처방일 파싱 성공 시 처방일, 실패 시 startDate fallback)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
prescriptionDate가 있으면 우선 사용, 없으면 startDate fallback

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

OCR 파서에 처방일/조제일 추출 로직이 추가되고, 추출된 날짜가 OcrParseResult → OcrResultConverter/OcrCommandService → OcrResultResponse 경로로 전달된다. 약물노트 그룹화 기준(MedicationQueryService, MedicationNoteGroupResponse)이 startDate에서 prescriptionDate(없으면 startDate 폴백)로 변경되었다.

Changes

OCR 처방일 파싱 및 약물노트 그룹화 기준 전환

Layer / File(s) Summary
OcrParser 처방일/조제일 추출 로직
src/main/java/com/piuda/callcare/domain/ocrresult/service/OcrParser.java
처방일/조제일 정규식 패턴, extractPrescriptionDate, tryExtractDate 메서드를 추가하고 예외 시 null 반환하며, parse(...)가 추출 날짜를 OcrParseResult 세 번째 인자로 전달.
처방일 데이터 전달 경로
.../ocrresult/dto/OcrParseResult.java, .../ocrresult/converter/OcrResultConverter.java, .../ocrresult/dto/response/OcrResultResponse.java, .../ocrresult/service/command/OcrCommandService.java
OcrParseResult, OcrResultResponse에 prescriptionDate 필드를 추가하고, toResponse 시그니처와 OcrCommandService.processOcr 호출부가 이를 전달하도록 연결.
약물노트 그룹화 기준 전환
.../medication/service/query/MedicationQueryService.java, .../medication/dto/response/MedicationNoteGroupResponse.java
그룹 키/응답 날짜 계산이 startDate 단독에서 prescriptionDate(없으면 startDate 폴백)로 변경되고, 레코드 필드명 및 @Schema 설명이 이에 맞춰 갱신.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant OcrParser
  participant OcrParseResult
  participant OcrCommandService
  participant OcrResultConverter
  participant OcrResultResponse

  OcrParser->>OcrParser: extractPrescriptionDate(rawText)
  OcrParser->>OcrParseResult: new OcrParseResult(rawText, parsedDrugs, prescriptionDate)
  OcrCommandService->>OcrResultConverter: toResponse(saved, parsedDrugs, parseResult.prescriptionDate())
  OcrResultConverter->>OcrResultResponse: new OcrResultResponse(..., prescriptionDate)
Loading
sequenceDiagram
  participant MedicationQueryService
  participant Medication
  participant MedicationNoteGroupResponse

  MedicationQueryService->>Medication: getPrescriptionDate()
  alt prescriptionDate 존재
    MedicationQueryService->>MedicationQueryService: groupDate = prescriptionDate
  else null
    MedicationQueryService->>Medication: getStartDate()
    MedicationQueryService->>MedicationQueryService: groupDate = startDate
  end
  MedicationQueryService->>MedicationNoteGroupResponse: build(groupDate, ...)
Loading

Possibly related PRs

  • PIUDAProject/Backend#39: OCR 파이프라인에 prescriptionDate 필드를 도입·응답에 포함시키는 동일한 코드 흐름 변경.
  • PIUDAProject/Backend#46: OcrParser/OcrResultConverter/OcrResultResponse와 약 등록 입력에 prescriptionDate를 전파하는 데이터 흐름을 공유.
  • PIUDAProject/Backend#56: MedicationQueryService.toNoteGroupResponses의 그룹 키를 prescriptionDate 기준으로 다루는 동일 코드 경로.

Suggested labels: ✨ Feature

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목이 OCR 처방일 파싱과 약물노트 그룹화 기준 전환이라는 핵심 변경을 간결하게 잘 요약합니다.
Linked Issues check ✅ Passed OCR 처방일 추출, nullable 필드 추가, 응답 전파, 그룹 키를 prescriptionDate 우선·startDate fallback으로 전환하는 요구를 모두 반영했습니다.
Out of Scope Changes check ✅ Passed 변경 파일들이 모두 OCR 처방일 처리와 약물노트 그룹화 관련 범위에 한정되어 있어 별도 무관한 변경은 보이지 않습니다.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/61

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@kangcheolung

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/main/java/com/piuda/callcare/domain/ocrresult/service/OcrParser.java (1)

475-495: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

catch (Exception e) 대신 구체적인 예외 타입 사용을 권장합니다.

tryExtractDate에서 catch (Exception e)는 의도치 않은 런타임 예외까지 포괄합니다. LocalDate.of()에서 발생하는 DateTimeException과 Integer.parseInt()에서 발생할 수 있는 NumberFormatException만 명시적으로 처리하는 것이 예외 처리 의도를 더 명확히 전달합니다.

As per coding guidelines, src/main/java/**/*.java 경로는 예외 처리에 중점을 둡니다.

♻️ 제안하는 리팩터링
     private LocalDate tryExtractDate(Pattern pattern, String text) {
         Matcher m = pattern.matcher(text);
         if (!m.find()) return null;
         try {
             int year  = Integer.parseInt(m.group(1));
             int month = Integer.parseInt(m.group(2).trim());
             int day   = Integer.parseInt(m.group(3).trim());
             return LocalDate.of(year, month, day);
-        } catch (Exception e) {
+        } catch (DateTimeException | NumberFormatException e) {
             return null;
         }
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/com/piuda/callcare/domain/ocrresult/service/OcrParser.java`
around lines 475 - 495, In OcrParser.tryExtractDate, replace the broad catch
block with specific handling for the exceptions actually expected from parsing
and date construction. Update the exception handling around Integer.parseInt and
LocalDate.of to catch only NumberFormatException and DateTimeException, keeping
the fallback behavior in extractPrescriptionDate unchanged.

Source: Path instructions

src/main/java/com/piuda/callcare/domain/medication/service/query/MedicationQueryService.java (1)

66-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

groupDate 계산을 헬퍼로 묶고, 목록 조회 설명도 실제 기준에 맞춰주세요

  • MedicationQueryService.toNoteGroupResponses() 안에서 prescriptionDate -> startDate 폴백이 두 번 반복됩니다. 헬퍼로 분리하면 DRY해지고, 이후 기준 변경도 한 곳만 수정하면 됩니다.
  • MedicationController.getNoteList()의 @Operation 설명은 현재 동작과 다릅니다. "복용 시작일 + 병원 기준" 대신 "처방일 + 병원 기준 (fallback: 복용 시작일)"로 맞춰주세요.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/com/piuda/callcare/domain/medication/service/query/MedicationQueryService.java`
around lines 66 - 77, The groupDate fallback logic is duplicated in
MedicationQueryService.toNoteGroupResponses(), so extract the
prescriptionDate-or-startDate selection into a helper and reuse it both when
building the grouping key and when creating MedicationNoteGroupResponse. Also
update MedicationController.getNoteList()’s `@Operation` description to match the
actual grouping rule, changing it from “복용 시작일 + 병원 기준” to “처방일 + 병원 기준
(fallback: 복용 시작일)”.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@src/main/java/com/piuda/callcare/domain/medication/service/query/MedicationQueryService.java`:
- Around line 66-77: The groupDate fallback logic is duplicated in
MedicationQueryService.toNoteGroupResponses(), so extract the
prescriptionDate-or-startDate selection into a helper and reuse it both when
building the grouping key and when creating MedicationNoteGroupResponse. Also
update MedicationController.getNoteList()’s `@Operation` description to match the
actual grouping rule, changing it from “복용 시작일 + 병원 기준” to “처방일 + 병원 기준
(fallback: 복용 시작일)”.

In `@src/main/java/com/piuda/callcare/domain/ocrresult/service/OcrParser.java`:
- Around line 475-495: In OcrParser.tryExtractDate, replace the broad catch
block with specific handling for the exceptions actually expected from parsing
and date construction. Update the exception handling around Integer.parseInt and
LocalDate.of to catch only NumberFormatException and DateTimeException, keeping
the fallback behavior in extractPrescriptionDate unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: cad03e55-2a45-4f68-beb8-cd6afd550e16

📥 Commits

Reviewing files that changed from the base of the PR and between 7d00944 and 74a850f.

📒 Files selected for processing (7)
  • src/main/java/com/piuda/callcare/domain/medication/dto/response/MedicationNoteGroupResponse.java
  • src/main/java/com/piuda/callcare/domain/medication/service/query/MedicationQueryService.java
  • src/main/java/com/piuda/callcare/domain/ocrresult/converter/OcrResultConverter.java
  • src/main/java/com/piuda/callcare/domain/ocrresult/dto/OcrParseResult.java
  • src/main/java/com/piuda/callcare/domain/ocrresult/dto/response/OcrResultResponse.java
  • src/main/java/com/piuda/callcare/domain/ocrresult/service/OcrParser.java
  • src/main/java/com/piuda/callcare/domain/ocrresult/service/command/OcrCommandService.java

@kangcheolung
kangcheolung merged commit bf0eed9 into develop Jul 9, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Refactor] OCR 처방일 파싱 및 약물노트 그룹화 기준 전환

1 participant