Compare commits

47 Commits

Author SHA1 Message Date
de7018475d 261110_01_ENH: 템플릿 명 최대 128자 확장 및 문자 템플릿 제목 64자 제한 2026-11-10 17:29:47 +09:00
67f17e993d 261102_01_ENH: 알림톡 발신 프로필 목록 조회 추가 및 템플릿 API senderKey 필수 검증 적용 2026-11-09 15:19:21 +09:00
e6b9760594 261102_01_ENH: 알림톡 발신 프로필 목록 조회 추가 및 템플릿 API senderKey 필수 검증 적용 2026-11-02 12:08:12 +09:00
9f0a06bfae 261029_02_ENH: 템플릿 삭제 후 기존 발송 유지 및 벌크 발송 한도 검증 2026-10-29 11:23:37 +09:00
3eb9c2d12f 261029_01_ENH: 템플릿 soft delete 적용 및 발송·예약 건 삭제 차단과 동시성 제어 2026-10-29 08:59:32 +09:00
6a2cc014a7 261023_01_ENH: 문자 발송 유형 LMS(22)·MMS(23) 분리 및 최종 발송 내용 기준 유형 자동 판정 2026-10-23 12:10:28 +09:00
3162b52a35 261022_02_ENH: 발송 결과·벌크 상세·벌크 목록 응답에 예약 취소 가능 여부(cancelable) 추가 2026-10-22 15:17:57 +09:00
f2a9d6bfc6 261022_01_ENH: 예약 발송 취소 구현, record로 전환 가능한 Class Dto record로 전환, KKO 템플릿 등록시 사용 준비도 등록가능 템플릿으로 지정 2026-10-22 12:33:32 +09:00
7a1501d551 261020_02_BUG: KKO 템플릿 리스트 조회에 ACT 결과가 없으면 RDY 조회 없이 오류 수정 2026-10-20 12:30:26 +09:00
dce0e115ae 261020_01_ENH: KKO 템플릿 리스트 조회에 RDY에 대한 조회도 추가 2026-10-20 08:28:48 +09:00
c0f39f7a20 261008_01_ENH: KKO 템플릿 리스트 조회, 템플릿 상세 조회, notihub에 KKO 템플릿 등록, KKO 발송 추가 2026-10-08 09:52:16 +09:00
20f1db3436 261006_02_ENH: 공용 라이브러리 버전업 2026-10-06 14:05:55 +09:00
b988d6850a 261006_01_ENH: AI Agent용 하네스 변경 적용 2026-10-06 14:01:05 +09:00
d8691bebef 261001_01_ENH: 문자 템플릿 JPG 첨부 및 MMS 발송 파일 경로 처리 2026-10-01 12:14:36 +09:00
b80ab72038 260907_01_ENH: 이메일 템플릿 테이블·이미지맵·HR 태그 화이트리스트 확장 2026-09-07 13:55:04 +09:00
b0dc957691 260826_01_ENH: 휴대전화 번호 인증 기능 추가 2026-08-26 12:54:07 +09:00
151af75e9c 260806_02_ENH: AI Agent 하네스 적용 2026-08-06 15:46:09 +09:00
de67433539 260806_01_ENH: 파일첨부 발송 추가 2026-08-06 14:36:13 +09:00
c4c57654da 260805_01_ENH: swagger sort용 속성 yml에 추가 2026-08-05 10:45:59 +09:00
b4d2595d87 260803_04_BUG: 본문 바이트 크기 비교 부등호 방향 버그 2026-08-03 16:47:35 +09:00
ec243e93c4 260803_03_ENH: 템플릿 저장 시 QR코드의 src에 http, https없으면 붙이게 수정 2026-08-03 15:32:43 +09:00
6ad56cd4c8 260803_02_ENH: 추후 첨부파일 발송을 위한 프링고 parameter-send로 발송 방식 교체 및 메일 발송 시 <mark> 태그 <span>으로 교체해서 발송되도록 수정 2026-08-03 15:07:58 +09:00
b442638194 260803_01_ENH: <qrcode> 태그 <img>로 치환해서 전송 및 템플릿 저장시 일부 태그에 대한 스타일 화이트리스트 처리 2026-08-03 14:33:50 +09:00
1428f7e133 260723_03_ENH: unitPrice의 Price BigDecimal로 변경 2026-07-23 16:45:48 +09:00
209b34720e 260723_02_ENH: 서비스별 발송 내역 및 금액 조회 API 생성 2026-07-23 16:36:26 +09:00
86f9d1b634 260723_01_ENH: 문자발송 갱신 조건 변경 (1시간 이내 -> 현재 시간보다 작은 모든 것) 2026-07-23 10:54:55 +09:00
8043fc457c 260722_02_ENH: 공용 패키지 고정 버전으로 다시 수정(최신 패키지 적용이 잘 안됨) 2026-07-22 11:38:57 +09:00
5698d2f135 260722_01_ENH: 공용 패키지 항상 최신버전을 사용하도록 수정 2026-07-22 11:21:18 +09:00
9c722e78d0 260721_01_ENH: 프링고 parameter 방식의 send요청 추가, 발송시 sendTy 다시 계산하도록 수정, sid 별 조회 추가 2026-07-21 09:58:34 +09:00
fb213035f3 260720_02_ENH: 프링고 응답 json에 오타있음 2026-07-20 11:24:09 +09:00
a3425b16e0 260720_01_ENH: 오타 수정 2026-07-20 11:20:51 +09:00
107b6b5c9c 260715_04_ENH: 이메일 대량 발송 타임 슬립 위치변경 2026-07-15 12:16:21 +09:00
791d01c6fc 260715_03_ENH: 이메일 대량 발송 스케쥴러로 분리 2026-07-15 10:22:35 +09:00
132a8a0367 260715_01_ENH: 스케쥴러에 들어가는 설정들 yml로 이동 2026-07-15 08:22:35 +09:00
e38a095755 260714_02_ENH: 발송결과 갱신 기본 시간 5초 -> 10초 로 변경 2026-07-14 15:08:11 +09:00
86f1cc0118 260714_02_ENH: 발송결과 갱신 기본 시간 60초 -> 5초 로 변경 2026-07-14 13:52:58 +09:00
06fe85e7ee 260714_01_ENH: 이메일 발송 수정 및 발송결과 재갱신 5분단위 스케쥴 추가 2026-07-14 09:07:34 +09:00
fd43fce572 260713_01_ENH: 발송 결과에 result code에 대한 label 매칭해서 반환하도록 수정, bulksend에 대한 결과 조회도 통일 2026-07-13 09:44:57 +09:00
8be53a1cae 260710_01_ENH: SID 별 발송 결과 조회 구현, 발송 결과 코드 표 조회 구현 2026-07-10 14:38:02 +09:00
6674c70ac6 260626_02_ENH: 발송 축약 결과 조회 구현, admin용 api 보이고 사용 가능하게 수정 2026-06-26 16:02:29 +09:00
57470854ff 260626_01_ENH: is_success 에서 result_code_type로 변경 2026-06-26 11:25:24 +09:00
01e27e678f 260624_01_ENH: t_send_result_code테이블에 is_success_code추가 관련 수정 2026-06-24 13:43:31 +09:00
f9b6346791 260618_01_ENH: sms인 경우 타이틀 제거하는 부분 수정 2026-06-18 14:28:52 +09:00
d77efb9c98 260617_02_ENH: 문자 발송 오류 수정 2026-06-17 15:05:39 +09:00
bc72bf2526 260617_01_ENH: 문자 줄바꿈 저장 되게 수정 2026-06-17 14:38:49 +09:00
556385ddbd 260407_01_ENH: swagger 허용 ip 추가 2026-04-07 11:16:09 +09:00
0050d75019 260327_02_ENH: kri.common 라이브러리 JWT 버전 충돌 해결 적용 2026-03-27 12:14:12 +09:00
125 changed files with 5666 additions and 1037 deletions

View File

@@ -0,0 +1,14 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-common
Source: .agent/consumer-references/crypto-contract.md
-->
# KriCommon Crypto Contract
- Crypto APIs are under `com.kri.common.feature.crypto.*` and do not use a central key database.
- AES uses PBKDF2-HMAC-SHA256 key derivation with salt and defaults to AES-256-GCM; callers may supply a master key, salt, IV, AAD, and detached or appended GCM tag representation for legacy interoperability.
- `kri.crypto.aes.keys` and per-call master keys are supported operational compromises. Never log them or commit real values.
- Per-call key material takes precedence over configured keys, and encrypted values retain key ID and KDF metadata for decryption compatibility.
- AES-GCM always requires its authentication tag. Use `AES_256_CBC_PKCS5` only for explicitly identified legacy data that has no tag, and do not treat CBC as authenticated encryption.
- `DigestService` supports SHA-256/SHA-512 plus legacy-only MD5/SHA-1. `AdaptiveHashService` uses BCrypt for short secrets; do not use MD5, SHA-1, or a fast digest for new password or secret storage.

View File

@@ -0,0 +1,28 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-common
Source: .agent/consumer-references/platform-capabilities.md
-->
# KriCommon Platform Capabilities
## Dependency and Configuration Boundary
- Include the matching Spring starter for any optional Web, Security, JPA, Redis, AOP, or Swagger integration the service enables; KriCommon intentionally declares many integrations as compile-only.
- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `kri.crypto`, `kri.security`, `kri.swagger`, `kri.web`, `kri.web.mdc`, `kri.http.bypass`, `kri.redis`, `kri.scheduling`, and `kri.error.expose`.
- Read the version-matched README and configuration-property classes before setting a property; do not infer a property name or default from an older service.
- Supply production JWT secrets, API keys, credentials, allowlists, and service URLs through the consumer's approved secret and configuration system. Never rely on library example or default secrets in production.
- Preserve consumer override points. KriCommon's default security chain is created only when the consumer does not provide one, and overridable beans should remain explicit.
- Adding a path to API-key allowed paths scopes where API-key authentication is attempted; it does not make the path public or grant authorization.
## Optional Capabilities
- JWT and API-key authentication integrate with Spring Security. API-key JPA preload requires Spring Data JPA; a consumer-provided claims provider can be used without JPA.
- Common Web may register error handling, tracing/MDC, request-user resolution, enum conversion, and CORS behavior. Check for overlap before defining consumer-local equivalents.
- Swagger support requires springdoc and defines the shared Bearer/API-key schemes and grouped paths.
- Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies.
- HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers.
- The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`.
- `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes.
- Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply.
- `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics.

View File

@@ -0,0 +1,13 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-common
Source: .agent/consumer-references/upgrade-and-verification.md
-->
# KriCommon Upgrade and Verification
- Review KriCommon release notes, README changes, configuration defaults, auto-configuration conditions, and affected public APIs before upgrading.
- Commit dependency-lock or resolved-version changes according to the consumer repository's policy.
- Run the consumer's focused compile and tests after an upgrade, including application-context startup tests when auto-configuration or security behavior is affected.
- Keep `.agent/project.md` near 2-3 KiB as a routing document. Do not delete material rules to meet the budget; move conditional schema, query, API, and migration details to routed `.agent/references/` documents.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.

25
.agent/profile.yml Normal file
View File

@@ -0,0 +1,25 @@
schema_version: 1
project:
id: noti-hub
name: NotiHub
type: shared-service
layer: backend
legacy: false
stack:
- java-springboot
shared_contracts:
consumes:
- kri-common
databases:
- id: notification-data
engine: mysql
role: primary
access: read-write
- id: api-key-data
engine: mysql
role: authentication
access: read-only

18
.agent/project.md Normal file
View File

@@ -0,0 +1,18 @@
# NotiHub Project Instruction Router
## Required Project References
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
## Harness Workflow
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.

View File

@@ -0,0 +1,29 @@
## NotiHub Repository Rules
### Repository Role and Contracts
- This repository is the Java 17 Spring Boot backend for shared email, SMS, Kakao notification, template, attachment, scheduling, and delivery-report workflows.
- Treat endpoint paths, request and response DTOs, channel and result codes, template variables, attachment behavior, scheduling rules, identifiers, retry behavior, and error responses as contracts used by other projects.
- Preserve the established controller, service, external-client, scheduler, DTO, configuration, and persistence boundaries.
- Consume KriCommon through `com.kri.common:starter:beta.1.6.3`. Do not change that approved version or duplicate a KriCommon feature without separate explicit approval.
### Delivery and External-Side-Effect Safety
- Never send real email, SMS, Kakao notifications, callbacks, or business API requests during development or validation. Use an already-approved mock, fake, or verified test recipient only when the task explicitly requires it.
- Before changing a send flow, identify creation, reservation, dispatch, provider callback or polling, retry, cancellation, and final-status transitions.
- Preserve idempotency and duplicate-send protections across HTTP retries, scheduler overlap, worker retries, and provider timeouts. Do not mark a message successful before the provider contract establishes success.
- Keep provider timeouts, retry limits, error mapping, and partial-failure behavior explicit. Do not silently discard provider errors or attachments.
- Validate attachment count, type, size, filename, storage path, and lifecycle. Prevent path traversal and avoid loading unbounded files or message bodies into memory.
### Data, Security, and Privacy
- Keep transaction boundaries narrow around queue, template, attachment, report, and status changes. Review concurrency and locking whenever scheduled or bulk work is modified.
- Treat the MySQL API-key data source as read-only authentication data. Do not add writes to it without separate explicit approval.
- Never log credentials, API keys, provider tokens, full recipient lists, complete message bodies, attachment contents, or other personal data.
- Preserve authentication, authorization, validation, rate limits, allowlists, template ownership checks, and reporting access controls.
### Documentation and Verification
- `AGENTS.md` and `CLAUDE.md` are harness-generated outputs. Never edit either file directly; edit `.agent/project.md` or `.agent/profile.yml` and recompose instead.
- Use the repository Gradle Wrapper and run `.\gradlew.bat compileJava` on Windows for relevant changes, followed by focused tests that cannot deliver real notifications or call live providers.
- Do not start schedulers, connect to production data, upload real attachments, or invoke external notification providers during validation without separate explicit approval.

View File

@@ -0,0 +1,41 @@
---
name: attention-aware-communication
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/attention-aware-communication/SKILL.md
-->
# Attention-Aware Communication
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
## Default: Attention-kind
- Put the bottom line in the first sentence and use plain Korean.
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
## Progress and Completion: Rundown
Use Rundown formatting when a task has multiple steps or mixed states:
- Start with a one-line outcome that includes any blocker.
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
- Put each blocker or material risk on its own line.
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
- End with the next action or a small numbered choice only when the user must decide.
## Explicit-Only: Spartan
Use Spartan style only when the user explicitly asks for it:
- Lead with the complete answer in one sentence.
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
- If the user also asks for depth, provide the full detail in short, separated blocks.

View File

@@ -0,0 +1,37 @@
---
name: karpathy-guidelines
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/karpathy-guidelines/SKILL.md
-->
# Karpathy Guidelines
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
## Think Before Coding
- Inspect the relevant code and repository conventions before choosing a solution.
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
## Simplicity First
- Implement the smallest complete solution that satisfies the observable requirement.
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
- Prefer an existing repository pattern or standard-library capability over a new local framework.
## Surgical Changes
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
## Goal-Driven Execution
- Translate the request into observable success criteria before implementation.
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.

View File

@@ -0,0 +1,29 @@
---
name: project-reference-loader
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/project-reference-loader/SKILL.md
-->
# Project Reference Loader
Use the repository's generated `AGENTS.md` as the routing entrypoint.
## Workflow
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
## Change Handling
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
- Never edit generated `.agent-harness/references/` copies directly.
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.

View File

@@ -0,0 +1,38 @@
---
name: verification-before-completion
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/verification-before-completion/SKILL.md
-->
# Verification Before Completion
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
## Verification Gate
Before making a success claim:
1. State the exact claim internally and identify which observable check can prove or disprove it.
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
4. Compare the evidence with the claim and the approved acceptance criteria.
5. Report only the status supported by that evidence.
## Evidence Rules
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
## Reporting
- Cite the commands or inspections actually run and summarize their observed results.
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.

View File

@@ -0,0 +1,41 @@
---
name: attention-aware-communication
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/attention-aware-communication/SKILL.md
-->
# Attention-Aware Communication
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
## Default: Attention-kind
- Put the bottom line in the first sentence and use plain Korean.
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
## Progress and Completion: Rundown
Use Rundown formatting when a task has multiple steps or mixed states:
- Start with a one-line outcome that includes any blocker.
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
- Put each blocker or material risk on its own line.
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
- End with the next action or a small numbered choice only when the user must decide.
## Explicit-Only: Spartan
Use Spartan style only when the user explicitly asks for it:
- Lead with the complete answer in one sentence.
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
- If the user also asks for depth, provide the full detail in short, separated blocks.

View File

@@ -0,0 +1,37 @@
---
name: karpathy-guidelines
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/karpathy-guidelines/SKILL.md
-->
# Karpathy Guidelines
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
## Think Before Coding
- Inspect the relevant code and repository conventions before choosing a solution.
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
## Simplicity First
- Implement the smallest complete solution that satisfies the observable requirement.
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
- Prefer an existing repository pattern or standard-library capability over a new local framework.
## Surgical Changes
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
## Goal-Driven Execution
- Translate the request into observable success criteria before implementation.
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.

View File

@@ -0,0 +1,29 @@
---
name: project-reference-loader
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/project-reference-loader/SKILL.md
-->
# Project Reference Loader
Use the repository's generated `AGENTS.md` as the routing entrypoint.
## Workflow
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
## Change Handling
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
- Never edit generated `.agent-harness/references/` copies directly.
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.

View File

@@ -0,0 +1,38 @@
---
name: verification-before-completion
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/verification-before-completion/SKILL.md
-->
# Verification Before Completion
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
## Verification Gate
Before making a success claim:
1. State the exact claim internally and identify which observable check can prove or disprove it.
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
4. Compare the evidence with the claim and the approved acceptance criteria.
5. Report only the status supported by that evidence.
## Evidence Rules
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
## Reporting
- Cite the commands or inspections actually run and summarize their observed results.
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.

4
.gitattributes vendored
View File

@@ -1,3 +1,7 @@
/gradlew text eol=lf /gradlew text eol=lf
*.bat text eol=crlf *.bat text eol=crlf
*.jar binary *.jar binary
/AGENTS.md text eol=lf
/CLAUDE.md text eol=lf
/.agent/*.md text eol=lf
/.agent/*.yml text eol=lf

276
AGENTS.md Normal file
View File

@@ -0,0 +1,276 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: noti-hub
Schema version: 1
Edit the source fragments or repository .agent files, then recompose.
-->
# KRI Development Base Instructions
This document defines the shared working rules for KRI development repositories.
Keep project-specific facts and commands in the project profile and project rules.
## Instruction Resolution
Apply repository instructions in this order:
1. Base rules
2. Project-type rules
3. Technology-stack rules
4. Shared consumer contracts
5. Project-specific rules
6. The explicitly approved task scope
Later and more specific instructions may override earlier general instructions only within their stated scope.
- Apply a shared consumer contract only when `.agent/profile.yml` declares it.
- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files.
- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive.
## Communication
- Respond to the user in Korean unless the user requests another language.
- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form.
- Follow the repository's existing language conventions for code comments and user-facing messages.
- Lead with the result or decision, then provide only the detail needed to verify it.
- Do not create or retain a full session transcript.
### Attention-Aware Response Style
- Use `attention-aware-communication` for substantive answers, progress updates, and completion reports.
- Default to concise, bottom-line-first Korean without omitting a condition, risk, number, or uncertainty needed for a correct decision.
- Give full detail when the user requests depth. Use Spartan style only when explicitly requested.
- Presentation rules never reduce investigation, implementation, validation, or reporting obligations.
## Work Authorization
- The default workflow is discussion first and explicit execution approval second.
- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection.
- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup.
- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state.
- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks.
- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands.
- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope.
- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages.
## Local Development Environment
- Primary OS: Windows 11.
- Primary shell: PowerShell.
- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior.
- Prefer repository-provided wrappers and scripts over globally installed commands.
- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them.
- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration.
- Do not install or modify global toolchains as part of a project task.
Preferred human-facing tools:
- Classic ASP: Visual Studio Code
- Java and Spring Boot: IntelliJ IDEA
- C# and .NET: JetBrains Rider
- JavaScript, TypeScript, and Next.js: JetBrains WebStorm
- Python: JetBrains PyCharm
- Microsoft SQL Server: SQL Server Management Studio
- Other databases: JetBrains DataGrip
- These preferences do not authorize launching or controlling a GUI application.
- Prefer IDE-independent commands that can also run in CI.
- Do not modify global IDE settings.
- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it.
- Preserve existing shared IDE configuration when it is already tracked.
## PowerShell and Path Safety
- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters.
- Prefer `-LiteralPath` when operating on an exact filesystem path.
- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`.
- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations.
- Keep a filesystem operation within one shell from target resolution through execution.
- Before a recursive delete or move, resolve and verify every absolute target.
- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target.
- Prefer recoverable operations when practical.
## Change Discipline
- Preserve all existing user changes, including uncommitted and untracked work.
- Keep changes minimal but complete for the approved objective.
- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring.
- Do not overwrite or revert unrelated changes.
- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely.
- Prefer changing an authoritative source over editing generated output.
- Treat files marked as generated as read-only unless regeneration is part of the approved plan.
- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required.
- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope.
## Text Encoding and Korean Content Safety
- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract.
- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them.
- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text.
- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them.
- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change.
- Avoid whole-file rewrites for small changes.
- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit.
- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding.
- Treat a console display problem and an on-disk encoding problem as separate issues.
- After editing Korean text, inspect the diff for replacement characters (`<60>`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes.
- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding.
- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence.
- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM.
## Git Safety
- Use `git status`, `git diff`, and `git log` for read-only investigation.
- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved.
- Source-edit approval does not include commit or push approval.
- Never amend an existing commit unless explicitly requested.
- Before an approved commit, show the intended files, validation results, and proposed commit message.
- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push.
## Dependencies and External Actions
- Use the package manager, lockfile, and toolchain already selected by the repository.
- Do not install global packages.
- Do not add, remove, or upgrade a dependency unless it was included in the approved plan.
- Pause for approval if an unplanned dependency becomes necessary.
- Keep lockfiles synchronized with approved dependency changes.
- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested.
- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service.
- Remove secrets and unnecessary internal identifiers from external search queries.
## Database Safety
- Treat writing or reviewing SQL as source code separately from executing SQL against a database.
- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope.
- Do not connect to a shared, staging, or production database without explicit authorization for that environment.
- Read-only queries against a non-local database also require authorization because results may contain sensitive data.
- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation.
- Source-change approval does not authorize migration execution.
- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature.
- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output.
## Secrets and Sensitive Data
- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control.
- Read sensitive files only when the approved task requires it and no safer source exists.
- Prefer inspecting configuration keys and schemas without displaying secret values.
- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots.
- Redact sensitive values when reporting errors or command output.
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized.
## Workflow Skills
- Use `project-reference-loader` before substantive repository analysis, planning, implementation, debugging, or review. Read only the current project and shared references routed for that task, and reread them for each related task even if they were loaded earlier in the session.
- Use `karpathy-guidelines` when implementing, refactoring, or reviewing code. It keeps assumptions visible, changes surgical, and success criteria verifiable.
- Use `verification-before-completion` before claiming that work is complete, fixed, passing, ready, or safe to commit or publish.
- A skill does not expand task scope or authorize Git publication, database execution, deployment, destructive actions, or external communication.
## Validation
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
- Include intended validation in the discussion-phase plan.
- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate.
- Limit formatting to files within the approved scope.
- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized.
- Do not claim that a check passed unless it was executed successfully.
- If a check cannot be run, state the exact reason.
- Distinguish a current-change failure from a pre-existing failure or an undetermined failure.
- Do not fix unrelated failures without expanding the approved scope.
- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes.
## Artifacts and Session Records
- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested.
- Store durable information in the repository's existing documentation structure.
- Do not place generated reports or temporary analysis files in the repository root.
- Remove task-specific temporary files created by the current task after validation when removal is safe.
## Completion Report
When implementation is complete, report in Korean:
- what changed and why;
- the main affected files or components;
- validation commands actually executed and their results;
- checks not executed and the reason;
- remaining risks, assumptions, or follow-up work;
- database, deployment, dependency, encoding, and compatibility impact when applicable.
- Do not report completion while required validation is failing or known encoding corruption is unresolved.
- Keep the report concise and do not include a full session transcript.
## Shared Service Project Rules
- Treat APIs, message formats, callback behavior, identifiers, error responses, and operational defaults as contracts used by multiple consumers.
- Prefer backward-compatible API and schema evolution.
- Identify all externally visible side effects before changing a request flow.
- Design retryable operations to be idempotent where duplicate execution could send multiple notifications, create duplicate records, or generate inconsistent results.
- Define explicit timeout, retry, and failure behavior for external dependencies.
- Do not send real email, SMS, notifications, callbacks, or business requests during development or validation.
- Use mocks, fakes, test recipients, or disposable local integrations only when their safety is verified.
- Do not expose credentials, message contents, personal data, shortened target URLs, or authentication material in logs.
- Preserve authentication, authorization, rate limits, validation, and abuse controls when modifying endpoints.
- Review database and rollout compatibility before changing persisted data or shared service behavior.
- Include consumer impact and rollback considerations in the completion report.
## Java and Spring Boot
- Treat the configured JDK, Spring Boot, Gradle, plugin, dependency, and package versions as authoritative.
- Use the repository's Gradle Wrapper. Do not substitute a machine-global Gradle installation.
- Preserve the established package layout and controller, application/service, domain, and persistence boundaries.
- Keep controllers thin, place business rules in the established service/domain layer, and prefer constructor injection.
- Apply request and configuration validation at boundaries and preserve the project's exception and response conventions.
- Make transaction boundaries explicit and narrow; do not add broad transactions to hide lifecycle or query problems.
- Preserve authentication, authorization, auditing, logging, and secret-management conventions.
- Do not edit generated QueryDSL or other generated sources. Change their source definitions and regenerate only when the repository workflow requires it.
- Use the approved KriCommon contract when the project profile includes it; do not duplicate shared backend behavior locally.
- Run the narrowest relevant Gradle compile, test, static-analysis, and build tasks.
## MySQL
- Use MySQL syntax and behavior only for data sources whose declared engine is `mysql`.
- Preserve the configured version, schema, character set, collation, time zone, naming, migration, and access conventions.
- Parameterize values. Do not build SQL by concatenating untrusted input.
- Consider indexes and execution plans for changed filters, joins, ordering, grouping, and pagination without guessing from small data sets.
- Preserve transaction, locking, null, date/time, decimal, and generated-key semantics.
- Do not introduce MSSQL or other dialect syntax into MySQL paths.
- A source-code change approval authorizes SQL analysis and migration drafting only. Execute DDL, DML, procedures, or migrations only with separate explicit approval and the declared data-source access level.
## KriCommon Consumer Contract
- Consume KriCommon as `com.kri.common:starter:<approved-version>` through the repository's established Gradle version-management convention.
- Import service-facing APIs from `com.kri.common.feature.*`; treat `com.kri.common.runtime.*` as internal.
- Prefer a shared feature or approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, crypto, or utility behavior locally.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.
### Required Shared References
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Dependency, configuration, security, Web, Swagger, Redis, scheduling, HTTP, JSON, or date/time behavior | `.agent-harness/references/kri-common/platform-capabilities.md` |
| Encryption, hashing, key material, or legacy crypto interoperability | `.agent-harness/references/kri-common/crypto-contract.md` |
| KriCommon version upgrade or consumer verification | `.agent-harness/references/kri-common/upgrade-and-verification.md` |
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
# NotiHub Project Instruction Router
## Required Project References
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
## Harness Workflow
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.

1
CLAUDE.md Normal file
View File

@@ -0,0 +1 @@
@AGENTS.md

30
README.md Normal file
View File

@@ -0,0 +1,30 @@
# NotiHub Server
## 이메일 발송 상태 101 운영 참고
`result_code=101` (`EMAIL_SENDING`)은 서버가 이메일 발송 처리를 시작했지만
공급사 접수 결과를 아직 DB에 반영하지 않은 일시적인 상태다.
이때 `send_status`는 `0` (`STANDBY`)이다.
- 즉시 단건 이메일은 공급사 API 호출 후 접수 결과를 발송 이력에 저장한다.
- 예약·벌크 이메일은 발송 대기 `100`에서 처리 시작 시 `101`로 전환한다.
- 공급사 접수 성공과 실제 `return_key` 저장이 완료되면 `111`로 전환한다.
이는 접수 성공이며 최종 발송 결과는 poller로 조회한다.
- 준비 오류·접수 실패·타임아웃·키 미수신 등이 처리되고 DB 저장까지 완료되면
`109`로 전환한다.
### 내부 장애로 101이 남은 경우
예약·벌크 발송 처리를 시작한 뒤 `111` 또는 `109`를 저장하기 전에 서버가 강제 종료되거나
DB 저장이 실패하면, 먼저 커밋된 `101`이 남을 수 있다.
정상적으로 응답·타임아웃 처리와 DB 저장이 끝난 경우에는 계속 남는 상태가 아니다.
잔류한 `101`만으로 공급사 접수 여부를 판단할 수 없으므로 운영 확인 대상으로 취급한다.
`RESERVATION_…`는 실제 `return_key`가 아니므로 결과 조회에 사용할 수 없다.
공급사 접수·발송 여부를 확인하지 않고 재발송하면 중복 발송될 수 있다.
템플릿 soft delete는 진행 중이거나 예약된 발송을 차단하지 않는다.
삭제된 템플릿의 첨부파일과 본문 이미지는 기존 발송을 위해 보존한다.
기존 비예약 벌크 이메일의 오래된 `101`을 `100`으로 되돌리는 복구 처리는 유지된다.
해당 처리는 `bulk_send_key`가 없는 즉시 단건 이메일에는 적용되지 않는다.

View File

@@ -38,7 +38,7 @@ repositories {
} }
dependencies { dependencies {
implementation "com.kri.common:starter:beta.1.1.02" implementation "com.kri.common:starter:beta.1.7.0"
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-security'
@@ -58,7 +58,7 @@ dependencies {
compileOnly 'org.projectlombok:lombok' compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok'
implementation 'org.apache.poi:poi-ooxml:5.2.5' implementation 'org.apache.poi:poi-ooxml:5.5.1'
developmentOnly 'org.springframework.boot:spring-boot-devtools' developmentOnly 'org.springframework.boot:spring-boot-devtools'

View File

@@ -2,9 +2,17 @@ package com.kri.notihub.server.common.consts;
import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.common.enums.SendType;
import java.util.List; import java.util.List;
import java.util.Set;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public final class NotihubConst { public final class NotihubConst {
// send_status=CANCELED와 함께 사용하는 NotiHub 내부 코드
public static final short EMAIL_CANCELED = 108;
public static final short BIZPPURIO_CANCELED = 9998;
public static final String CANCELED_LABEL = "예약 취소";
public static final String NATION_CODE = "82"; public static final String NATION_CODE = "82";
public static final int OUTSOURCE_USER_ROLE = 4000; public static final int OUTSOURCE_USER_ROLE = 4000;
public static final int CHUNK_SIZE = 5_000; public static final int CHUNK_SIZE = 5_000;
@@ -13,11 +21,20 @@ public final class NotihubConst {
public static final short EMAIL_RESULT_SEARCH_DELAY = 500; public static final short EMAIL_RESULT_SEARCH_DELAY = 500;
public static final short EMAIL_DELAY = 500; public static final short EMAIL_DELAY = 500;
public static final short DELAY_MAX_MS = (short) 5_000; // 필요시 조정 public static final short DELAY_MAX_MS = (short) 5_000; // 필요시 조정
public static final List<Short> SMS_TYPE_CODE_LIST = List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode()); public static final List<Short> SMS_TYPE_CODE_LIST = List.of(
SendType.SMS.getCode(),
SendType.LMS.getCode(),
SendType.MMS.getCode()
);
public static final List<Short> LMS_MMS_TYPE_CODE_LIST = List.of(
SendType.LMS.getCode(),
SendType.MMS.getCode()
);
public static final List<Short> KKO_TYPE_CODE_LIST = List.of(SendType.KKO_AT.getCode()); public static final List<Short> KKO_TYPE_CODE_LIST = List.of(SendType.KKO_AT.getCode());
public static final List<Short> EMAIL_TYPE_CODE_LIST = List.of(SendType.EMAIL.getCode()); public static final List<Short> EMAIL_TYPE_CODE_LIST = List.of(SendType.EMAIL.getCode());
public static final String EMAIL_RESERVATION_PREFIX = "RESERVATION_"; public static final String EMAIL_RESERVATION_PREFIX = "RESERVATION_";
public static final short EMAIL_STANDBY = 100; public static final short EMAIL_STANDBY = 100; // 발송 전 대기
public static final short EMAIL_SENDING = 101; // worker 점유/발송 시도 중
public static final short EMAIL_PENDING = (short) 111; // 발송요청은 성공했으나 json_return 미조회 public static final short EMAIL_PENDING = (short) 111; // 발송요청은 성공했으나 json_return 미조회
public static final short EMAIL_SEND_FAIL = (short) 109; // 발송요청 실패(또는 return_key 미수신) public static final short EMAIL_SEND_FAIL = (short) 109; // 발송요청 실패(또는 return_key 미수신)
public static final short EMAIL_NOT_RESULT = (short) 119; // json_return 조회 실패/결과없음(최종상태 확보 실패) public static final short EMAIL_NOT_RESULT = (short) 119; // json_return 조회 실패/결과없음(최종상태 확보 실패)
@@ -29,7 +46,6 @@ public final class NotihubConst {
public static final short LMS_MMS_SUCCESS = 6600; public static final short LMS_MMS_SUCCESS = 6600;
public static final short KKO_AT_STANDBY = 7900; public static final short KKO_AT_STANDBY = 7900;
public static final short KKO_AT_SUCCESS = 7000; public static final short KKO_AT_SUCCESS = 7000;
public static final Set<String> KKO_TEMPLATE_AVAILABLE_STATUSES = Set.of("A", "R"); // 정상, 사용준비
private NotihubConst() {
}
} }

View File

@@ -0,0 +1,15 @@
package com.kri.notihub.server.common.enums;
import com.kri.common.feature.enums.CodeEnum;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public enum PhoneVerificationStatus implements CodeEnum<Short> {
PENDING((short) 0),
VERIFIED((short) 1);
private final Short code;
}

View File

@@ -20,7 +20,7 @@ public enum SendCorpType implements CodeEnum<Short> {
return null; return null;
} }
for (SendCorpType s : values()) { for (SendCorpType s : values()) {
if (s.code == code) { if (s.code.equals(code)) {
return s; return s;
} }
} }

View File

@@ -10,7 +10,8 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor @RequiredArgsConstructor
public enum SendSmsType implements CodeEnum<Short> { public enum SendSmsType implements CodeEnum<Short> {
SMS((short) 21), SMS((short) 21),
LMS_MMS((short) 22); LMS((short) 22),
MMS((short) 23);
private final Short code; private final Short code;

View File

@@ -12,6 +12,7 @@ public enum SendStatusType implements CodeEnum<Short> {
STANDBY((short) 0), STANDBY((short) 0),
SUCCESS((short) 1), SUCCESS((short) 1),
CANCELED((short) 8),
FAIL((short) 9); FAIL((short) 9);
private final Short code; private final Short code;

View File

@@ -11,7 +11,8 @@ import lombok.RequiredArgsConstructor;
public enum SendType implements CodeEnum<Short> { public enum SendType implements CodeEnum<Short> {
EMAIL(SendEmailType.EMAIL), EMAIL(SendEmailType.EMAIL),
SMS(SendSmsType.SMS), SMS(SendSmsType.SMS),
LMS_MMS(SendSmsType.LMS_MMS), LMS(SendSmsType.LMS),
MMS(SendSmsType.MMS),
KKO_AT(SendKkoAtType.KKO_AT); KKO_AT(SendKkoAtType.KKO_AT);
private final Short code; private final Short code;

View File

@@ -0,0 +1,30 @@
package com.kri.notihub.server.common.enums;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.kri.common.feature.enums.CodeEnum;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter(onMethod_ = @JsonValue)
@RequiredArgsConstructor
public enum TemplatePurpose implements CodeEnum<Short> {
NORMAL((short) 0),
PHONE_VERIFICATION((short) 1);
private final Short code;
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static TemplatePurpose fromCode(Short code) {
if (code == null) {
return null;
}
for (TemplatePurpose purpose : values()) {
if (purpose.code.equals(code)) {
return purpose;
}
}
throw new IllegalArgumentException("Unknown TemplatePurpose code: " + code);
}
}

View File

@@ -0,0 +1,73 @@
package com.kri.notihub.server.common.external.intranet;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kri.common.feature.http.ExternalApiClient;
import com.kri.common.feature.http.ExternalApiResponse;
import com.kri.notihub.server.common.external.intranet.dto.IntranetProjectBaseInfoDto;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class IntranetApiClient {
private static final String PROJECT_WITH_P_CHILD_SN_PATH =
"/project/search/all/with-p-child-sn";
// ExternalApiClient is constructed directly because the starter may not provide it as a Bean.
private final ExternalApiClient externalApiClient = new ExternalApiClient();
private final ObjectMapper objectMapper = new ObjectMapper();
@Value("${kri.api-url.intranet-extension}")
private String intranetExtensionBaseUrl;
@Value("${kri.auth.apikey.header-name:X-API-Key}")
private String apiKeyHeaderName;
@Value("${kri.auth.apikey.key}")
private String apiKey;
/**
* POST {intranetExtensionBaseUrl}/project/search/all/with-p-child-sn
*/
public List<IntranetProjectBaseInfoDto> getProjectWithPChildSn(List<String> childSnList) {
if (childSnList == null || childSnList.isEmpty()) {
return Collections.emptyList();
}
String url = String.format("%s%s", normalizeBaseUrl(intranetExtensionBaseUrl),
PROJECT_WITH_P_CHILD_SN_PATH);
Map<String, String> headers = new HashMap<>();
headers.put(apiKeyHeaderName, apiKey);
try {
String body = objectMapper.writeValueAsString(childSnList);
ExternalApiResponse response = externalApiClient.post(url, headers, body);
return objectMapper.readValue(response.getBody(),
new TypeReference<List<IntranetProjectBaseInfoDto>>() {
});
} catch (JsonProcessingException e) {
return Collections.emptyList();
}
}
public List<IntranetProjectBaseInfoDto> getProjectWithPChildSn(String... childSnArray) {
if (childSnArray == null || childSnArray.length == 0) {
return Collections.emptyList();
}
return getProjectWithPChildSn(List.of(childSnArray));
}
private String normalizeBaseUrl(String baseUrl) {
return baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
}
}

View File

@@ -0,0 +1,12 @@
package com.kri.notihub.server.common.external.intranet.dto;
public record IntranetProjectBaseInfoDto(
String childSn,
String title,
String researchTeam,
String researchTeamName
) {
}

View File

@@ -0,0 +1,119 @@
package com.kri.notihub.server.common.external.kakao;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kri.common.feature.http.ExternalApiClient;
import com.kri.common.feature.http.ExternalApiResponse;
import com.kri.common.feature.web.BusinessException;
import com.kri.notihub.server.config.KkoTemplateProperties;
import java.net.http.HttpTimeoutException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class KkoTemplateApiClient {
private final KkoTemplateProperties properties;
private final ObjectMapper objectMapper;
private final ExternalApiClient externalApiClient;
@Autowired
public KkoTemplateApiClient(KkoTemplateProperties properties, ObjectMapper objectMapper) {
this(properties, objectMapper, new ExternalApiClient());
}
KkoTemplateApiClient(KkoTemplateProperties properties, ObjectMapper objectMapper,
ExternalApiClient externalApiClient) {
this.properties = properties;
this.objectMapper = objectMapper;
this.externalApiClient = externalApiClient;
}
public JsonNode list(String senderKey, String keyword, String templateStatus) {
Map<String, Object> request = credentials();
request.put("senderKey", senderKey);
request.put("templateStatus", templateStatus);
if (keyword == null || keyword.isBlank()) {
request.put("page", 1);
request.put("count", 10);
} else {
request.put("keyword", keyword.trim());
}
return post("/template/list", request);
}
public JsonNode detail(String senderKey, String templateCode) {
Map<String, Object> request = credentials();
request.put("senderKey", senderKey);
request.put("templateCode", templateCode);
return post("/template/detail", request);
}
public JsonNode profiles() {
return post("/profile/use", credentials());
}
private Map<String, Object> credentials() {
Map<String, Object> request = new LinkedHashMap<>();
request.put("bizId", properties.getBizId());
request.put("apiKey", properties.getApiKey());
return request;
}
private JsonNode post(String path, Map<String, Object> request) {
try {
String baseUrl = properties.getBaseUrl().replaceAll("/+$", "");
ExternalApiResponse response = externalApiClient.post(baseUrl + path,
Map.of("Content-Type", "application/json; charset=utf-8", "Accept", "application/json"),
objectMapper.writeValueAsString(request));
if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
throw providerError();
}
JsonNode root = objectMapper.readTree(response.getBody());
if (root == null || !root.isObject() || !root.path("code").isTextual()) {
throw invalidResponse();
}
if ("/template/list".equals(path) && "508".equals(root.path("code").asText())) {
var empty = objectMapper.createObjectNode();
empty.put("totalCount", 0);
empty.put("totalPage", 0);
empty.put("currentPage", 0);
empty.putObject("data").putArray("list");
return empty;
}
if (!"200".equals(root.path("code").asText())) {
throw providerError();
}
if (!root.path("data").isObject()) {
throw invalidResponse();
}
return root;
} catch (BusinessException e) {
throw e;
} catch (JsonProcessingException e) {
throw invalidResponse();
} catch (RuntimeException e) {
for (Throwable cause = e; cause != null; cause = cause.getCause()) {
if (cause instanceof HttpTimeoutException) {
throw BusinessException.of(HttpStatus.GATEWAY_TIMEOUT, "KKO_TEMPLATE_TIMEOUT",
"알림톡 템플릿 조회 시간이 초과되었습니다.");
}
}
throw providerError();
}
}
public static BusinessException invalidResponse() {
return BusinessException.of(HttpStatus.BAD_GATEWAY, "KKO_TEMPLATE_INVALID_RESPONSE",
"알림톡 템플릿 조회 응답이 올바르지 않습니다.");
}
private static BusinessException providerError() {
return BusinessException.of(HttpStatus.BAD_GATEWAY, "KKO_TEMPLATE_PROVIDER_ERROR",
"알림톡 템플릿을 조회하지 못했습니다.");
}
}

View File

@@ -5,14 +5,18 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.kri.common.feature.http.ExternalApiClient; import com.kri.common.feature.http.ExternalApiClient;
import com.kri.common.feature.http.ExternalApiMultipartPart;
import com.kri.common.feature.http.ExternalApiResponse; import com.kri.common.feature.http.ExternalApiResponse;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnErrorDto; import com.kri.notihub.server.common.external.pringo.dto.PringoReturnErrorDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnItemDto; import com.kri.notihub.server.common.external.pringo.dto.PringoReturnItemDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnRequestDto; import com.kri.notihub.server.common.external.pringo.dto.PringoReturnRequestDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnResponseDto; import com.kri.notihub.server.common.external.pringo.dto.PringoReturnResponseDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonSendRequestDto; import com.kri.notihub.server.common.external.pringo.dto.PringoSendRequestDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonSendResponseDto; import com.kri.notihub.server.common.external.pringo.dto.PringoSendResponseDto;
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -25,23 +29,23 @@ public class PringoApiClient {
private final ExternalApiClient externalApiClient = new ExternalApiClient(); private final ExternalApiClient externalApiClient = new ExternalApiClient();
private final ObjectMapper objectMapper = new ObjectMapper(); private final ObjectMapper objectMapper = new ObjectMapper();
@Value("${kri.api.pringo.url}") @Value("${kri.api.pringo.url}")
private String pringoBaseUrl; private String pringoBaseUrl;
@Value("${kri.api.pringo.apiKey}") @Value("${kri.api.pringo.apiKey}")
private String apiKey; private String apiKey;
@Value("${kri.api.pringo.template-id}") @Value("${kri.api.pringo.template-id}")
private String templateId; private String templateId;
/** /**
* Pringo 자동메일 Json 발송 POST {pringoBaseUrl}/json-send * Pringo automatic email JSON send POST {pringoBaseUrl}/json-send.
*/ */
public PringoJsonSendResponseDto jsonSend(PringoJsonSendRequestDto request) { public PringoSendResponseDto jsonSend(PringoSendRequestDto request) {
String url = String.format("%s/json-send", pringoBaseUrl); String url = String.format("%s/json-send", pringoBaseUrl);
// defaults 주입
request.applyDefaults(apiKey, templateId); request.applyDefaults(apiKey, templateId);
// 필수값 검증(Pringo 실패 케이스 사전 차단)
request.validateRequired(); request.validateRequired();
Map<String, String> headers = new HashMap<>(); Map<String, String> headers = new HashMap<>();
@@ -52,17 +56,44 @@ public class PringoApiClient {
String body = objectMapper.writeValueAsString(request); String body = objectMapper.writeValueAsString(request);
ExternalApiResponse response = externalApiClient.post(url, headers, body); ExternalApiResponse response = externalApiClient.post(url, headers, body);
return objectMapper.readValue(response.getBody(), PringoJsonSendResponseDto.class); return objectMapper.readValue(response.getBody(), PringoSendResponseDto.class);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
// 프로젝트 스타일에 맞게 BusinessException으로 바꿔도 됨
throw new IllegalStateException("Failed to call Pringo json-send API.", e); throw new IllegalStateException("Failed to call Pringo json-send API.", e);
} }
} }
/** /**
* 편의 메서드: vars 포함해서 바로 발송 * Pringo automatic email parameter send POST {pringoBaseUrl}/parameter-send.
*/ */
public PringoJsonSendResponseDto jsonSend( public PringoSendResponseDto parameterSend(PringoSendRequestDto request) {
String url = String.format("%s/parameter-send", pringoBaseUrl);
request.applyDefaults(apiKey, templateId);
request.validateRequired();
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
try {
List<ExternalApiMultipartPart> parts = new ArrayList<>();
addFormField(parts, "api_key", request.getApiKey());
addFormField(parts, "template_id", request.getTemplateId());
addFormField(parts, "sender", request.getSender());
addFormField(parts, "sender_name", request.getSenderName());
addFormField(parts, "recipient_name", request.getRecipientName());
addFormField(parts, "subject", request.getSubject());
addFormField(parts, "body", request.getBody());
addFormField(parts, "user_info", objectMapper.writeValueAsString(buildUserInfo(request)));
addFileParts(parts, request.getAttachments());
ExternalApiResponse response = externalApiClient.postMultipart(url, headers, parts);
return objectMapper.readValue(response.getBody(), PringoSendResponseDto.class);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Failed to call Pringo parameter-send API.", e);
}
}
public PringoSendResponseDto jsonSend(
String sender, String sender,
String senderName, String senderName,
String recipient, String recipient,
@@ -71,7 +102,7 @@ public class PringoApiClient {
String htmlBody, String htmlBody,
Map<String, Object> vars Map<String, Object> vars
) { ) {
PringoJsonSendRequestDto req = PringoJsonSendRequestDto.builder() PringoSendRequestDto req = PringoSendRequestDto.builder()
.sender(sender) .sender(sender)
.senderName(senderName) .senderName(senderName)
.recipient(recipient) .recipient(recipient)
@@ -88,9 +119,9 @@ public class PringoApiClient {
} }
/** /**
* Pringo 자동메일 Json 조회 POST {pringoBaseUrl}/json-return * Pringo automatic email JSON return POST {pringoBaseUrl}/json-return.
*/ */
public PringoJsonReturnResponseDto jsonReturn(PringoJsonReturnRequestDto request) { public PringoReturnResponseDto jsonReturn(PringoReturnRequestDto request) {
String url = String.format("%s/json-return", pringoBaseUrl); String url = String.format("%s/json-return", pringoBaseUrl);
request.applyDefaults(apiKey, templateId); request.applyDefaults(apiKey, templateId);
@@ -104,11 +135,9 @@ public class PringoApiClient {
String body = objectMapper.writeValueAsString(request); String body = objectMapper.writeValueAsString(request);
ExternalApiResponse response = externalApiClient.post(url, headers, body); ExternalApiResponse response = externalApiClient.post(url, headers, body);
// 응답은 항상 배열 형태
JsonNode root = objectMapper.readTree(response.getBody()); JsonNode root = objectMapper.readTree(response.getBody());
if (root == null || !root.isArray() || root.size() == 0) { if (root == null || !root.isArray() || root.size() == 0) {
// 비정상/빈 응답 방어 return PringoReturnResponseDto.builder()
return PringoJsonReturnResponseDto.builder()
.itemList(List.of()) .itemList(List.of())
.error(PringoJsonReturnErrorDtoBuilder.noResultFallback()) .error(PringoJsonReturnErrorDtoBuilder.noResultFallback())
.build(); .build();
@@ -116,23 +145,21 @@ public class PringoApiClient {
JsonNode first = root.get(0); JsonNode first = root.get(0);
// 실패 형태 판별: result/msg가 있으면 오류 DTO로 본다
if (first.has("result") && first.has("msg")) { if (first.has("result") && first.has("msg")) {
PringoJsonReturnErrorDto err = objectMapper.convertValue(first, PringoReturnErrorDto err = objectMapper.convertValue(first,
PringoJsonReturnErrorDto.class); PringoReturnErrorDto.class);
return PringoJsonReturnResponseDto.builder() return PringoReturnResponseDto.builder()
.itemList(List.of()) .itemList(List.of())
.error(err) .error(err)
.build(); .build();
} }
// 성공 형태: row 리스트 List<PringoReturnItemDto> items = objectMapper.convertValue(
List<PringoJsonReturnItemDto> items = objectMapper.convertValue( root, new TypeReference<List<PringoReturnItemDto>>() {
root, new TypeReference<List<PringoJsonReturnItemDto>>() {
} }
); );
return PringoJsonReturnResponseDto.builder() return PringoReturnResponseDto.builder()
.itemList(items) .itemList(items)
.error(null) .error(null)
.build(); .build();
@@ -142,31 +169,62 @@ public class PringoApiClient {
} }
} }
/** public PringoReturnResponseDto jsonReturn(String returnKey) {
* 편의 메서드: returnKey만으로 조회 PringoReturnRequestDto req = PringoReturnRequestDto.builder()
*/
public PringoJsonReturnResponseDto jsonReturn(String returnKey) {
PringoJsonReturnRequestDto req = PringoJsonReturnRequestDto.builder()
.returnKey(returnKey) .returnKey(returnKey)
.build(); .build();
return jsonReturn(req); return jsonReturn(req);
} }
/** public PringoReturnResponseDto jsonReturn(long returnKey) {
* 편의 메서드: long도 지원
*/
public PringoJsonReturnResponseDto jsonReturn(long returnKey) {
return jsonReturn(Long.toString(returnKey)); return jsonReturn(Long.toString(returnKey));
} }
// 내부 fallback builder (원하시면 별도 클래스로 분리) private void addFormField(List<ExternalApiMultipartPart> parts, String name, String value) {
if (value == null) {
return;
}
parts.add(ExternalApiMultipartPart.formField(name, value));
}
private void addFileParts(
List<ExternalApiMultipartPart> parts,
List<EmailAttachmentDto> attachments
) {
if (attachments == null || attachments.isEmpty()) {
return;
}
if (attachments.size() > 5) {
throw new IllegalArgumentException("Pringo attachments must not exceed 5 files.");
}
for (EmailAttachmentDto attachment : attachments) {
if (attachment.content().length >= 1_000_000) {
throw new IllegalArgumentException(
"Pringo attachment must be smaller than 1 MB: " + attachment.fileName());
}
parts.add(ExternalApiMultipartPart.file(
"files",
attachment.fileName(),
attachment.contentType(),
attachment.content()
));
}
}
private Map<String, Object> buildUserInfo(PringoSendRequestDto request) {
Map<String, Object> recipientInfo = new LinkedHashMap<>();
recipientInfo.put("alternates", request.getVars() == null ? Map.of() : request.getVars());
Map<String, Object> userInfo = new LinkedHashMap<>();
userInfo.put(request.getRecipient(), recipientInfo);
return userInfo;
}
private static final class PringoJsonReturnErrorDtoBuilder { private static final class PringoJsonReturnErrorDtoBuilder {
static PringoJsonReturnErrorDto noResultFallback() { static PringoReturnErrorDto noResultFallback() {
PringoJsonReturnErrorDto e = new PringoJsonReturnErrorDto(); return new PringoReturnErrorDto(null, null, "0", "응답이 비어 있습니다.");
e.setResult("0");
e.setMsg("응답이 비어 있습니다.");
return e;
} }
} }
} }

View File

@@ -1,26 +0,0 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PringoJsonReturnErrorDto {
private String type;
@JsonProperty("typeAlias")
private String typeAlias;
/**
* 예: "0"
*/
private String result;
private String msg;
public boolean isNoResult() {
return "0".equals(result);
}
}

View File

@@ -1,44 +0,0 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PringoJsonReturnItemDto {
@JsonProperty("No")
private Integer no;
@JsonProperty("return_key")
private Long returnKey;
@JsonProperty("email")
private String email;
/**
* "O" / "X"
*/
@JsonProperty("open")
private String open;
/**
* "O" / "X"
*/
@JsonProperty("send_success")
private String sendSuccess;
/**
* "yyyy-MM-dd HH:mm:ss" (문자열로 보관 권장)
*/
@JsonProperty("send_time")
private String sendTime;
/**
* ex) "250"
*/
@JsonProperty("status")
private String status;
}

View File

@@ -1,34 +0,0 @@
package com.kri.notihub.server.common.external.pringo.dto;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PringoJsonReturnResponseDto {
/**
* 조회 결과 row들(성공 시)
*/
private List<PringoJsonReturnItemDto> itemList;
/**
* 조회 실패/없음(실패 시)
*/
private PringoJsonReturnErrorDto error;
public boolean isSuccess() {
return itemList != null && !itemList.isEmpty();
}
public boolean isNoResult() {
return error != null && error.isNoResult();
}
}

View File

@@ -1,34 +0,0 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PringoJsonSendResponseDto {
private String type;
@JsonProperty("typeAlias")
private String typeAlias;
/**
* 성공: 1 실패: "-1" (API가 숫자/문자 둘 다 줄 수 있으니 String으로 받는 편이 안전)
*/
@JsonProperty("result")
private String result;
@JsonProperty("msg")
private String msg;
/**
* 응답 JSON 오타 그대로 "retrun_key"
*/
@JsonProperty("retrun_key")
private Long returnKey;
public boolean isSuccess() {
return "1".equals(result);
}
}

View File

@@ -0,0 +1,21 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public record PringoReturnErrorDto(
String type,
@JsonProperty("typeAlias")
String typeAlias,
/**
* 예: "0"
*/
String result,
String msg
) {
public boolean isNoResult() {
return "0".equals(result);
}
}

View File

@@ -0,0 +1,39 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public record PringoReturnItemDto(
@JsonProperty("No")
Integer no,
@JsonProperty("return_key")
Long returnKey,
@JsonProperty("email")
String email,
/**
* "O" / "X"
*/
@JsonProperty("open")
String open,
/**
* "O" / "X"
*/
@JsonProperty("send_success")
String sendSuccess,
/**
* "yyyy-MM-dd HH:mm:ss" (문자열로 보관 권장)
*/
@JsonProperty("send_time")
String sendTime,
/**
* ex) "250"
*/
@JsonProperty("status")
String status
) {
}

View File

@@ -13,7 +13,7 @@ import lombok.Setter;
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class PringoJsonReturnRequestDto { public class PringoReturnRequestDto {
@JsonProperty("api_key") @JsonProperty("api_key")
private String apiKey; private String apiKey;

View File

@@ -0,0 +1,25 @@
package com.kri.notihub.server.common.external.pringo.dto;
import java.util.List;
import lombok.Builder;
@Builder
public record PringoReturnResponseDto(
/**
* 조회 결과 row들(성공 시)
*/
List<PringoReturnItemDto> itemList,
/**
* 조회 실패/없음(실패 시)
*/
PringoReturnErrorDto error
) {
public boolean isSuccess() {
return itemList != null && !itemList.isEmpty();
}
public boolean isNoResult() {
return error != null && error.isNoResult();
}
}

View File

@@ -4,8 +4,10 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
import com.kri.notihub.server.dto.template.TemplateBasicDto; import com.kri.notihub.server.dto.template.TemplateBasicDto;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
@@ -20,13 +22,13 @@ import lombok.Setter;
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class PringoJsonSendRequestDto { public class PringoSendRequestDto {
private static final Set<String> RESERVED_KEYS = Set.of( private static final Set<String> RESERVED_KEYS = Set.of(
"api_key", "template_id", "api_key", "template_id",
"sender", "sender_name", "sender", "sender_name",
"recipient", "recipient_name", "recipient", "recipient_name",
"subject", "body" "subject", "body", "files"
); );
@JsonProperty("api_key") @JsonProperty("api_key")
@@ -61,6 +63,10 @@ public class PringoJsonSendRequestDto {
*/ */
private String body; private String body;
@JsonIgnore
@Builder.Default
private List<EmailAttachmentDto> attachments = List.of();
/** /**
* Pringo 템플릿 치환용 동적 변수 예) body: "...[$jstest]..." vars: {"jstest":"테스트 지롱~"} * Pringo 템플릿 치환용 동적 변수 예) body: "...[$jstest]..." vars: {"jstest":"테스트 지롱~"}
*/ */
@@ -71,19 +77,19 @@ public class PringoJsonSendRequestDto {
/** /**
* TemplateBasicDto -> Pringo 발송 DTO 기본 매핑 - recipient/recipientName 은 템플릿에 없으므로 여기서는 비워두고 이후 세팅 * TemplateBasicDto -> Pringo 발송 DTO 기본 매핑 - recipient/recipientName 은 템플릿에 없으므로 여기서는 비워두고 이후 세팅
*/ */
public static PringoJsonSendRequestDto from(TemplateBasicDto template, String sendName, public static PringoSendRequestDto from(TemplateBasicDto template, String sendName,
String sendEmail) { String sendEmail) {
return from(template, sendName, sendEmail, null, null); return from(template, sendName, sendEmail, null, null);
} }
public static PringoJsonSendRequestDto from(TemplateBasicDto template, String sendName, public static PringoSendRequestDto from(TemplateBasicDto template, String sendName,
String sendEmail, String recipient, String recipientName) { String sendEmail, String recipient, String recipientName) {
Objects.requireNonNull(template, "template is required"); Objects.requireNonNull(template, "template is required");
String sender = sendEmail != null && !sendEmail.isBlank() ? sendEmail : template.getSendEml(); String sender = sendEmail != null && !sendEmail.isBlank() ? sendEmail : template.getSendEml();
String senderName = sendName != null && !sendName.isBlank() ? sendName : template.getSendNm(); String senderName = sendName != null && !sendName.isBlank() ? sendName : template.getSendNm();
return PringoJsonSendRequestDto.builder() return PringoSendRequestDto.builder()
.sender(sender) .sender(sender)
.senderName(senderName) .senderName(senderName)
.recipient(recipient) .recipient(recipient)
@@ -93,7 +99,7 @@ public class PringoJsonSendRequestDto {
.build(); .build();
} }
public static PringoJsonSendRequestDto of( public static PringoSendRequestDto of(
String sender, String sender,
String senderName, String senderName,
String recipient, String recipient,
@@ -101,7 +107,7 @@ public class PringoJsonSendRequestDto {
String subject, String subject,
String htmlBody String htmlBody
) { ) {
return PringoJsonSendRequestDto.builder() return PringoSendRequestDto.builder()
.sender(sender) .sender(sender)
.senderName(senderName) .senderName(senderName)
.recipient(recipient) .recipient(recipient)
@@ -132,8 +138,8 @@ public class PringoJsonSendRequestDto {
setAny(key, value); setAny(key, value);
} }
public PringoJsonSendRequestDto copy() { public PringoSendRequestDto copy() {
return PringoJsonSendRequestDto.builder() return PringoSendRequestDto.builder()
.apiKey(this.apiKey) .apiKey(this.apiKey)
.templateId(this.templateId) .templateId(this.templateId)
.sender(this.sender) .sender(this.sender)
@@ -142,6 +148,7 @@ public class PringoJsonSendRequestDto {
.recipientName(this.recipientName) .recipientName(this.recipientName)
.subject(this.subject) .subject(this.subject)
.body(this.body) .body(this.body)
.attachments(this.attachments == null ? List.of() : List.copyOf(this.attachments))
.vars(new java.util.LinkedHashMap<>(this.vars)) .vars(new java.util.LinkedHashMap<>(this.vars))
.build(); .build();
} }
@@ -149,7 +156,7 @@ public class PringoJsonSendRequestDto {
/** /**
* recipient를 나중에 세팅할 수 있게 체이닝용 * recipient를 나중에 세팅할 수 있게 체이닝용
*/ */
public PringoJsonSendRequestDto withRecipient(String recipient, String recipientName) { public PringoSendRequestDto withRecipient(String recipient, String recipientName) {
this.recipient = recipient; this.recipient = recipient;
this.recipientName = recipientName; this.recipientName = recipientName;
return this; return this;

View File

@@ -0,0 +1,31 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
public record PringoSendResponseDto(
String type,
@JsonProperty("typeAlias")
String typeAlias,
/**
* Success: 1, failure: -1. Keep String because the API can return numeric or string values.
*/
@JsonProperty("result")
String result,
@JsonProperty("msg")
String msg,
/**
* Pringo send response key. Accepts the legacy misspelled key for compatibility.
*/
@JsonProperty("return_key")
@JsonAlias("retrun_key")
Long returnKey
) {
public boolean isSuccess() {
return "1".equals(result);
}
}

View File

@@ -1,11 +1,16 @@
package com.kri.notihub.server.common.util; package com.kri.notihub.server.common.util;
import static com.kri.notihub.server.common.consts.NotihubConst.SMS_TYPE_CODE_LIST;
import com.kri.common.feature.util.StringUtil; import com.kri.common.feature.util.StringUtil;
import com.kri.common.feature.web.BusinessException;
import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.dto.template.TemplateBasicDto; import com.kri.notihub.server.dto.template.TemplateBasicDto;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Safelist; import org.jsoup.safety.Safelist;
public final class TemplateContentSanitizer { public final class TemplateContentSanitizer {
@@ -13,10 +18,46 @@ public final class TemplateContentSanitizer {
// 필요 시 시스템 정책에 맞게 조정 // 필요 시 시스템 정책에 맞게 조정
// (KOR 환경에서 SMS는 바이트 기준으로 제한을 두는 경우가 흔함) // (KOR 환경에서 SMS는 바이트 기준으로 제한을 두는 경우가 흔함)
private static final int SMS_MAX_BYTES_UTF8 = 90; private static final int SMS_MAX_BYTES_UTF8 = 90;
public static final int SMS_TITLE_MAX_LENGTH = 64;
private static final Pattern ESCAPED_QRCODE_OPEN_TAG_PATTERN =
Pattern.compile("(?i)&lt;\\s*qrcode\\b([\\s\\S]*?)/?\\s*&gt;");
private static final Pattern ESCAPED_QRCODE_CLOSE_TAG_PATTERN =
Pattern.compile("(?i)&lt;/\\s*qrcode\\s*&gt;");
private static final Safelist EMAIL_HTML_SAFELIST = createEmailHtmlSafelist();
private TemplateContentSanitizer() { private TemplateContentSanitizer() {
} }
private static Safelist createEmailHtmlSafelist() {
return Safelist.relaxed()
.addTags("mark", "hr")
.addAttributes("mark", "style", "data-color")
.addAttributes("hr", "style", "width", "size", "color", "align", "noshade")
.addAttributes("div", "style", "align")
.addAttributes("span", "style")
.addAttributes("p", "style")
.addAttributes("b", "style")
.addAttributes("table", "style", "width", "height", "cellpadding", "cellspacing",
"border", "align", "bgcolor", "role")
.addAttributes("tbody", "style", "align", "valign")
.addAttributes("tr", "style", "align", "valign", "bgcolor", "height")
.addAttributes("td", "style", "align", "valign", "bgcolor", "width", "height",
"colspan", "rowspan")
.addAttributes("th", "style", "align", "valign", "bgcolor", "width", "height",
"colspan", "rowspan", "scope")
.addAttributes("a", "style", "target", "rel")
.addAttributes("img", "style", "loading", "src", "width", "height", "alt", "title",
"align", "usemap")
.addTags("map", "area")
.addAttributes("map", "name", "id")
.addAttributes("area", "shape", "coords", "href", "alt", "title", "target")
.addTags("qrcode")
.addAttributes("qrcode", "src", "width", "height", "alt")
.addProtocols("a", "href", "http", "https", "mailto", "tel")
.addProtocols("area", "href", "http", "https", "mailto", "tel")
.addProtocols("img", "src", "http", "https");
}
private static int utf8ByteLength(String s) { private static int utf8ByteLength(String s) {
if (s == null) { if (s == null) {
return 0; return 0;
@@ -41,6 +82,17 @@ public final class TemplateContentSanitizer {
return trimmed.substring(0, end); return trimmed.substring(0, end);
} }
/**
* 문자 제목은 평문 변환 후 최대 64자(코드포인트 기준)까지만 허용
*/
private static void validateSmsTitleLength(String title) {
if (title != null
&& title.codePointCount(0, title.length()) > SMS_TITLE_MAX_LENGTH) {
throw BusinessException.badRequest("TITLE_TOO_LONG",
"문자 제목은 " + SMS_TITLE_MAX_LENGTH + "자 이하로 입력해야 합니다.");
}
}
/** /**
* 제어문자 제거(개행/탭은 옵션), 줄바꿈은 \n 으로 통일 * 제어문자 제거(개행/탭은 옵션), 줄바꿈은 \n 으로 통일
*/ */
@@ -66,17 +118,42 @@ public final class TemplateContentSanitizer {
return null; return null;
} }
Safelist safelist = Safelist.relaxed() html = normalizeQrcodeSrc(normalizeEscapedQrcodeTags(html));
.addProtocols("a", "href", "http", "https", "mailto")
.addProtocols("img", "src", "http", "https");
Document.OutputSettings out = new Document.OutputSettings().prettyPrint(false); Document.OutputSettings out = new Document.OutputSettings().prettyPrint(false);
String cleaned = Jsoup.clean(html, "", safelist, out); String cleaned = Jsoup.clean(html, "", EMAIL_HTML_SAFELIST, out);
cleaned = normalizeControls(cleaned, true); cleaned = normalizeControls(cleaned, true);
return cleaned.trim(); return cleaned.trim();
} }
private static String normalizeEscapedQrcodeTags(String html) {
String normalized = ESCAPED_QRCODE_OPEN_TAG_PATTERN.matcher(html)
.replaceAll("<qrcode$1>");
return ESCAPED_QRCODE_CLOSE_TAG_PATTERN.matcher(normalized).replaceAll("");
}
private static String normalizeQrcodeSrc(String html) {
Document doc = Jsoup.parseBodyFragment(html);
doc.outputSettings(new Document.OutputSettings().prettyPrint(false));
for (Element qrcode : doc.select("qrcode[src]")) {
String src = qrcode.attr("src").trim();
if (src.isEmpty() || startsWithHttpScheme(src)) {
continue;
}
qrcode.attr("src", src.startsWith("//") ? "https:" + src : "https://" + src);
}
return doc.body().html();
}
private static boolean startsWithHttpScheme(String value) {
return value.regionMatches(true, 0, "http://", 0, "http://".length())
|| value.regionMatches(true, 0, "https://", 0, "https://".length());
}
/** /**
* SMS/LMS body: HTML -> 평문(개행 보존) * SMS/LMS body: HTML -> 평문(개행 보존)
*/ */
@@ -103,6 +180,24 @@ public final class TemplateContentSanitizer {
return text.trim(); return text.trim();
} }
public static SendType resolveSendType(SendType originalType, String title, String body,
String attachments) {
if (!SMS_TYPE_CODE_LIST.contains(originalType.getCode())) {
return originalType;
}
if (attachments != null && !attachments.isBlank()) {
return SendType.MMS;
}
return determineSms(title, body);
}
public static SendType determineSms(String outTitle, String outBody){
boolean hasTitle = StringUtil.hasText(outTitle);
boolean isLargeBody = utf8ByteLength(outBody) >= SMS_MAX_BYTES_UTF8;
return hasTitle || isLargeBody ? SendType.LMS : SendType.SMS;
}
/** /**
* 1) tmplatTy별 치환/정리 2) (SMS/LMS_MMS) 치환 후 길이 기반으로 타입 재결정 - SMS는 제목 저장 안 함 - LMS_MMS는 본문 짧아도 제목 * 1) tmplatTy별 치환/정리 2) (SMS/LMS_MMS) 치환 후 길이 기반으로 타입 재결정 - SMS는 제목 저장 안 함 - LMS_MMS는 본문 짧아도 제목
* 있으면 그대로 유지 * 있으면 그대로 유지
@@ -123,35 +218,20 @@ public final class TemplateContentSanitizer {
outBody = sanitizeEmailHtml(outBody); outBody = sanitizeEmailHtml(outBody);
} }
case SMS, LMS_MMS, KKO_AT -> { case KKO_AT -> {
// 카카오 등록 원문과 일치하도록 미리보기 제목과 본문을 변형하지 않는다.
}
case SMS, LMS, MMS -> {
// 평문화 // 평문화
outTitle = htmlToPlainTextPreserveNewlines(outTitle); outTitle = htmlToPlainTextPreserveNewlines(outTitle);
outTitle = truncateTo128CodePoints(outTitle); validateSmsTitleLength(outTitle);
outBody = htmlToPlainTextPreserveNewlines(outBody); outBody = htmlToPlainTextPreserveNewlines(outBody);
} }
} }
if (type == SendType.KKO_AT) { if (SMS_TYPE_CODE_LIST.contains(type)) {
outTitle = null; type = determineSms(outTitle, outBody);
} else if (type == SendType.SMS) {
// SMS는 제목 저장 안 함
outTitle = null;
// 2) 타입 재결정
// 본문이 SMS 한도 초과면 LMS_MMS로 승격
if (utf8ByteLength(outBody) > SMS_MAX_BYTES_UTF8) {
type = SendType.LMS_MMS;
}
} else if (type == SendType.LMS_MMS) {
boolean hasTitle = StringUtil.hasText(outTitle);
// "LMS_MMS인데 본문이 짧으면 SMS로 강등"이 기본인데,
// 단, 제목이 있으면 본문이 짧아도 LMS_MMS 유지
if (!hasTitle && utf8ByteLength(outBody) <= SMS_MAX_BYTES_UTF8) {
type = SendType.SMS;
outTitle = null; // SMS는 제목 저장 안 함
}
} }
return new SanitizedTemplate(type, outTitle, outBody); return new SanitizedTemplate(type, outTitle, outBody);

View File

@@ -0,0 +1,36 @@
package com.kri.notihub.server.config;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.HashSet;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Getter
@Setter
@Validated
@Component
@ConfigurationProperties(prefix = "notihub.kakao")
public class KkoTemplateProperties {
@NotBlank
private String baseUrl;
@NotBlank
private String bizId;
@NotBlank
private String apiKey;
@NotEmpty
private List<@NotBlank String> templateStatuses;
@AssertTrue(message = "template-statuses must not contain duplicate values")
public boolean isTemplateStatusesUnique() {
return templateStatuses == null
|| new HashSet<>(templateStatuses).size() == templateStatuses.size();
}
}

View File

@@ -0,0 +1,43 @@
package com.kri.notihub.server.config;
import jakarta.annotation.PostConstruct;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Getter
@Setter
@Validated
@Component
@ConfigurationProperties(prefix = "kri.sms.verification")
public class PhoneVerificationProperties {
public static final String CODE_PLACEHOLDER = "#{verificationCode}";
@Min(1)
private int expireMinutes = 5;
@Min(1)
private int maxAttempts = 5;
@NotBlank
private String messageTemplate = "인증번호는 [#{verificationCode}] 입니다.";
@PostConstruct
void validateMessageTemplate() {
int first = messageTemplate.indexOf(CODE_PLACEHOLDER);
int last = messageTemplate.lastIndexOf(CODE_PLACEHOLDER);
if (first < 0 || first != last) {
throw new IllegalStateException(
"kri.sms.verification.message-template must contain #{verificationCode} exactly once");
}
}
public String renderMessage(String verificationCode) {
return messageTemplate.replace(CODE_PLACEHOLDER, verificationCode);
}
}

View File

@@ -0,0 +1,30 @@
package com.kri.notihub.server.controller;
import com.kri.notihub.server.dto.verification.PhoneVerificationRequestDto;
import com.kri.notihub.server.dto.verification.PhoneVerificationResponseDto;
import com.kri.notihub.server.service.PhoneVerificationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/phone-verifications")
@RequiredArgsConstructor
@Tag(name = "Phone Verification", description = "휴대전화번호 인증 API")
public class PhoneVerificationController {
private final PhoneVerificationService phoneVerificationService;
@Operation(summary = "휴대전화번호 인증")
@PostMapping("/verify")
public PhoneVerificationResponseDto verify(
@Valid @RequestBody PhoneVerificationRequestDto request
) {
return phoneVerificationService.verify(request);
}
}

View File

@@ -4,21 +4,35 @@ import com.kri.common.feature.web.RequestUserContext;
import com.kri.common.feature.web.page.PageRequestDto; import com.kri.common.feature.web.page.PageRequestDto;
import com.kri.common.feature.web.page.PageResponseDto; import com.kri.common.feature.web.page.PageResponseDto;
import com.kri.notihub.server.common.consts.NotihubConst; import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.ChannelType;
import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.dto.report.BulkSendInfoDto; import com.kri.notihub.server.dto.report.BulkSendInfoDto;
import com.kri.notihub.server.dto.report.ReportExcelResponseDto; import com.kri.notihub.server.dto.report.ReportExcelResponseDto;
import com.kri.notihub.server.dto.report.SendInfoDto; import com.kri.notihub.server.dto.report.SendCostSummaryRequestDto;
import com.kri.notihub.server.dto.report.SendCostSummaryWithItrntPrjctDto;
import com.kri.notihub.server.dto.report.SendResultLastWithSidDto;
import com.kri.notihub.server.dto.report.SendResultCodeDto;
import com.kri.notihub.server.dto.report.SendResultInfoDto;
import com.kri.notihub.server.dto.report.SendResultSummaryRequestDto;
import com.kri.notihub.server.dto.report.SendResultSummaryResponseDto;
import com.kri.notihub.server.service.ReportService; import com.kri.notihub.server.service.ReportService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List; import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@@ -29,6 +43,23 @@ public class ReportController {
private final ReportService reportService; private final ReportService reportService;
@Operation(summary = "발송 결과 코드 목록 조회")
@GetMapping("/send-result-code")
public List<SendResultCodeDto> getSendResultCodeList() {
return reportService.getSendResultCodeList();
}
@Operation(summary = "발송 결과 목록 조회")
@GetMapping("/send-result/{sid}/{prjctCd}/{reqstSvc}")
public List<SendResultInfoDto> getSendResultList(
@PathVariable String sid,
@PathVariable String prjctCd,
@PathVariable String reqstSvc,
@RequestParam(required = false) ChannelType channelTy
) {
return reportService.getSendResultList(sid, prjctCd, reqstSvc, channelTy);
}
@Operation(summary = "대량발송 리스트 조회") @Operation(summary = "대량발송 리스트 조회")
@GetMapping("/bulk-list/{sendTy}/{reqstSvc}/{prjctCd}") @GetMapping("/bulk-list/{sendTy}/{reqstSvc}/{prjctCd}")
public List<BulkSendInfoDto> getBulkSendList( public List<BulkSendInfoDto> getBulkSendList(
@@ -44,7 +75,7 @@ public class ReportController {
@Operation(summary = "대량발송 결과 조회") @Operation(summary = "대량발송 결과 조회")
@PostMapping("/bulk-detail/{bulkSendKey}") @PostMapping("/bulk-detail/{bulkSendKey}")
public PageResponseDto<SendInfoDto> getBulkSendDetail( public PageResponseDto<SendResultInfoDto> getBulkSendDetail(
@PathVariable String bulkSendKey, @PathVariable String bulkSendKey,
@Valid @RequestBody PageRequestDto pageReq @Valid @RequestBody PageRequestDto pageReq
) { ) {
@@ -56,4 +87,57 @@ public class ReportController {
public ReportExcelResponseDto getBulkSendDetailExcel(@PathVariable String bulkSendKey) { public ReportExcelResponseDto getBulkSendDetailExcel(@PathVariable String bulkSendKey) {
return reportService.getBulkSendDetailExcel(bulkSendKey); return reportService.getBulkSendDetailExcel(bulkSendKey);
} }
@Operation(summary = "발송 결과 축약 조회")
@PostMapping("/send-result-summary")
public List<SendResultSummaryResponseDto> getSendResultSummary(
@Valid @RequestBody SendResultSummaryRequestDto req
) {
return reportService.getSendResultSummary(req);
}
@Operation(summary = "인트라넷 프로젝트별 발송 비용 요약 조회")
@PostMapping("/cost/summary-itrnt-prjct")
public List<SendCostSummaryWithItrntPrjctDto> getSendCostSummaryWithItrntPrjct(
@Valid @RequestBody SendCostSummaryRequestDto req
) {
return reportService.getSendCostSummaryWithItrntPrjct(req);
}
@Operation(summary = "인트라넷 프로젝트별 발송 비용 요약 다운로드")
@PostMapping("/cost/summary-itrnt-prjct/excel")
public ReportExcelResponseDto getSendCostSummaryWithItrntPrjctExcel(
@Valid @RequestBody SendCostSummaryRequestDto req
) {
return reportService.getSendCostSummaryWithItrntPrjctExcel(req);
}
@Operation(summary = "인트라넷 프로젝트별 발송 비용 요약 다운로드 For Swagger")
@PostMapping("/cost/summary-itrnt-prjct/excel/swagger")
public ResponseEntity<byte[]> getSendCostSummaryWithItrntPrjctExcelForSwagger(
@Valid @RequestBody SendCostSummaryRequestDto req
) {
ReportExcelResponseDto result = reportService.getSendCostSummaryWithItrntPrjctExcel(req);
byte[] bytes = Base64.getDecoder().decode(result.fileBase64());
String contentDisposition = "attachment; filename*=UTF-8''" +
URLEncoder.encode(result.fileName(), StandardCharsets.UTF_8).replace("+", "%20");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
@Operation(summary = "리스트 별 최종 발송 결과 조회")
@PostMapping("/last/send/{channelTy}/{reqstSvc}/{prjctCd}")
public List<SendResultLastWithSidDto> getSendResultLastWithSid(
@PathVariable ChannelType channelTy,
@PathVariable String reqstSvc,
@PathVariable String prjctCd,
@RequestBody List<String> sids
) {
return reportService.getSendResultLastWithSid(channelTy, reqstSvc, prjctCd, sids);
}
} }

View File

@@ -0,0 +1,38 @@
package com.kri.notihub.server.controller;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.notihub.server.dto.send.SendCancelBulkRequestDto;
import com.kri.notihub.server.dto.send.SendCancelSingleRequestDto;
import com.kri.notihub.server.dto.send.SendCancelResponseDto;
import com.kri.notihub.server.service.SendCancelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/send/cancel")
@RequiredArgsConstructor
@Tag(name = "Send Cancel", description = "예약 발송 취소")
public class SendCancelController {
private final SendCancelService sendCancelService;
@PostMapping("/single")
@Operation(summary = "단건 예약 취소")
public SendCancelResponseDto cancelSingle(
@Valid @RequestBody SendCancelSingleRequestDto request, RequestUserContext ctx) {
return sendCancelService.cancelSingle(request.sendIdx(), ctx);
}
@PostMapping("/bulk")
@Operation(summary = "벌크의 남은 예약 건 취소", description = "이미 시작된 건은 유지하고 취소 가능한 건만 처리")
public SendCancelResponseDto cancelBulk(
@Valid @RequestBody SendCancelBulkRequestDto request, RequestUserContext ctx) {
return sendCancelService.cancelBulk(request.bulkSendKey(), ctx);
}
}

View File

@@ -6,6 +6,7 @@ import com.kri.notihub.server.dto.send.BulkSendResponseDto;
import com.kri.notihub.server.dto.send.EmailPollQueueResponseDto; import com.kri.notihub.server.dto.send.EmailPollQueueResponseDto;
import com.kri.notihub.server.dto.send.SendRequestBulkDto; import com.kri.notihub.server.dto.send.SendRequestBulkDto;
import com.kri.notihub.server.dto.send.SendRequestSingleDto; import com.kri.notihub.server.dto.send.SendRequestSingleDto;
import com.kri.notihub.server.dto.send.SendSingleResponseDto;
import com.kri.notihub.server.service.EmailResultPoller; import com.kri.notihub.server.service.EmailResultPoller;
import com.kri.notihub.server.service.SendEmailService; import com.kri.notihub.server.service.SendEmailService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@@ -43,11 +44,11 @@ public class SendEmailController {
@Operation(summary = "이메일 단건 발송") @Operation(summary = "이메일 단건 발송")
@PostMapping("/single") @PostMapping("/single")
public void sendSingle( public SendSingleResponseDto sendSingle(
@Valid @RequestBody SendRequestSingleDto req, @Valid @RequestBody SendRequestSingleDto req,
RequestUserContext ctx RequestUserContext ctx
) { ) {
sendEmailService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId()); return sendEmailService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId());
} }
@Operation(summary = "bulkSendKey 기반 이메일 벌크 발송") @Operation(summary = "bulkSendKey 기반 이메일 벌크 발송")

View File

@@ -6,6 +6,7 @@ import com.kri.notihub.server.dto.send.BulkSendCreateRequestDto;
import com.kri.notihub.server.dto.send.BulkSendResponseDto; import com.kri.notihub.server.dto.send.BulkSendResponseDto;
import com.kri.notihub.server.dto.send.SendRequestBulkDto; import com.kri.notihub.server.dto.send.SendRequestBulkDto;
import com.kri.notihub.server.dto.send.SendRequestSingleDto; import com.kri.notihub.server.dto.send.SendRequestSingleDto;
import com.kri.notihub.server.dto.send.SendSingleResponseDto;
import com.kri.notihub.server.service.BizppurioSendCursorStore; import com.kri.notihub.server.service.BizppurioSendCursorStore;
import com.kri.notihub.server.service.SendKkoAtService; import com.kri.notihub.server.service.SendKkoAtService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@@ -41,11 +42,11 @@ public class SendKkoAtController {
@Operation(summary = "알림톡 단건 발송") @Operation(summary = "알림톡 단건 발송")
@PostMapping("/single") @PostMapping("/single")
public void sendSingle( public SendSingleResponseDto sendSingle(
@Valid @RequestBody SendRequestSingleDto req, @Valid @RequestBody SendRequestSingleDto req,
RequestUserContext ctx RequestUserContext ctx
) { ) {
sendKKoAtService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId()); return sendKKoAtService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId());
} }
@Operation(summary = "bulkSendKey 기반 알림톡 벌크 발송") @Operation(summary = "bulkSendKey 기반 알림톡 벌크 발송")

View File

@@ -5,6 +5,7 @@ import com.kri.notihub.server.dto.send.BulkSendCreateRequestDto;
import com.kri.notihub.server.dto.send.BulkSendResponseDto; import com.kri.notihub.server.dto.send.BulkSendResponseDto;
import com.kri.notihub.server.dto.send.SendRequestBulkDto; import com.kri.notihub.server.dto.send.SendRequestBulkDto;
import com.kri.notihub.server.dto.send.SendRequestSingleDto; import com.kri.notihub.server.dto.send.SendRequestSingleDto;
import com.kri.notihub.server.dto.send.SendSingleResponseDto;
import com.kri.notihub.server.dto.send.BizppurioCursorResponseDto; import com.kri.notihub.server.dto.send.BizppurioCursorResponseDto;
import com.kri.notihub.server.service.SendSmsService; import com.kri.notihub.server.service.SendSmsService;
import com.kri.notihub.server.service.BizppurioSendCursorStore; import com.kri.notihub.server.service.BizppurioSendCursorStore;
@@ -42,11 +43,11 @@ public class SendSmsController {
@Operation(summary = "문자 단건 발송") @Operation(summary = "문자 단건 발송")
@PostMapping("/single") @PostMapping("/single")
public void sendSingle( public SendSingleResponseDto sendSingle(
@Valid @RequestBody SendRequestSingleDto req, @Valid @RequestBody SendRequestSingleDto req,
RequestUserContext ctx RequestUserContext ctx
) { ) {
sendSmsService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId()); return sendSmsService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId());
} }
@Operation(summary = "bulkSendKey 기반 문자 벌크 발송") @Operation(summary = "bulkSendKey 기반 문자 벌크 발송")

View File

@@ -2,25 +2,38 @@ package com.kri.notihub.server.controller;
import com.kri.common.feature.web.RequestUserContext; import com.kri.common.feature.web.RequestUserContext;
import com.kri.notihub.server.common.enums.ChannelType; import com.kri.notihub.server.common.enums.ChannelType;
import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.dto.email.EmailAttachmentDto;
import com.kri.notihub.server.dto.template.KkoTemplateDetailDto;
import com.kri.notihub.server.dto.template.KkoProfileDto;
import com.kri.notihub.server.dto.template.KkoTemplateDetailRequestDto;
import com.kri.notihub.server.dto.template.KkoTemplateListRequestDto;
import com.kri.notihub.server.dto.template.KkoTemplateListResponseDto;
import com.kri.notihub.server.dto.template.TemplateBasicDto; import com.kri.notihub.server.dto.template.TemplateBasicDto;
import com.kri.notihub.server.dto.template.TemplateDto; import com.kri.notihub.server.dto.template.TemplateDto;
import com.kri.notihub.server.dto.template.TemplateSummaryDto; import com.kri.notihub.server.dto.template.TemplateSummaryDto;
import com.kri.notihub.server.service.FileService; import com.kri.notihub.server.service.FileService;
import com.kri.notihub.server.service.TemplateService; import com.kri.notihub.server.service.TemplateService;
import com.kri.notihub.server.service.KkoTemplateService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@@ -32,6 +45,30 @@ public class TemplateController {
private final TemplateService templateService; private final TemplateService templateService;
private final FileService fileService; private final FileService fileService;
private final KkoTemplateService kkoTemplateService;
@Operation(summary = "사용 가능한 알림톡 발신 프로필 조회")
@GetMapping("/kko/profiles")
public List<KkoProfileDto> getKkoProfiles() {
return kkoTemplateService.getProfiles();
}
@Operation(summary = "외부 알림톡 템플릿 목록 조회")
@PostMapping(value = "/kko/list", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public KkoTemplateListResponseDto getKkoTemplateList(
@Valid @RequestBody KkoTemplateListRequestDto request) {
return kkoTemplateService.getList(request.senderKey(), request.keyword());
}
@Operation(summary = "외부 알림톡 템플릿 상세 조회")
@PostMapping(value = "/kko/detail", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public KkoTemplateDetailDto getKkoTemplateDetail(
@Valid @RequestBody KkoTemplateDetailRequestDto request) {
return kkoTemplateService.getDetail(request.senderKey(), request.templateCode());
}
@Operation(summary = "템플릿 목록 조회") @Operation(summary = "템플릿 목록 조회")
@GetMapping("/list/{chnnlTy}/{itrntPrjctCd}") @GetMapping("/list/{chnnlTy}/{itrntPrjctCd}")
@@ -48,50 +85,61 @@ public class TemplateController {
return templateService.getTemplate(tmplatIdx); return templateService.getTemplate(tmplatIdx);
} }
@Operation(summary = "템플릿 생성") @Operation(summary = "템플릿 첨부파일 개별 다운로드")
@PutMapping @GetMapping("/{tmplatIdx}/attachment")
public ResponseEntity<byte[]> downloadAttachment(
@PathVariable long tmplatIdx,
@RequestParam String fileName
) {
EmailAttachmentDto attachment = templateService.downloadAttachment(tmplatIdx, fileName);
String encodedFileName = URLEncoder.encode(attachment.fileName(), StandardCharsets.UTF_8)
.replace("+", "%20");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename*=UTF-8''" + encodedFileName)
.header(HttpHeaders.CACHE_CONTROL, "no-store")
.contentType(MediaType.parseMediaType(attachment.contentType()))
.contentLength(attachment.content().length)
.body(attachment.content());
}
@Operation(summary = "첨부파일을 포함한 템플릿 생성")
@PutMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public TemplateDto createTemplate( public TemplateDto createTemplate(
@Valid @RequestBody TemplateBasicDto template, @Valid @RequestPart("template") TemplateBasicDto template,
@RequestPart(value = "files", required = false) List<MultipartFile> files,
RequestUserContext ctx RequestUserContext ctx
) { ) {
TemplateDto newTmplat = templateService.createTemplate(template.getItrntPrjctCd(), template, return templateService.createTemplate(
ctx.getUserId()); template.getItrntPrjctCd(),
template,
if (template.getTmplatTy() == SendType.EMAIL) { files,
String newHtml = fileService.syncOnSave( ctx.getUserId()
newTmplat.getItrntPrjctCd(),
newTmplat.getTmplatIdx(),
newTmplat.getTmplatBody()
); );
newTmplat.setTmplatBody(newHtml);
templateService.updateTemplateBodyWithCreate(newTmplat);
} }
return newTmplat; @Operation(summary = "바디에 사용하는 이미지 업로드")
}
@Operation(summary = "시나리오 이미지 업로드")
@PutMapping("/body-image/{itrntPrjctCd}") @PutMapping("/body-image/{itrntPrjctCd}")
public String uploadContactSenarioImage(@PathVariable String itrntPrjctCd, public String uploadContactSenarioImage(@PathVariable String itrntPrjctCd,
@RequestParam("file") MultipartFile file) { @RequestParam("file") MultipartFile file) {
return fileService.storeTempFile(itrntPrjctCd, file); return fileService.storeTempFile(itrntPrjctCd, file);
} }
@Operation(summary = "템플릿 수정") @Operation(summary = "첨부파일 변경을 포함한 템플릿 수정")
@PatchMapping @PatchMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public TemplateDto updateTemplate( public TemplateDto updateTemplate(
@Valid @RequestBody TemplateDto template, @Valid @RequestPart("template") TemplateDto template,
@RequestPart(value = "files", required = false) List<MultipartFile> files,
@RequestParam(value = "deleteFileNames", required = false) List<String> deleteFileNames,
RequestUserContext ctx RequestUserContext ctx
) { ) {
String newHtml = fileService.syncOnSave( return templateService.updateTemplate(
template.getItrntPrjctCd(), template,
template.getTmplatIdx(), files,
template.getTmplatBody() deleteFileNames,
ctx.getUserId()
); );
template.setTmplatBody(newHtml);
return templateService.updateTemplate(template, ctx.getUserId());
} }
@Operation(summary = "템플릿 삭제(소프트 삭제)") @Operation(summary = "템플릿 삭제(소프트 삭제)")

View File

@@ -0,0 +1,12 @@
package com.kri.notihub.server.dto.email;
import java.util.Objects;
public record EmailAttachmentDto(String fileName, String contentType, byte[] content) {
public EmailAttachmentDto {
Objects.requireNonNull(fileName, "fileName is required");
Objects.requireNonNull(contentType, "contentType is required");
Objects.requireNonNull(content, "content is required");
}
}

View File

@@ -44,6 +44,9 @@ public class BulkSendInfoDto {
@Schema(description = "예약 여부") @Schema(description = "예약 여부")
private Boolean resve; private Boolean resve;
@Schema(description = "조회 시점에 취소 가능한 예약 상세 건이 하나 이상인지 여부. 최종 판단은 취소 API 응답 기준")
private boolean cancelable;
@NotNull @NotNull
@Schema(description = "발송일시") @Schema(description = "발송일시")
private LocalDateTime sendDt; private LocalDateTime sendDt;
@@ -80,12 +83,32 @@ public class BulkSendInfoDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime regDt; private LocalDateTime regDt;
@Schema(description = "벌크 취소 요청자")
private String cancelUser;
@Schema(description = "벌크 취소 요청 일시. 수신자 추가 등록 마감 기준")
private LocalDateTime cancelDt;
@Schema(description = "현재 취소 상태인 건수")
private long canceledCount;
@Schema(description = "취소 상태: NONE, PARTIAL, ALL")
private String cancellationStatus;
public void applyCanceledCount(long count, long targetCount) {
canceledCount = count;
cancellationStatus = count == 0 ? "NONE"
: count == targetCount ? "ALL" : "PARTIAL";
}
public static BulkSendInfoDto from(TBulkSendEntity entity) { public static BulkSendInfoDto from(TBulkSendEntity entity) {
if (entity == null) { if (entity == null) {
return null; return null;
} }
return BulkSendInfoDto.builder() return BulkSendInfoDto.builder()
.cancelUser(entity.getCancelUser())
.cancelDt(entity.getCancelDt())
.bulkSendKey(entity.getBulkSendKey()) .bulkSendKey(entity.getBulkSendKey())
.reqstSvc(entity.getReqstSvc()) .reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd()) .prjctCd(entity.getPrjctCd())

View File

@@ -2,17 +2,13 @@ package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder @Builder
public class ReportExcelResponseDto { public record ReportExcelResponseDto(
@Schema(description = "프론트가 저장용으로 쓸 파일명") @Schema(description = "프론트가 저장용으로 쓸 파일명")
private String errorFileName; String fileName,
@Schema(description = "에러 엑셀 파일 (xlsx)의 Base64 문자열 (hasErrorFile == true일 때만 세팅)") @Schema(description = "엑셀 파일 (xlsx)의 Base64 문자열 (hasErrorFile == true일 때만 세팅)")
private String errorFileBase64; String fileBase64
) {
} }

View File

@@ -0,0 +1,15 @@
package com.kri.notihub.server.dto.report;
import java.math.BigDecimal;
/**
* 요청 서비스 · 인트라넷 프로젝트 · 발송 타입별 발송 비용 집계 (조회 전용 projection)
*/
public record SendCostByTypeDto(
String reqstSvc,
String itrntPrjctCd,
Short sendTy,
Long sendCnt,
BigDecimal totalPrice
) {
}

View File

@@ -0,0 +1,19 @@
package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDate;
import lombok.Builder;
@Builder
@Schema(description = "발송 비용 프로젝트별 요약 요청")
public record SendCostSummaryRequestDto(
@Schema(description = "조회 시작 일시")
@NotNull
LocalDate startDt,
@Schema(description = "조회 종료 일시")
@NotNull
LocalDate endDt
) {
}

View File

@@ -0,0 +1,123 @@
package com.kri.notihub.server.dto.report;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.common.external.intranet.dto.IntranetProjectBaseInfoDto;
import io.swagger.v3.oas.annotations.media.Schema;
import java.math.BigDecimal;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "인트라넷 프로젝트 정보 포함 발송 비용 요약 (발송 타입별 컬럼)")
public class SendCostSummaryWithItrntPrjctDto {
@Schema(description = "요청 서비스")
private String reqstSvc;
@Schema(description = "인트라넷 프로젝트 코드")
private String itrntPrjctCd;
@Schema(description = "EMAIL 발송 건수")
@Builder.Default
private Long emailCnt = 0L;
@Schema(description = "SMS 발송 건수")
@Builder.Default
private Long smsCnt = 0L;
@Schema(description = "LMS 발송 건수")
@Builder.Default
private Long lmsCnt = 0L;
@Schema(description = "MMS 발송 건수")
@Builder.Default
private Long mmsCnt = 0L;
@Schema(description = "알림톡 발송 건수")
@Builder.Default
private Long kkoAtCnt = 0L;
@Schema(description = "EMAIL 단가")
@Builder.Default
private BigDecimal emailUnitPrice = BigDecimal.ZERO;
@Schema(description = "SMS 단가")
@Builder.Default
private BigDecimal smsUnitPrice = BigDecimal.ZERO;
@Schema(description = "LMS 단가")
@Builder.Default
private BigDecimal lmsUnitPrice = BigDecimal.ZERO;
@Schema(description = "MMS 단가")
@Builder.Default
private BigDecimal mmsUnitPrice = BigDecimal.ZERO;
@Schema(description = "알림톡 단가")
@Builder.Default
private BigDecimal kkoAtUnitPrice = BigDecimal.ZERO;
@Schema(description = "EMAIL 비용")
@Builder.Default
private BigDecimal emailTotalPrice = BigDecimal.ZERO;
@Schema(description = "SMS 비용")
@Builder.Default
private BigDecimal smsTotalPrice = BigDecimal.ZERO;
@Schema(description = "LMS 비용")
@Builder.Default
private BigDecimal lmsTotalPrice = BigDecimal.ZERO;
@Schema(description = "MMS 비용")
@Builder.Default
private BigDecimal mmsTotalPrice = BigDecimal.ZERO;
@Schema(description = "알림톡 비용")
@Builder.Default
private BigDecimal kkoAtTotalPrice = BigDecimal.ZERO;
@Schema(description = "인트라넷 프로젝트 정보")
private IntranetProjectBaseInfoDto itrntPrjctInfo;
/**
* 발송 타입에 해당하는 건수 · 단가 · 비용 컬럼을 설정한다.
*/
public void applySendType(SendType sendType, long sendCnt, BigDecimal unitPrice,
BigDecimal totalPrice) {
switch (sendType) {
case EMAIL -> {
this.emailCnt = sendCnt;
this.emailUnitPrice = unitPrice;
this.emailTotalPrice = totalPrice;
}
case SMS -> {
this.smsCnt = sendCnt;
this.smsUnitPrice = unitPrice;
this.smsTotalPrice = totalPrice;
}
case LMS -> {
this.lmsCnt = sendCnt;
this.lmsUnitPrice = unitPrice;
this.lmsTotalPrice = totalPrice;
}
case MMS -> {
this.mmsCnt = sendCnt;
this.mmsUnitPrice = unitPrice;
this.mmsTotalPrice = totalPrice;
}
case KKO_AT -> {
this.kkoAtCnt = sendCnt;
this.kkoAtUnitPrice = unitPrice;
this.kkoAtTotalPrice = totalPrice;
}
}
}
}

View File

@@ -0,0 +1,97 @@
package com.kri.notihub.server.dto.report;
import com.kri.common.feature.excel.ExcelColumn;
import com.kri.notihub.server.common.external.intranet.dto.IntranetProjectBaseInfoDto;
import java.math.BigDecimal;
import lombok.Builder;
@Builder
public record SendCostSummaryWithItrntPrjctExcelDto(
@ExcelColumn(header = "요청 서비스", order = 0)
String reqstSvc,
@ExcelColumn(header = "인트라넷 프로젝트 코드", order = 1)
String itrntPrjctCd,
@ExcelColumn(header = "프로젝트 명", order = 2)
String title,
@ExcelColumn(header = "연구팀 명", order = 3)
String researchTeamName,
@ExcelColumn(header = "EMAIL 건수", order = 4)
Long emailCnt,
@ExcelColumn(header = "SMS 건수", order = 5)
Long smsCnt,
@ExcelColumn(header = "LMS 건수", order = 6)
Long lmsCnt,
@ExcelColumn(header = "MMS 건수", order = 7)
Long mmsCnt,
@ExcelColumn(header = "알림톡 건수", order = 8)
Long kkoAtCnt,
@ExcelColumn(header = "EMAIL 단가", order = 9)
BigDecimal emailUnitPrice,
@ExcelColumn(header = "SMS 단가", order = 10)
BigDecimal smsUnitPrice,
@ExcelColumn(header = "LMS 단가", order = 11)
BigDecimal lmsUnitPrice,
@ExcelColumn(header = "MMS 단가", order = 12)
BigDecimal mmsUnitPrice,
@ExcelColumn(header = "알림톡 단가", order = 13)
BigDecimal kkoAtUnitPrice,
@ExcelColumn(header = "EMAIL 비용", order = 14)
BigDecimal emailTotalPrice,
@ExcelColumn(header = "SMS 비용", order = 15)
BigDecimal smsTotalPrice,
@ExcelColumn(header = "LMS 비용", order = 16)
BigDecimal lmsTotalPrice,
@ExcelColumn(header = "MMS 비용", order = 17)
BigDecimal mmsTotalPrice,
@ExcelColumn(header = "알림톡 비용", order = 18)
BigDecimal kkoAtTotalPrice
) {
public static SendCostSummaryWithItrntPrjctExcelDto from(
SendCostSummaryWithItrntPrjctDto source) {
if (source == null) {
return null;
}
IntranetProjectBaseInfoDto projectInfo = source.getItrntPrjctInfo();
return SendCostSummaryWithItrntPrjctExcelDto.builder()
.reqstSvc(source.getReqstSvc())
.itrntPrjctCd(source.getItrntPrjctCd())
.title(projectInfo != null ? projectInfo.title() : null)
.researchTeamName(projectInfo != null ? projectInfo.researchTeamName() : null)
.emailCnt(source.getEmailCnt())
.smsCnt(source.getSmsCnt())
.lmsCnt(source.getLmsCnt())
.mmsCnt(source.getMmsCnt())
.kkoAtCnt(source.getKkoAtCnt())
.emailUnitPrice(source.getEmailUnitPrice())
.smsUnitPrice(source.getSmsUnitPrice())
.lmsUnitPrice(source.getLmsUnitPrice())
.mmsUnitPrice(source.getMmsUnitPrice())
.kkoAtUnitPrice(source.getKkoAtUnitPrice())
.emailTotalPrice(source.getEmailTotalPrice())
.smsTotalPrice(source.getSmsTotalPrice())
.lmsTotalPrice(source.getLmsTotalPrice())
.mmsTotalPrice(source.getMmsTotalPrice())
.kkoAtTotalPrice(source.getKkoAtTotalPrice())
.build();
}
}

View File

@@ -2,6 +2,7 @@ package com.kri.notihub.server.dto.report;
import com.kri.common.feature.excel.ExcelColumn; import com.kri.common.feature.excel.ExcelColumn;
import com.kri.notihub.server.common.enums.SendStatusType; import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.persistence.entity.TSendEntity; import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.entity.TSendResultCodeEntity; import com.kri.notihub.server.persistence.entity.TSendResultCodeEntity;
@@ -11,123 +12,121 @@ import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import lombok.AllArgsConstructor; import java.util.Objects;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder @Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "발송 정보") @Schema(description = "발송 정보")
public class SendInfoDto { public record SendInfoDto(
@Size(max = 32) @Size(max = 32)
@NotBlank @NotBlank
@Schema(description = "CMID") @Schema(description = "CMID")
private String cmid; String cmid,
@Size(max = 32) @Size(max = 32)
@Schema(description = "대량발송 키") @Schema(description = "대량발송 키")
private String bulkSendKey; String bulkSendKey,
@NotNull @NotNull
@Schema(description = "발송 타입 코드") @Schema(description = "발송 타입 코드")
private Short sendTyCode; Short sendTyCode,
@NotNull @NotNull
@Schema(description = "발송 타입 라벨") @Schema(description = "발송 타입 라벨")
private String sendTyLabel; String sendTyLabel,
@NotNull @NotNull
@Schema(description = "예약 여부") @Schema(description = "예약 여부")
private Boolean resve; Boolean resve,
@NotNull @NotNull
@Schema(description = "발송 상태") @Schema(description = "발송 상태")
private Short sendStatusCode; Short sendStatusCode,
@NotNull @NotNull
@ExcelColumn(header = "발송 상태", order = 0) @ExcelColumn(header = "발송 상태", order = 0)
@Schema(description = "발송 상태 라벨") @Schema(description = "발송 상태 라벨")
private String sendStatusLabel; String sendStatusLabel,
@NotNull @NotNull
@Schema(description = "결과 코드") @Schema(description = "결과 코드")
private Short resultCode; Short resultCode,
@NotNull @NotNull
@ExcelColumn(header = "발송 결과", order = 1) @ExcelColumn(header = "발송 결과", order = 1)
@Schema(description = "결과 라벨") @Schema(description = "결과 라벨")
private String resultLabel; String resultLabel,
@Size(max = 16) @Size(max = 16)
@NotBlank @NotBlank
@Schema(description = "요청 서비스") @Schema(description = "요청 서비스")
private String reqstSvc; String reqstSvc,
@Size(max = 32) @Size(max = 32)
@NotBlank @NotBlank
@Schema(description = "프로젝트 코드") @Schema(description = "프로젝트 코드")
private String prjctCd; String prjctCd,
@Schema(description = "템플릿 인덱스") @Schema(description = "템플릿 인덱스")
private Long tmplatIdx; Long tmplatIdx,
@Size(max = 64) @Size(max = 64)
@ExcelColumn(header = "발신지", order = 2) @ExcelColumn(header = "발신지", order = 2)
@Schema(description = "발신지(EMAIL이면 sendEml, 아니면 sendTel)") @Schema(description = "발신지(EMAIL이면 sendEml, 아니면 sendTel)")
private String sendFrom; String sendFrom,
@Size(max = 32) @Size(max = 32)
@ExcelColumn(header = "발신자명", order = 3) @ExcelColumn(header = "발신자명", order = 3)
@Schema(description = "발신자명") @Schema(description = "발신자명")
private String sendNm; String sendNm,
@NotNull @NotNull
@ExcelColumn(header = "발송 일시", order = 4) @ExcelColumn(header = "발송 일시", order = 4)
@Schema(description = "발송 일시") @Schema(description = "발송 일시")
private LocalDateTime sendDt; LocalDateTime sendDt,
@Size(max = 128) @Size(max = 128)
@NotBlank @NotBlank
@ExcelColumn(header = "SID", order = 5) @ExcelColumn(header = "SID", order = 5)
@Schema(description = "SID") @Schema(description = "SID")
private String sid; String sid,
@Size(max = 64) @Size(max = 64)
@ExcelColumn(header = "수신지", order = 6) @ExcelColumn(header = "수신지", order = 6)
@Schema(description = "수신지(EMAIL이면 destEml, 아니면 destTel)") @Schema(description = "수신지(EMAIL이면 destEml, 아니면 destTel)")
private String destTo; String destTo,
@Size(max = 32) @Size(max = 32)
@ExcelColumn(header = "수신자명", order = 7) @ExcelColumn(header = "수신자명", order = 7)
@Schema(description = "수신자명") @Schema(description = "수신자명")
private String destNm; String destNm,
@ExcelColumn(header = "발송 결과 확인 일시", order = 8) @ExcelColumn(header = "발송 결과 확인 일시", order = 8)
@Schema(description = "리포트 일시") @Schema(description = "리포트 일시")
private LocalDateTime reportDt; LocalDateTime reportDt,
@Size(max = 32) @Size(max = 32)
@NotBlank @NotBlank
@Schema(description = "등록 회사") @Schema(description = "등록 회사")
private String regCmpn; String regCmpn,
@Size(max = 32) @Size(max = 32)
@NotBlank @NotBlank
@ExcelColumn(header = "발송 요청자", order = 9) @ExcelColumn(header = "발송 요청자", order = 9)
@Schema(description = "등록자") @Schema(description = "등록자")
private String regUser; String regUser,
@NotNull @NotNull
@ExcelColumn(header = "발송 요청 일시", order = 10) @ExcelColumn(header = "발송 요청 일시", order = 10)
@Schema(description = "등록일시") @Schema(description = "등록일시")
private LocalDateTime regDt; LocalDateTime regDt,
@ExcelColumn(header = "취소 처리자", order = 11)
String cancelUser,
@ExcelColumn(header = "취소 처리 일시", order = 12)
LocalDateTime cancelDt
) {
public static SendInfoDto from(TSendEntity entity, List<TSendResultCodeEntity> resultCodeEntity) { public static SendInfoDto from(TSendEntity entity, List<TSendResultCodeEntity> resultCodeEntity) {
if (entity == null) { if (entity == null) {
return null; return null;
@@ -146,15 +145,19 @@ public class SendInfoDto {
.orElse(null); // 없으면 null .orElse(null); // 없으면 null
return SendInfoDto.builder() return SendInfoDto.builder()
.cancelUser(entity.getCancelUser())
.cancelDt(entity.getCancelDt())
.cmid(entity.getCmid()) .cmid(entity.getCmid())
.bulkSendKey(entity.getBulkSendKey()) .bulkSendKey(entity.getBulkSendKey())
.sendTyCode(entity.getSendTy()) .sendTyCode(entity.getSendTy())
.sendTyLabel(SendType.fromCode(entity.getSendTy()).name()) .sendTyLabel(SendType.fromCode(entity.getSendTy()).name())
.resve(entity.isResve()) .resve(entity.isResve())
.sendStatusCode(entity.getSendStatus()) .sendStatusCode(entity.getSendStatus())
.sendStatusLabel(SendStatusType.fromCode(entity.getSendStatus()).name()) .sendStatusLabel(Objects.equals(entity.getSendStatus(), SendStatusType.CANCELED.getCode())
? NotihubConst.CANCELED_LABEL : SendStatusType.fromCode(entity.getSendStatus()).name())
.resultCode(entity.getResultCode()) .resultCode(entity.getResultCode())
.resultLabel(resultViewLabel) .resultLabel(Objects.equals(entity.getSendStatus(), SendStatusType.CANCELED.getCode())
? NotihubConst.CANCELED_LABEL : resultViewLabel)
.reqstSvc(entity.getReqstSvc()) .reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd()) .prjctCd(entity.getPrjctCd())
.tmplatIdx(entity.getTmplatIdx()) .tmplatIdx(entity.getTmplatIdx())

View File

@@ -0,0 +1,43 @@
package com.kri.notihub.server.dto.report;
import com.kri.notihub.server.persistence.entity.TSendResultCodeEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Builder;
@Builder
@Schema(description = "발송 결과 코드")
public record SendResultCodeDto(
@NotNull
@Schema(description = "결과 코드")
Short resultCode,
@NotNull
@Schema(description = "결과 타입")
Short resultTy,
@Size(max = 128)
@NotBlank
@Schema(description = "결과 라벨")
String resultLabel,
@Size(max = 128)
@NotBlank
@Schema(description = "결과 표시 라벨")
String resultViewLabel
) {
public static SendResultCodeDto from(TSendResultCodeEntity entity) {
if (entity == null) {
return null;
}
return SendResultCodeDto.builder()
.resultCode(entity.getResultCode())
.resultTy(entity.getResultTy())
.resultLabel(entity.getResultLabel())
.resultViewLabel(entity.getResultViewLabel())
.build();
}
}

View File

@@ -0,0 +1,182 @@
package com.kri.notihub.server.dto.report;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.persistence.entity.TSendResultCodeEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import lombok.Builder;
@Builder
@Schema(description = "발송 결과 정보")
public record SendResultInfoDto(
@Schema(description = "발송 이력 ID")
Long sendIdx,
@Schema(description = "취소 처리자")
String cancelUser,
@Schema(description = "취소 처리 일시. 실제 발송 결과가 확인된 뒤에도 이력 유지")
LocalDateTime cancelDt,
@Schema(description = "CMID")
String cmid,
@Schema(description = "대량 발송 키")
String bulkSendKey,
@Schema(description = "인트라넷 프로젝트 코드")
String itrntPrjctCd,
@Schema(description = "요청 서비스")
String reqstSvc,
@Schema(description = "프로젝트 코드")
String prjctCd,
@Schema(description = "리스트 아이디")
String sid,
@NotNull
@Schema(description = "발송 타입")
Short sendTy,
@NotNull
@Schema(description = "예약 여부")
Boolean resve,
@Schema(description = "조회 시점의 상태 기준 예약 취소 가능 여부. 최종 판단은 취소 API 응답 기준")
boolean cancelable,
@NotNull
@Schema(description = "결과 코드")
Short resultCode,
@Size(max = 128)
@Schema(description = "결과 라벨")
String resultLabel,
@Size(max = 128)
@Schema(description = "결과 표시 라벨")
String resultViewLabel,
@Schema(description = "템플릿 인덱스")
Long tmplatIdx,
@Size(max = 64)
@Schema(description = "카카오 템플릿 코드")
String kkoTmplatCd,
@Size(max = 64)
@Schema(description = "발신 이메일")
String sendEml,
@Size(max = 16)
@Schema(description = "발신 전화번호")
String sendTel,
@Size(max = 32)
@Schema(description = "발신자명")
String sendNm,
@NotNull
@Schema(description = "발송 일시")
LocalDateTime sendDt,
@Size(max = 64)
@Schema(description = "수신 이메일")
String destEml,
@Size(max = 32)
@Schema(description = "수신자명")
String destNm,
@Size(max = 16)
@Schema(description = "수신 전화번호")
String destTel,
@Size(max = 32)
@NotBlank
@Schema(description = "등록 회사")
String regCmpn,
@Size(max = 32)
@NotBlank
@Schema(description = "등록자")
String regUser,
@NotNull
@Schema(description = "등록 일시")
LocalDateTime regDt
) {
public static SendResultInfoDto from(TSendEntity entity) {
return from(entity, null);
}
public static SendResultInfoDto from(TSendEntity entity,
List<TSendResultCodeEntity> resultCodeEntity) {
return from(entity, resultCodeEntity, false);
}
public static SendResultInfoDto from(TSendEntity entity,
List<TSendResultCodeEntity> resultCodeEntity, boolean cancelable) {
if (entity == null) {
return null;
}
TSendResultCodeEntity resultCode = findResultCode(entity, resultCodeEntity);
boolean canceled = Objects.equals(entity.getSendStatus(), SendStatusType.CANCELED.getCode());
return SendResultInfoDto.builder()
.sendIdx(entity.getSendIdx())
.cancelUser(entity.getCancelUser())
.cancelDt(entity.getCancelDt())
.cmid(entity.getCmid())
.bulkSendKey(entity.getBulkSendKey())
.itrntPrjctCd(entity.getItrntPrjctCd())
.reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd())
.sid(entity.getSid())
.sendTy(entity.getSendTy())
.resve(entity.isResve())
.cancelable(cancelable)
.resultCode(entity.getResultCode())
.resultLabel(canceled ? NotihubConst.CANCELED_LABEL
: resultCode != null ? resultCode.getResultLabel() : null)
.resultViewLabel(canceled ? NotihubConst.CANCELED_LABEL
: resultCode != null ? resultCode.getResultViewLabel() : null)
.tmplatIdx(entity.getTmplatIdx())
.kkoTmplatCd(entity.getKkoTmplatCd())
.sendEml(entity.getSendEml())
.sendTel(entity.getSendTel())
.sendNm(entity.getSendNm())
.sendDt(entity.getSendDt())
.destEml(entity.getDestEml())
.destNm(entity.getDestNm())
.destTel(entity.getDestTel())
.regCmpn(entity.getRegCmpn())
.regUser(entity.getRegUser())
.regDt(entity.getRegDt())
.build();
}
private static TSendResultCodeEntity findResultCode(TSendEntity entity,
List<TSendResultCodeEntity> resultCodeEntity) {
if (resultCodeEntity == null) {
return null;
}
return resultCodeEntity.stream()
.filter(e -> e.getId() != null)
.filter(e -> Objects.equals(e.getId().getSendCorp(), entity.getSendCorp()))
.filter(e -> Objects.equals(e.getId().getResultCode(), entity.getResultCode()))
.findFirst()
.orElse(null);
}
}

View File

@@ -0,0 +1,29 @@
package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.Builder;
import lombok.Builder;
@Builder
@Schema(description = "발송 결과 정보")
public record SendResultLastWithSidDto(
@Schema(description = "리스트 아이디")
String sid,
@Schema(description = "마지막 결과 코드")
Short lastResultCode,
@Schema(description = "마지막 결과 라벨")
String lastResultLabel,
@Schema(description = "마지막 결과 표시 라벨")
String lastResultViewLabel,
@Schema(description = "마지막 발송 일시")
LocalDateTime lastSendDt,
@Schema(description = "총 발송 Count")
Integer totalSendCount
) {
}

View File

@@ -0,0 +1,38 @@
package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "발송 축약 결과")
public class SendResultSummaryDto {
@Schema(description = "발송 타입 코드")
private Short sendTy;
@Schema(description = "발송 사")
private Short sendCorp;
@Schema(description = "발송 성공 카운트")
private Long successCount;
@Schema(description = "발송 실패 카운트")
private Long failCount;
@Schema(description = "대기중 카운트")
private Long standByCount;
@Schema(description = "현재 취소 상태인 건수")
private Long canceledCount;
@Schema(description = "전체 카운트")
private Long totalCount;
}

View File

@@ -0,0 +1,28 @@
package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.Builder;
@Builder
@Schema(description = "발송 축약 결과 요청")
public record SendResultSummaryRequestDto(
@Schema(description = "대량발송 키")
String bulkSendKey,
@Schema(description = "인트라넷 프로젝트 코드")
String itrntPrjctCd,
@Schema(description = "요청 서비스")
String reqstSvc,
@Schema(description = "프로젝트 코드")
String prjctCd,
@Schema(description = "발송일시 조회 시작")
LocalDateTime sendStartDt,
@Schema(description = "발송일시 조회 종료")
LocalDateTime sendEndDt
) {
}

View File

@@ -0,0 +1,24 @@
package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import java.math.BigDecimal;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "발송 축약 결과 응답")
public class SendResultSummaryResponseDto extends SendResultSummaryDto {
@Schema(description = "발송 단가")
private BigDecimal price;
@Schema(description = "발송 비용")
private BigDecimal cost;
}

View File

@@ -1,20 +1,13 @@
package com.kri.notihub.server.dto.send; package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder @Builder
@NoArgsConstructor public record BizppurioCursorResponseDto(
@AllArgsConstructor
public class BizppurioCursorResponseDto {
@Schema(description = "SMS 결과 반영 스케줄러 커서(send_idx)") @Schema(description = "SMS 결과 반영 스케줄러 커서(send_idx)")
private Long cursor; Long cursor
) {
public static BizppurioCursorResponseDto of(long cursor) { public static BizppurioCursorResponseDto of(long cursor) {
return BizppurioCursorResponseDto.builder() return BizppurioCursorResponseDto.builder()
.cursor(cursor) .cursor(cursor)

View File

@@ -1,29 +1,22 @@
package com.kri.notihub.server.dto.send; package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder @Builder
@NoArgsConstructor public record BulkSendResponseDto(
@AllArgsConstructor
public class BulkSendResponseDto {
@Schema(description = "bulkSendKey") @Schema(description = "bulkSendKey")
private String bulkSendKey; String bulkSendKey,
@Schema(description = "요청 건수") @Schema(description = "요청 건수")
private Integer requestCount; Integer requestCount,
@Schema(description = "Pringo send 요청 성공(return_key 수신) 건수") @Schema(description = "발송 접수 건수(대기 또는 즉시 성공)")
private Integer acceptCount; Integer acceptCount,
@Schema(description = "Pringo send 요청 실패(return_key 미수신) 건수")
private Integer failCount;
@Schema(description = "발송 접수 실패 건수")
Integer failCount
) {
public static BulkSendResponseDto of(String bulkSendKey, Integer requestCount, public static BulkSendResponseDto of(String bulkSendKey, Integer requestCount,
Integer acceptCount, Integer failCount) { Integer acceptCount, Integer failCount) {
return BulkSendResponseDto.builder() return BulkSendResponseDto.builder()

View File

@@ -5,39 +5,30 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Email; import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import java.util.Map; import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder @Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "수신 정보") @Schema(description = "수신 정보")
public class DestInfoDto { public record DestInfoDto(
@Schema(description = "리스트 아이디") @Schema(description = "리스트 아이디")
private String sid; String sid,
@Size(max = 64) @Size(max = 64)
@Email @Email
@Schema(description = "수신 이메일 (이메일 발송에서 사용)") @Schema(description = "수신 이메일 (이메일 발송에서 사용)")
private String destEml; String destEml,
@Size(max = 16) @Size(max = 16)
@Schema(description = "수신 전화번호 (문자 발송에서 사용)") @Schema(description = "수신 전화번호 (문자 발송에서 사용)")
private String destTel; String destTel,
@Size(max = 32) @Size(max = 32)
@Schema(description = "수신자 이름") @Schema(description = "수신자 이름")
private String destNm; String destNm,
@Schema(description = "수신 파라미터 (템플릿 내용 파싱용)") @Schema(description = "수신 파라미터 (템플릿 내용 파싱용)")
private Map<String, String> msgParam; Map<String, String> msgParam
) {
public static DestInfoDto from(TSendEntity entity) { public static DestInfoDto from(TSendEntity entity) {
return DestInfoDto.builder() return DestInfoDto.builder()
.sid(entity.getSid()) .sid(entity.getSid())

View File

@@ -5,30 +5,23 @@ import com.kri.common.feature.datetime.DateTimeUtil;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder @Builder
@NoArgsConstructor public record EmailPollQueueItemDto(
@AllArgsConstructor
public class EmailPollQueueItemDto {
@Schema(description = "Pringo return_key(cmid)") @Schema(description = "Pringo return_key(cmid)")
private String cmid; String cmid,
@Schema(description = "폴링 시도 횟수(0부터 시작)") @Schema(description = "폴링 시도 횟수(0부터 시작)")
private Integer attempt; Integer attempt,
@Schema(description = "구동까지 남은 시간(ms)") @Schema(description = "구동까지 남은 시간(ms)")
private Long remainingMs; Long remainingMs,
@Schema(description = "구동 예상 시간(KST LocalDateTime)") @Schema(description = "구동 예상 시간(KST LocalDateTime)")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime triggerAt; LocalDateTime triggerAt
) {
public static EmailPollQueueItemDto of(String cmid, int attempt, long remainingMs, public static EmailPollQueueItemDto of(String cmid, int attempt, long remainingMs,
long triggerAtEpochMs) { long triggerAtEpochMs) {
return EmailPollQueueItemDto.builder() return EmailPollQueueItemDto.builder()

View File

@@ -2,23 +2,16 @@ package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List; import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder @Builder
@NoArgsConstructor public record EmailPollQueueResponseDto(
@AllArgsConstructor
public class EmailPollQueueResponseDto {
@Schema(description = "Queue size (snapshot)") @Schema(description = "Queue size (snapshot)")
private Integer size; Integer size,
@Schema(description = "Queue에 있는 작업 내용 (snapshot)") @Schema(description = "Queue에 있는 작업 내용 (snapshot)")
private List<EmailPollQueueItemDto> items; List<EmailPollQueueItemDto> items
) {
public static EmailPollQueueResponseDto of(List<EmailPollQueueItemDto> items) { public static EmailPollQueueResponseDto of(List<EmailPollQueueItemDto> items) {
return EmailPollQueueResponseDto.builder() return EmailPollQueueResponseDto.builder()
.size(items != null ? items.size() : 0) .size(items != null ? items.size() : 0)

View File

@@ -0,0 +1,11 @@
package com.kri.notihub.server.dto.send;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record SendCancelBulkRequestDto(
@NotBlank
@Size(max = 32)
String bulkSendKey
) {
}

View File

@@ -0,0 +1,14 @@
package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
@Schema(description = "싱글/벌크 예약 취소 결과. 문자·알림톡은 큐 제거 기준이며 미발송을 보장하지 않음")
@Builder
public record SendCancelResponseDto(
long targetCount,
long canceledCount,
long alreadyCanceledCount,
long notCancelableCount
) {
}

View File

@@ -0,0 +1,11 @@
package com.kri.notihub.server.dto.send;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
public record SendCancelSingleRequestDto(
@NotNull
@Positive
Long sendIdx
) {
}

View File

@@ -2,26 +2,17 @@ package com.kri.notihub.server.dto.send;
import com.kri.notihub.server.common.enums.SendStatusType; import com.kri.notihub.server.common.enums.SendStatusType;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder @Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "이메일/문자 발송 결과") @Schema(description = "이메일/문자 발송 결과")
public class SendInternalResultDto { public record SendInternalResultDto(
String cmid,
private String cmid; SendStatusType status,
private SendStatusType status;
private Short resultCode;
Short resultCode
) {
public static SendInternalResultDto of(String cmid, SendStatusType status, short resultCode) { public static SendInternalResultDto of(String cmid, SendStatusType status, short resultCode) {
return SendInternalResultDto.builder() return SendInternalResultDto.builder()
.cmid(cmid) .cmid(cmid)

View File

@@ -0,0 +1,35 @@
package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Map;
import lombok.Builder;
@Builder
@Schema(description = "단건 발송 접수 결과")
public record SendSingleResponseDto(
@Schema(description = "발송 이력 ID")
Long sendIdx,
@Schema(description = "발송 고유 키")
String cmid,
@Schema(description = "템플릿 목적별 추가 응답 정보")
Map<String, Object> data
) {
public static final String VERIFICATION_ID_KEY = "verificationId";
public static final String EXPIRE_DT_KEY = "expireDt";
public static SendSingleResponseDto of(Long sendIdx, String cmid, Map<String, Object> data) {
return SendSingleResponseDto.builder()
.sendIdx(sendIdx)
.cmid(cmid)
.data(data == null ? Map.of() : Map.copyOf(data))
.build();
}
public static class SendSingleResponseDtoBuilder {
private Map<String, Object> data = Map.of();
}
}

View File

@@ -0,0 +1,4 @@
package com.kri.notihub.server.dto.template;
public record KkoProfileDto(String senderKey, String name, String uuid) {
}

View File

@@ -0,0 +1,31 @@
package com.kri.notihub.server.dto.template;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public record KkoTemplateDetailDto(
String templateCode,
String templateName,
String templateContent,
String templatePreviewMessage,
String templateMessageType,
String templateEmphasizeType,
String inspectionStatus,
String status,
Boolean block,
Boolean dormant,
String templateExtra,
String templateImageName,
String templateImageUrl,
String templateTitle,
String templateSubtitle,
String templateHeader,
JsonNode templateItemHighlight,
JsonNode templateItem,
JsonNode templateRepresentLink,
List<JsonNode> buttons,
List<JsonNode> quickReplies
) {
}

View File

@@ -0,0 +1,16 @@
package com.kri.notihub.server.dto.template;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public record KkoTemplateDetailRequestDto(
@NotBlank
@Size(max = 40)
String senderKey,
@NotBlank
@Size(max = 30)
@Pattern(regexp = "[A-Za-z0-9_-]+")
String templateCode
) {
}

View File

@@ -0,0 +1,16 @@
package com.kri.notihub.server.dto.template;
import jakarta.validation.constraints.Size;
import jakarta.validation.constraints.NotBlank;
public record KkoTemplateListRequestDto(
@NotBlank
@Size(max = 40)
String senderKey,
@Size(min = 2, max = 50)
String keyword
) {
public KkoTemplateListRequestDto {
keyword = keyword == null || keyword.isBlank() ? null : keyword.trim();
}
}

View File

@@ -0,0 +1,11 @@
package com.kri.notihub.server.dto.template;
import java.util.List;
public record KkoTemplateListResponseDto(
int totalCount,
int totalPage,
int currentPage,
List<KkoTemplateSummaryDto> list
) {
}

View File

@@ -0,0 +1,13 @@
package com.kri.notihub.server.dto.template;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public record KkoTemplateSummaryDto(
String templateCode,
String templateName,
String serviceStatus,
String createdAt,
String modifiedAt
) {
}

View File

@@ -1,6 +1,8 @@
package com.kri.notihub.server.dto.template; package com.kri.notihub.server.dto.template;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.common.enums.TemplatePurpose;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.validation.constraints.Email; import jakarta.validation.constraints.Email;
@@ -29,17 +31,19 @@ public class TemplateBasicDto {
@Schema(description = "템플릿 타입") @Schema(description = "템플릿 타입")
private SendType tmplatTy; private SendType tmplatTy;
@Size(max = 32) @Schema(description = "템플릿 목적 (0: 일반, 1: 휴대전화번호 인증)")
private TemplatePurpose tmplatPurpose;
@Size(max = 128)
@NotBlank @NotBlank
@Schema(description = "템플릿 명") @Schema(description = "템플릿 명")
private String tmplatNm; private String tmplatNm;
@Size(max = 128) @Size(max = 128)
@Schema(description = "발송시 제목") @Schema(description = "발송시 제목 (문자 템플릿은 평문 기준 최대 64자)")
private String tmplatTitle; private String tmplatTitle;
@NotBlank @Schema(description = "발송 내용 (알림톡은 외부 상세 조회 결과로 저장)")
@Schema(description = "발송 내용")
private String tmplatBody; private String tmplatBody;
@Schema(description = "비즈뿌리오 알림톡 프로필의 sender key") @Schema(description = "비즈뿌리오 알림톡 프로필의 sender key")
@@ -52,6 +56,7 @@ public class TemplateBasicDto {
private String nationCd; private String nationCd;
@Schema(description = "첨부 파일 (여러 개일 경우, ‘I’문자로 구분)") @Schema(description = "첨부 파일 (여러 개일 경우, ‘I’문자로 구분)")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String atchFl; private String atchFl;
@Schema(description = "이메일 건당 발송 딜레이(단위 ms, 기본: 500ms)") @Schema(description = "이메일 건당 발송 딜레이(단위 ms, 기본: 500ms)")

View File

@@ -2,6 +2,7 @@ package com.kri.notihub.server.dto.template;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.common.enums.TemplatePurpose;
import com.kri.notihub.server.persistence.entity.TTmplatEntity; import com.kri.notihub.server.persistence.entity.TTmplatEntity;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
@@ -48,6 +49,7 @@ public class TemplateDto extends TemplateBasicDto {
.tmplatIdx(entity.getTmplatIdx()) .tmplatIdx(entity.getTmplatIdx())
.itrntPrjctCd(entity.getItrntPrjctCd()) .itrntPrjctCd(entity.getItrntPrjctCd())
.tmplatTy(SendType.fromCode(entity.getTmplatTy())) .tmplatTy(SendType.fromCode(entity.getTmplatTy()))
.tmplatPurpose(TemplatePurpose.fromCode(entity.getTmplatPurpose()))
.tmplatNm(entity.getTmplatNm()) .tmplatNm(entity.getTmplatNm())
.tmplatTitle(entity.getTmplatTitle()) .tmplatTitle(entity.getTmplatTitle())
.tmplatBody(entity.getTmplatBody()) .tmplatBody(entity.getTmplatBody())

View File

@@ -1,31 +1,27 @@
package com.kri.notihub.server.dto.template; package com.kri.notihub.server.dto.template;
import com.kri.notihub.server.common.enums.TemplatePurpose;
import com.kri.notihub.server.persistence.entity.TTmplatEntity; import com.kri.notihub.server.persistence.entity.TTmplatEntity;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder @Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "템플릿 요약 정보") @Schema(description = "템플릿 요약 정보")
public class TemplateSummaryDto { public record TemplateSummaryDto(
@Schema(description = "템플릿 고유 키") @Schema(description = "템플릿 고유 키")
private Long tmplatIdx; Long tmplatIdx,
@Schema(description = "템플릿 명") @Schema(description = "템플릿 명")
private String tmplatNm; String tmplatNm,
@Schema(description = "템플릿 목적")
TemplatePurpose tmplatPurpose
) {
public static TemplateSummaryDto from(TTmplatEntity entity) { public static TemplateSummaryDto from(TTmplatEntity entity) {
return TemplateSummaryDto.builder() return TemplateSummaryDto.builder()
.tmplatIdx(entity.getTmplatIdx()) .tmplatIdx(entity.getTmplatIdx())
.tmplatNm(entity.getTmplatNm()) .tmplatNm(entity.getTmplatNm())
.tmplatPurpose(TemplatePurpose.fromCode(entity.getTmplatPurpose()))
.build(); .build();
} }
} }

View File

@@ -0,0 +1,28 @@
package com.kri.notihub.server.dto.verification;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
@Schema(description = "휴대전화번호 인증 요청")
public record PhoneVerificationRequestDto(
@NotBlank
@Pattern(
regexp = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$",
message = "verificationId는 UUID 형식이어야 합니다."
)
@Schema(description = "인증 발급 UUID")
String verificationId,
@NotBlank
@Size(max = 16)
@Schema(description = "인증 대상 휴대전화번호")
String sendTel,
@NotBlank
@Pattern(regexp = "^[0-9]{6}$", message = "verificationCode는 숫자 6자리여야 합니다.")
@Schema(description = "6자리 인증번호")
String verificationCode
) {
}

View File

@@ -0,0 +1,33 @@
package com.kri.notihub.server.dto.verification;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.Builder;
@Builder
@Schema(description = "휴대전화번호 인증 결과")
public record PhoneVerificationResponseDto(
String verificationId,
String sendTel,
boolean verified,
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime verifiedDt
) {
public static PhoneVerificationResponseDto of(
String verificationId,
String sendTel,
boolean verified,
LocalDateTime verifiedDt
) {
return PhoneVerificationResponseDto.builder()
.verificationId(verificationId)
.sendTel(sendTel)
.verified(verified)
.verifiedDt(verifiedDt)
.build();
}
}

View File

@@ -86,6 +86,25 @@ public class TBulkSendEntity extends BaseUuidEntity {
@Column(name = "reg_dt", nullable = false) @Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt; private LocalDateTime regDt;
@Column(name = "cancel_user", length = 32)
private String cancelUser;
@Column(name = "cancel_dt")
private LocalDateTime cancelDt;
public void completeIfSettled(long canceledCount, LocalDateTime now) {
long registered = value(sendCnt);
boolean registrationClosed = cancelDt != null || registered >= value(trgtCnt);
if (registrationClosed && registered <= value(succesCnt) + value(failCnt) + canceledCount
&& completeDt == null) {
completeDt = now;
}
}
private long value(Integer count) {
return count == null ? 0 : count;
}
public static TBulkSendEntity from(BulkSendCreateRequestDto req, LocalDateTime now) { public static TBulkSendEntity from(BulkSendCreateRequestDto req, LocalDateTime now) {
return TBulkSendEntity.builder() return TBulkSendEntity.builder()

View File

@@ -0,0 +1,71 @@
package com.kri.notihub.server.persistence.entity;
import com.kri.notihub.server.common.enums.PhoneVerificationStatus;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder
@Entity
@Table(name = "t_phone_verification")
@NoArgsConstructor
@AllArgsConstructor
public class TPhoneVerificationEntity {
@Id
@Size(max = 36)
@Column(name = "verification_id", nullable = false, length = 36)
private String verificationId;
@NotNull
@Size(max = 32)
@Column(name = "cmid", nullable = false, length = 32, unique = true)
private String cmid;
@NotNull
@Size(min = 6, max = 6)
@Column(name = "verification_code", nullable = false, length = 6)
private String verificationCode;
@NotNull
@Size(max = 16)
@Column(name = "send_tel", nullable = false, length = 16)
private String sendTel;
@NotNull
@Column(name = "status", nullable = false)
private Short status;
@NotNull
@Column(name = "attempt_count", nullable = false)
private Short attemptCount;
@NotNull
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
@NotNull
@Column(name = "expire_dt", nullable = false)
private LocalDateTime expireDt;
@Column(name = "verified_dt")
private LocalDateTime verifiedDt;
public void markVerified(LocalDateTime verifiedDt) {
this.status = PhoneVerificationStatus.VERIFIED.getCode();
this.verifiedDt = verifiedDt;
}
public void increaseAttemptCount() {
this.attemptCount = (short) (attemptCount + 1);
}
}

View File

@@ -1,5 +1,8 @@
package com.kri.notihub.server.persistence.entity; package com.kri.notihub.server.persistence.entity;
import static com.kri.notihub.server.common.consts.NotihubConst.SMS_TYPE_CODE_LIST;
import static com.kri.notihub.server.common.util.TemplateContentSanitizer.resolveSendType;
import com.kri.notihub.server.common.enums.SendCorpType; import com.kri.notihub.server.common.enums.SendCorpType;
import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.dto.send.DestInfoDto; import com.kri.notihub.server.dto.send.DestInfoDto;
@@ -170,6 +173,12 @@ public class TSendEntity {
@Column(name = "reg_dt", nullable = false) @Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt; private LocalDateTime regDt;
@Column(name = "cancel_user", length = 32)
private String cancelUser;
@Column(name = "cancel_dt")
private LocalDateTime cancelDt;
public static TSendEntity from( public static TSendEntity from(
SendRequestSingleDto req, SendRequestSingleDto req,
TemplateDto tmplat, TemplateDto tmplat,
@@ -230,14 +239,17 @@ public class TSendEntity {
Short sendCorp = tmplat.getTmplatTy() == SendType.EMAIL ? SendCorpType.PRINGO.getCode() Short sendCorp = tmplat.getTmplatTy() == SendType.EMAIL ? SendCorpType.PRINGO.getCode()
: SendCorpType.BIZ_PPURIO.getCode(); : SendCorpType.BIZ_PPURIO.getCode();
Short sendTy = resolveSendType(tmplat.getTmplatTy(), msgTitle, msgBody,
tmplat.getAtchFl()).getCode();
return TSendEntity.builder() return TSendEntity.builder()
.cmid(sendResult.getCmid()) .cmid(sendResult.cmid())
.bulkSendKey(bulkSendKey) .bulkSendKey(bulkSendKey)
.sendTy(tmplat.getTmplatTy().getCode()) .sendTy(sendTy)
.resve(resve) .resve(resve)
.sendCorp(sendCorp) .sendCorp(sendCorp)
.sendStatus(sendResult.getStatus().getCode()) .sendStatus(sendResult.status().getCode())
.resultCode(sendResult.getResultCode()) .resultCode(sendResult.resultCode())
.itrntPrjctCd(tmplat.getItrntPrjctCd()) .itrntPrjctCd(tmplat.getItrntPrjctCd())
.reqstSvc(reqstSvc) .reqstSvc(reqstSvc)
.prjctCd(prjctCd) .prjctCd(prjctCd)
@@ -250,16 +262,39 @@ public class TSendEntity {
.sendTel(basic.getSendTel()) .sendTel(basic.getSendTel())
.sendNm(basic.getSendNm()) .sendNm(basic.getSendNm())
.sendDt(sendDt) .sendDt(sendDt)
.sid(dest.getSid()) .sid(dest.sid())
.msgTitle(msgTitle) .msgTitle(msgTitle)
.msgBody(msgBody) .msgBody(msgBody)
.msgParam(dest.getMsgParam() != null ? dest.getMsgParam() : Map.of()) .msgParam(dest.msgParam() != null ? dest.msgParam() : Map.of())
.destEml(dest.getDestEml()) .destEml(dest.destEml())
.destTel(dest.getDestTel()) .destTel(dest.destTel())
.destNm(dest.getDestNm()) .destNm(dest.destNm())
.regCmpn(regCmpn) .regCmpn(regCmpn)
.regUser(regUser) .regUser(regUser)
.regDt(regDt) .regDt(regDt)
.build(); .build();
} }
public void prepareAttachmentPathForSend() {
if (atchFl == null || atchFl.isBlank() || !SMS_TYPE_CODE_LIST.contains(sendTy)) {
return;
}
if (tmplatIdx == null || tmplatIdx <= 0) {
throw new IllegalStateException("MMS attachment requires tmplatIdx.");
}
String prefix = tmplatIdx + "/";
String[] fileNames = atchFl.split("\\|", -1);
for (int i = 0; i < fileNames.length; i++) {
String fileName = fileNames[i];
if (fileName.startsWith(prefix)) {
continue;
}
if (fileName.isBlank() || fileName.indexOf('/') >= 0 || fileName.indexOf('\\') >= 0) {
throw new IllegalStateException("Invalid MMS attachment file name.");
}
fileNames[i] = prefix + fileName;
}
atchFl = String.join("|", fileNames);
}
} }

View File

@@ -32,6 +32,10 @@ public class TSendResultCodeEntity {
@Column(name = "result_view_label", nullable = false, length = 128) @Column(name = "result_view_label", nullable = false, length = 128)
private String resultViewLabel; private String resultViewLabel;
@NotNull
@Column(name = "result_code_type", nullable = false)
private Short resultCodeType;
@Size(max = 128) @Size(max = 128)
@Column(name = "memo", length = 128) @Column(name = "memo", length = 128)
private String memo; private String memo;

View File

@@ -41,9 +41,14 @@ public class TTmplatEntity {
@Column(name = "tmplat_ty", nullable = false) @Column(name = "tmplat_ty", nullable = false)
private Short tmplatTy; private Short tmplatTy;
@Size(max = 32)
@NotNull @NotNull
@Column(name = "tmplat_nm", nullable = false, length = 32) @ColumnDefault("0")
@Column(name = "tmplat_purpose", nullable = false)
private Short tmplatPurpose;
@Size(max = 128)
@NotNull
@Column(name = "tmplat_nm", nullable = false, length = 128)
private String tmplatNm; private String tmplatNm;
@Size(max = 128) @Size(max = 128)
@@ -121,6 +126,7 @@ public class TTmplatEntity {
return TTmplatEntity.builder() return TTmplatEntity.builder()
.itrntPrjctCd(itrntPrjctCd) .itrntPrjctCd(itrntPrjctCd)
.tmplatTy(template.getTmplatTy().getCode()) .tmplatTy(template.getTmplatTy().getCode())
.tmplatPurpose(template.getTmplatPurpose().getCode())
.tmplatNm(template.getTmplatNm()) .tmplatNm(template.getTmplatNm())
.tmplatTitle(template.getTmplatTitle()) .tmplatTitle(template.getTmplatTitle())
.tmplatBody(template.getTmplatBody()) .tmplatBody(template.getTmplatBody())
@@ -141,13 +147,13 @@ public class TTmplatEntity {
public void updateFrom(TemplateBasicDto template, String modUser, LocalDateTime modDt) { public void updateFrom(TemplateBasicDto template, String modUser, LocalDateTime modDt) {
// 기본 정보 갱신 // 기본 정보 갱신
this.tmplatTy = template.getTmplatTy().getCode(); this.tmplatTy = template.getTmplatTy().getCode();
this.tmplatPurpose = template.getTmplatPurpose().getCode();
this.tmplatNm = template.getTmplatNm(); this.tmplatNm = template.getTmplatNm();
this.tmplatTitle = template.getTmplatTitle(); this.tmplatTitle = template.getTmplatTitle();
this.tmplatBody = template.getTmplatBody(); this.tmplatBody = template.getTmplatBody();
this.senderKey = template.getSenderKey(); this.senderKey = template.getSenderKey();
this.kkoTmplatCd = template.getKkoTmplatCd(); this.kkoTmplatCd = template.getKkoTmplatCd();
this.nationCd = template.getNationCd(); this.nationCd = template.getNationCd();
this.atchFl = template.getAtchFl();
this.delayTime = template.getDelayTime(); this.delayTime = template.getDelayTime();
this.sendTel = template.getSendTel(); this.sendTel = template.getSendTel();
this.sendEml = template.getSendEml(); this.sendEml = template.getSendEml();

View File

@@ -0,0 +1,55 @@
package com.kri.notihub.server.persistence.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.math.BigDecimal;
import java.time.Instant;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter
@Setter
@Entity
@Table(name = "t_unit_price")
public class TUnitPriceEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "unit_price_idx", nullable = false)
private Integer id;
@NotNull
@Column(name = "send_ty", nullable = false)
private Short sendTy;
@NotNull
@Column(name = "send_corp", nullable = false)
private Short sendCorp;
@NotNull
@Column(name = "price", nullable = false)
private BigDecimal price;
@NotNull
@Column(name = "is_use", nullable = false)
private Boolean use;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
}

View File

@@ -2,7 +2,14 @@ package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.BizMsgEntity; import com.kri.notihub.server.persistence.entity.BizMsgEntity;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface BizMsgRepository extends JpaRepository<BizMsgEntity, String> { public interface BizMsgRepository extends JpaRepository<BizMsgEntity, String> {
// 사전 조회가 아닌 실제 DELETE 결과로 큐 제거 성공 여부를 판단한다.
@Modifying
@Query("delete from BizMsgEntity m where m.cmid = :cmid and m.status = 0")
int deleteWaiting(String cmid);
} }

View File

@@ -4,10 +4,16 @@ import com.kri.notihub.server.persistence.entity.TBulkSendEntity;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
public interface BulkSendRepository extends JpaRepository<TBulkSendEntity, String> { public interface BulkSendRepository extends JpaRepository<TBulkSendEntity, String> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select b from TBulkSendEntity b where b.bulkSendKey = :bulkSendKey")
Optional<TBulkSendEntity> findForUpdate(String bulkSendKey);
List<TBulkSendEntity> findByBulkSendKeyIn(List<String> bulkSendKeyList); List<TBulkSendEntity> findByBulkSendKeyIn(List<String> bulkSendKeyList);
@Query(""" @Query("""

View File

@@ -0,0 +1,22 @@
package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.TPhoneVerificationEntity;
import jakarta.persistence.LockModeType;
import java.time.LocalDateTime;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface PhoneVerificationRepository
extends JpaRepository<TPhoneVerificationEntity, String> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select v from TPhoneVerificationEntity v where v.verificationId = :verificationId")
Optional<TPhoneVerificationEntity> findByVerificationIdForUpdate(String verificationId);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TPhoneVerificationEntity v where v.expireDt <= :now")
int deleteExpired(LocalDateTime now);
}

View File

@@ -1,5 +1,10 @@
package com.kri.notihub.server.persistence.repository; package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.common.enums.ChannelType;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.dto.report.SendCostByTypeDto;
import com.kri.notihub.server.dto.report.SendResultLastWithSidDto;
import com.kri.notihub.server.dto.report.SendResultSummaryDto;
import com.kri.notihub.server.persistence.entity.TSendEntity; import com.kri.notihub.server.persistence.entity.TSendEntity;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
@@ -7,10 +12,57 @@ import java.util.Optional;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface SendRepository extends JpaRepository<TSendEntity, Long> { public interface SendRepository extends JpaRepository<TSendEntity, Long> {
// 목록과 벌크 집계에서 동일한 상태 기준을 사용한다. 취소 API의 잠금 후 판단이 최종이다.
String CANCELABLE_CONDITION = """
s.resve = true and s.sendStatus = 0 and s.cancelDt is null
and (
(s.sendTy = :emailSendType and s.resultCode = :emailStandbyCode)
or (s.sendTy in :bizSendTypes and exists (
select 1 from BizMsgEntity m where m.cmid = s.cmid and m.status = 0
))
)
""";
@Query("select s.sendIdx from TSendEntity s where s.sendIdx in :sendIds and ("
+ CANCELABLE_CONDITION + ")")
List<Long> findCancelableSendIds(List<Long> sendIds, short emailSendType,
short emailStandbyCode, List<Short> bizSendTypes);
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select s from TSendEntity s where s.sendIdx = :sendIdx")
Optional<TSendEntity> findForUpdate(Long sendIdx);
@Query("select s.sendIdx from TSendEntity s where s.bulkSendKey = :bulkSendKey "
+ "and s.sendIdx > :afterIdx order by s.sendIdx")
List<Long> findBulkSendIds(String bulkSendKey, Long afterIdx, Pageable pageable);
long countByBulkSendKeyAndSendStatus(String bulkSendKey, Short sendStatus);
interface CancellationCount {
String getBulkSendKey();
Long getCanceledCount();
Long getTargetCount();
Long getCancelableCount();
}
@Query("select s.bulkSendKey as bulkSendKey, "
+ "sum(case when s.sendStatus = 8 then 1L else 0L end) as canceledCount, "
+ "count(s) as targetCount, "
+ "sum(case when " + CANCELABLE_CONDITION + " then 1L else 0L end) as cancelableCount "
+ "from TSendEntity s where s.bulkSendKey in :bulkSendKeys "
+ "group by s.bulkSendKey")
List<CancellationCount> countCanceledByBulkSendKeys(List<String> bulkSendKeys,
short emailSendType, short emailStandbyCode, List<Short> bizSendTypes);
Optional<TSendEntity> findByCmid(String cmid); Optional<TSendEntity> findByCmid(String cmid);
@Query(""" @Query("""
@@ -24,16 +76,22 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
@Query(""" @Query("""
select s select s
from TSendEntity s from TSendEntity s
where s.sendStatus = :sendStatus where (s.sendStatus = :sendStatus or s.sendStatus = 8)
and s.sendTy in :sendTyList and s.sendTy in :sendTyList
and s.sendDt between :fromDt and :toDt and (s.resultCode in :resultCodes or s.sendStatus = 8)
and s.sendDt <= :now
and exists (
select 1
from BizLogEntity b
where b.cmid = s.cmid
)
order by s.sendIdx asc order by s.sendIdx asc
""") """)
List<TSendEntity> findSendListToRefreshWithinHours( List<TSendEntity> findSendListToRefresh(
List<Short> sendTyList, List<Short> sendTyList,
short sendStatus, short sendStatus,
LocalDateTime fromDt, List<Short> resultCodes,
LocalDateTime toDt, LocalDateTime now,
Pageable pageable Pageable pageable
); );
@@ -43,6 +101,8 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
where s.sendTy = :sendTy where s.sendTy = :sendTy
and s.resultCode = :resultCode and s.resultCode = :resultCode
and s.resve = true and s.resve = true
and s.sendStatus = 0
and s.cancelDt is null
and s.sendDt <= :now and s.sendDt <= :now
order by s.sendIdx asc order by s.sendIdx asc
""") """)
@@ -53,15 +113,183 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
Pageable pageable Pageable pageable
); );
@Query("""
select s
from TSendEntity s
where s.sendTy = :sendTy
and s.resultCode = :resultCode
and s.resve = false
and s.sendStatus = 0
and s.cancelDt is null
and s.bulkSendKey is not null
and s.sendDt <= :now
order by s.sendIdx asc
""")
List<TSendEntity> findBulkStandbySendEmail(
short sendTy,
short resultCode,
LocalDateTime now,
Pageable pageable
);
@Transactional
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
update TSendEntity s
set s.resultCode = :sendingResultCode
where s.sendIdx = :sendIdx
and s.resultCode = :standbyResultCode
and s.sendStatus = 0
and s.cancelDt is null
""")
int markEmailSending(
Long sendIdx,
short standbyResultCode,
short sendingResultCode
);
@Transactional
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
update TSendEntity s
set s.resultCode = :standbyResultCode
where s.sendTy = :sendTy
and s.resultCode = :sendingResultCode
and s.sendStatus = 0
and s.cancelDt is null
and s.resve = false
and s.bulkSendKey is not null
and s.sendDt <= :staleBefore
""")
int recoverStaleBulkEmailSending(
short sendTy,
short sendingResultCode,
short standbyResultCode,
LocalDateTime staleBefore
);
/** /**
* Poller 복구용: STANDBY_EMAIL 상태로 남아있는 최근 발송건을 다시 enqueue 하기 위해 사용 * Poller 복구용: STANDBY_EMAIL 상태로 남아있는 최근 발송건을 다시 enqueue 하기 위해 사용
*/ */
Page<TSendEntity> findBySendTyAndResultCodeAndSendDtAfterOrderBySendDtAsc( Page<TSendEntity> findBySendTyAndResultCodeInAndSendDtAfterOrderBySendDtAsc(
short sendTy, short sendTy,
short resultCode, List<Short> resultCodes,
LocalDateTime sendDtAfter, LocalDateTime sendDtAfter,
Pageable pageable Pageable pageable
); );
Page<TSendEntity> findByBulkSendKey(String bulkSendKey, Pageable pageable); Page<TSendEntity> findByBulkSendKey(String bulkSendKey, Pageable pageable);
List<TSendEntity> findBySidAndPrjctCdAndReqstSvcOrderBySendDtDescSendIdxDesc(
String sid,
String prjctCd,
String reqstSvc
);
List<TSendEntity> findBySidAndPrjctCdAndReqstSvcAndSendTyInOrderBySendDtDescSendIdxDesc(
String sid,
String prjctCd,
String reqstSvc,
List<Short> sendTyList
);
@Query("""
select new com.kri.notihub.server.dto.report.SendResultLastWithSidDto(
s.sid,
s.resultCode,
case when s.sendStatus = 8 then '예약 취소' else src.resultLabel end,
case when s.sendStatus = 8 then '예약 취소' else src.resultViewLabel end,
s.sendDt,
cast((
select count(sc)
from TSendEntity sc
where sc.sid = s.sid
and sc.prjctCd = :prjctCd
and sc.reqstSvc = :reqstSvc
and sc.sendTy in :sendTys
) as integer)
)
from TSendEntity s
left join TSendResultCodeEntity src
on s.sendCorp = src.id.sendCorp
and s.resultCode = src.id.resultCode
where s.sid in :sids
and (src.id.resultCode is not null or s.sendStatus = 8)
and s.prjctCd = :prjctCd
and s.reqstSvc = :reqstSvc
and s.sendTy in :sendTys
and not exists (
select 1
from TSendEntity last
where last.sid = s.sid
and last.prjctCd = :prjctCd
and last.reqstSvc = :reqstSvc
and last.sendTy in :sendTys
and last.sendIdx > s.sendIdx
)
order by s.sid desc
""")
List<SendResultLastWithSidDto> findSendResultLastWithSidBySid(
@Param("sendTys") List<Short> sendTys,
@Param("reqstSvc") String reqstSvc,
@Param("prjctCd") String prjctCd,
@Param("sids") List<String> sids
);
@Query("""
select new com.kri.notihub.server.dto.report.SendResultSummaryDto(
s.sendTy,
s.sendCorp,
sum(case when s.sendStatus <> 8 and src.resultCodeType = 1 then 1L else 0L end),
sum(case when s.sendStatus <> 8 and src.resultCodeType = 0 then 1L else 0L end),
sum(case when s.sendStatus <> 8 and src.resultCodeType = 9 then 1L else 0L end),
sum(case when s.sendStatus = 8 then 1L else 0L end),
count(s)
)
from TSendEntity s
left join TSendResultCodeEntity src
on s.sendCorp = src.id.sendCorp
and s.resultCode = src.id.resultCode
where (:bulkSendKey is null or s.bulkSendKey = :bulkSendKey)
and (src.id.resultCode is not null or s.sendStatus = 8)
and (:itrntPrjctCd is null or s.itrntPrjctCd = :itrntPrjctCd)
and (:reqstSvc is null or s.reqstSvc = :reqstSvc)
and (:prjctCd is null or s.prjctCd = :prjctCd)
and (:sendStartDt is null or s.sendDt >= :sendStartDt)
and (:sendEndDt is null or s.sendDt <= :sendEndDt)
group by s.sendTy, s.sendCorp
""")
List<SendResultSummaryDto> findSendResultSummary(
@Param("bulkSendKey") String bulkSendKey,
@Param("itrntPrjctCd") String itrntPrjctCd,
@Param("reqstSvc") String reqstSvc,
@Param("prjctCd") String prjctCd,
@Param("sendStartDt") LocalDateTime sendStartDt,
@Param("sendEndDt") LocalDateTime sendEndDt
);
@Query("""
select new com.kri.notihub.server.dto.report.SendCostByTypeDto(
s.reqstSvc,
s.itrntPrjctCd,
s.sendTy,
count(s),
sum(up.price)
)
from TSendEntity s
left join TUnitPriceEntity up
on up.sendTy = s.sendTy
and up.sendCorp = s.sendCorp
and up.use = true
where s.sendStatus = 1
and s.sendDt >= :startDt
and s.sendDt < :endDt
group by s.reqstSvc, s.itrntPrjctCd, s.sendTy
order by s.reqstSvc, s.itrntPrjctCd, s.sendTy
""")
List<SendCostByTypeDto> findSendCostSummaryWithItrntPrjct(
@Param("startDt") LocalDateTime startDt,
@Param("endDt") LocalDateTime endDt
);
} }

View File

@@ -1,27 +1,24 @@
package com.kri.notihub.server.persistence.repository; package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.TTmplatEntity; import com.kri.notihub.server.persistence.entity.TTmplatEntity;
import java.time.LocalDateTime; import jakarta.persistence.LockModeType;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
public interface TemplateRepository extends JpaRepository<TTmplatEntity, Long>, public interface TemplateRepository extends JpaRepository<TTmplatEntity, Long>,
JpaSpecificationExecutor<TTmplatEntity> { JpaSpecificationExecutor<TTmplatEntity> {
@Modifying(clearAutomatically = true, flushAutomatically = true) @Lock(LockModeType.PESSIMISTIC_WRITE)
@Query(""" @Query("select t from TTmplatEntity t where t.tmplatIdx = :idx and t.del = false")
update TTmplatEntity t Optional<TTmplatEntity> findActiveForUpdate(long idx);
set t.del = true,
t.delUser = :delUser, @Lock(LockModeType.PESSIMISTIC_WRITE)
t.delDt = :delDt @Query("select t from TTmplatEntity t where t.tmplatIdx = :idx")
where t.tmplatIdx = :idx Optional<TTmplatEntity> findForDelete(long idx);
and t.del = false
""")
int softDeleteByTmplatIdx(long idx, String delUser, LocalDateTime delDt);
List<TTmplatEntity> findAllByTmplatTyInAndItrntPrjctCdAndDelFalse(List<Short> tmplatTyList, List<TTmplatEntity> findAllByTmplatTyInAndItrntPrjctCdAndDelFalse(List<Short> tmplatTyList,
String itrntPrjctCd); String itrntPrjctCd);

View File

@@ -0,0 +1,10 @@
package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.TUnitPriceEntity;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UnitPriceRepository extends JpaRepository<TUnitPriceEntity, Integer> {
List<TUnitPriceEntity> findByUseTrue();
}

View File

@@ -1,32 +1,20 @@
package com.kri.notihub.server.scheduler; package com.kri.notihub.server.scheduler;
import com.kri.common.feature.datetime.DateTimeUtil; import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.util.StringUtil;
import com.kri.notihub.server.common.consts.NotihubConst; import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.SendStatusType; import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.persistence.entity.BizLogEntity;
import com.kri.notihub.server.persistence.entity.TBulkSendEntity;
import com.kri.notihub.server.persistence.entity.TSendEntity; import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.repository.BizLogRepository; import com.kri.notihub.server.persistence.repository.BizLogRepository;
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
import com.kri.notihub.server.persistence.repository.SendRepository; import com.kri.notihub.server.persistence.repository.SendRepository;
import com.kri.notihub.server.service.BizppurioSendCursorStore; import com.kri.notihub.server.service.BizppurioSendCursorStore;
import java.time.LocalDateTime; import com.kri.notihub.server.service.SendResultService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.stream.Stream;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -35,250 +23,51 @@ public class BizLogResultScheduler {
private final BizppurioSendCursorStore cursorStore; private final BizppurioSendCursorStore cursorStore;
private final SendRepository sendRepository; private final SendRepository sendRepository;
private final BizLogRepository bizLogRepository; private final BizLogRepository bizLogRepository;
private final BulkSendRepository bulkSendRepository; private final SendResultService resultService;
@Scheduled(fixedDelay = 60 * 1_000) // 나중에 증가시킬 것 @Value("${kri.sms.result-sync.batch-size:1000}")
@Transactional(transactionManager = "transactionManager") private int resultSyncBatchSize;
@Scheduled(fixedDelayString = "${kri.sms.result-sync.fixed-delay-ms:60000}")
public void syncSmsResults() { public void syncSmsResults() {
List<Short> types = Stream.concat(NotihubConst.SMS_TYPE_CODE_LIST.stream(),
TimeWindow window = buildWindow(1L); // hours는 추후 파라미터화 NotihubConst.KKO_TYPE_CODE_LIST.stream()).toList();
List<Short> codes = List.of(NotihubConst.SMS_STANDBY,
List<Short> sendTyList = List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode(), SendType.KKO_AT.getCode()); NotihubConst.LMS_MMS_STANDBY, NotihubConst.KKO_AT_STANDBY);
while (true) { while (true) {
List<TSendEntity> batch = fetchRefreshTargets(sendTyList, window, 1000); List<TSendEntity> sends = sendRepository.findSendListToRefresh(types,
if (batch.isEmpty()) { SendStatusType.STANDBY.getCode(), codes, DateTimeUtil.nowKstLocalDateTime(),
PageRequest.of(0, Math.max(1, resultSyncBatchSize)));
if (sends.isEmpty()) {
return; return;
} }
boolean updated = false;
BulkContext bulkCtx = loadBulkContext(batch); for (TSendEntity send : sends) {
var log = bizLogRepository.findTopByCmidOrderByReportTimeDesc(send.getCmid());
BatchResult result = applyResultsAndCollectDeltas(batch, bulkCtx); if (log.isEmpty()) {
persistChanges(result, bulkCtx);
}
}
private TimeWindow buildWindow(long hours) {
LocalDateTime toDt = LocalDateTime.now();
return new TimeWindow(toDt.minusHours(hours), toDt);
}
private List<TSendEntity> fetchRefreshTargets(List<Short> sendTyList, TimeWindow window,
int size) {
return sendRepository.findSendListToRefreshWithinHours(
sendTyList,
SendStatusType.STANDBY.getCode(),
window.from(),
window.to(),
PageRequest.of(0, size)
);
}
/**
* batch에서 bulkKey 수집 + bulk 엔티티 로딩 + Map 인덱싱
*/
private BulkContext loadBulkContext(List<TSendEntity> batch) {
Set<String> bulkKeys = extractBulkKeys(batch);
if (bulkKeys.isEmpty()) {
return new BulkContext(Set.of(), Map.of());
}
List<TBulkSendEntity> bulkEntities =
bulkSendRepository.findByBulkSendKeyIn(new ArrayList<>(bulkKeys));
Map<String, TBulkSendEntity> bulkMap = bulkEntities.stream()
.collect(Collectors.toMap(
TBulkSendEntity::getBulkSendKey,
Function.identity(),
(a, b) -> a
));
return new BulkContext(bulkKeys, bulkMap);
}
private Set<String> extractBulkKeys(List<TSendEntity> batch) {
return batch.stream()
.map(TSendEntity::getBulkSendKey)
.filter(k -> k != null && !k.isBlank())
.collect(Collectors.toSet());
}
/**
* BizLog 반영 + send/bulk delta 수집
*/
private BatchResult applyResultsAndCollectDeltas(List<TSendEntity> batch, BulkContext bulkCtx) {
Map<String, Integer> successDelta = new HashMap<>();
Map<String, Integer> failDelta = new HashMap<>();
List<TSendEntity> updatedSends = new ArrayList<>();
for (TSendEntity s : batch) {
if (!isResultPending(s)) {
continue; continue;
} }
short code = parseCode(log.get().getCallStatus());
Short beforeStatus = s.getSendStatus(); SendStatusType status = code == NotihubConst.SMS_SUCCESS
|| code == NotihubConst.LMS_MMS_SUCCESS || code == NotihubConst.KKO_AT_SUCCESS
bizLogRepository.findTopByCmidOrderByReportTimeDesc(s.getCmid()).ifPresent(log -> { ? SendStatusType.SUCCESS : SendStatusType.FAIL;
applySmsResultFromBizLog(s, log); if (resultService.record(send.getSendIdx(), null, status, code,
updatedSends.add(s); log.get().getReportTime()) != null) {
cursorStore.set(send.getSendIdx());
accumulateBulkDeltaIfNeeded(s, beforeStatus, bulkCtx.bulkMap(), successDelta, failDelta); updated = true;
});
} }
return new BatchResult(updatedSends, successDelta, failDelta);
} }
if (!updated) {
private boolean isResultPending(TSendEntity s) {
if (s == null) {
return false;
}
Short resultCode = s.getResultCode();
return resultCode != null
&& (resultCode == NotihubConst.SMS_STANDBY || resultCode == NotihubConst.LMS_MMS_STANDBY || resultCode == NotihubConst.KKO_AT_STANDBY);
}
/**
* STANDBY -> SUCCESS/FAIL 전이일 때만 bulk delta 누적
*/
private void accumulateBulkDeltaIfNeeded(
TSendEntity s,
Short beforeStatus,
Map<String, TBulkSendEntity> bulkMap,
Map<String, Integer> successDelta,
Map<String, Integer> failDelta
) {
String key = s.getBulkSendKey();
if (StringUtil.isNullOrBlank(key)) {
return; return;
} }
if (!bulkMap.containsKey(key)) {
return;
}
if (!Objects.equals(beforeStatus, SendStatusType.STANDBY.getCode())) {
return;
}
if (Objects.equals(s.getSendStatus(), SendStatusType.SUCCESS.getCode())) {
successDelta.merge(key, 1, Integer::sum);
} else if (Objects.equals(s.getSendStatus(), SendStatusType.FAIL.getCode())) {
failDelta.merge(key, 1, Integer::sum);
} }
} }
/** private short parseCode(String code) {
* 저장 + cursor + bulk 카운트 반영
*/
private void persistChanges(BatchResult result, BulkContext bulkCtx) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
if (!result.updatedSends().isEmpty()) {
sendRepository.saveAll(result.updatedSends());
sendRepository.flush();
// 마지막 갱신 sendIdx 기록(현재 로직 유지)
cursorStore.set(result.updatedSends().get(result.updatedSends().size() - 1).getSendIdx());
}
if (bulkCtx.bulkMap().isEmpty()) {
return;
}
applyBulkCountDeltas(bulkCtx.bulkMap(), result.successDelta(), result.failDelta(), now);
bulkSendRepository.saveAll(bulkCtx.bulkMap().values());
}
private void applyBulkCountDeltas(
Map<String, TBulkSendEntity> bulkMap,
Map<String, Integer> successDelta,
Map<String, Integer> failDelta,
LocalDateTime now
) {
Set<String> touched = new HashSet<>();
successDelta.forEach((k, d) -> {
TBulkSendEntity e = bulkMap.get(k);
if (e != null) {
int cur = e.getSuccesCnt() == null ? 0 : e.getSuccesCnt();
e.setSuccesCnt(cur + d);
touched.add(k);
}
});
failDelta.forEach((k, d) -> {
TBulkSendEntity e = bulkMap.get(k);
if (e != null) {
int cur = e.getFailCnt() == null ? 0 : e.getFailCnt();
e.setFailCnt(cur + d);
touched.add(k);
}
});
// 완료 처리: trgt_cnt <= succes_cnt + fail_cnt 되는 순간 complete_dt 세팅
for (String k : touched) {
TBulkSendEntity e = bulkMap.get(k);
if (e == null) {
continue;
}
if (e.getCompleteDt() != null) {
continue; // 이미 완료면 재세팅 방지
}
int trgt = e.getTrgtCnt() == null ? 0 : e.getTrgtCnt();
int success = e.getSuccesCnt() == null ? 0 : e.getSuccesCnt();
int fail = e.getFailCnt() == null ? 0 : e.getFailCnt();
if (trgt <= (success + fail)) {
e.setCompleteDt(now);
}
}
}
private void applySmsResultFromBizLog(TSendEntity s, BizLogEntity log) {
// ReportDt(LocalDateTime) 반영
// BizLogEntity.reportTime 타입이 Date면 LocalDateTime 변환 로직으로 바꾸세요.
s.setReportDt(log.getReportTime());
short callStatus = safeParseShort(log.getCallStatus(), NotihubConst.SMS_NOT_RESULT);
if (callStatus == NotihubConst.SMS_SUCCESS || callStatus == NotihubConst.LMS_MMS_SUCCESS || callStatus == NotihubConst.KKO_AT_SUCCESS) {
s.setSendStatus(SendStatusType.SUCCESS.getCode());
s.setResultCode(callStatus);
} else {
s.setSendStatus(SendStatusType.FAIL.getCode());
s.setResultCode(callStatus); // “그 외 실패”이지만, 실제 코드 보존이 운영/분석에 유리
}
}
private short safeParseShort(String v, short fallback) {
if (v == null || v.isBlank()) {
return fallback;
}
try { try {
return Short.parseShort(v.trim()); return Short.parseShort(code.trim());
} catch (Exception e) { } catch (RuntimeException ex) {
return fallback; return NotihubConst.SMS_NOT_RESULT;
} }
} }
private record TimeWindow(LocalDateTime from, LocalDateTime to) {
}
private record BulkContext(Set<String> bulkKeys, Map<String, TBulkSendEntity> bulkMap) {
}
private record BatchResult(List<TSendEntity> updatedSends,
Map<String, Integer> successDelta,
Map<String, Integer> failDelta) {
}
} }

View File

@@ -0,0 +1,192 @@
package com.kri.notihub.server.scheduler;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.common.external.pringo.dto.PringoSendRequestDto;
import com.kri.notihub.server.dto.send.DestInfoDto;
import com.kri.notihub.server.dto.send.SendInternalResultDto;
import com.kri.notihub.server.persistence.entity.TBulkSendEntity;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.entity.TTmplatEntity;
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
import com.kri.notihub.server.persistence.repository.SendRepository;
import com.kri.notihub.server.persistence.repository.TemplateRepository;
import com.kri.notihub.server.service.SendEmailService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class EmailBulkSendScheduler {
private final SendEmailService sendEmailService;
private final SendRepository sendRepository;
private final BulkSendRepository bulkSendRepository;
private final TemplateRepository templateRepository;
@Value("${kri.email.bulk-send.batch-size:500}")
private int batchSize;
@Value("${kri.email.bulk-send.sending-stale-minutes:30}")
private long sendingStaleMinutes;
@Scheduled(fixedDelayString = "${kri.email.bulk-send.fixed-delay-ms:10000}")
public void sendBulkEmail() {
recoverStaleSending();
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
List<TSendEntity> standbyList = sendRepository.findBulkStandbySendEmail(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_STANDBY,
now,
PageRequest.of(0, Math.max(1, batchSize))
);
Map<Long, TTmplatEntity> templateMap = loadTemplateMap(standbyList);
for (TSendEntity send : standbyList) {
if (!tryMarkSending(send)) {
continue;
}
SendInternalResultDto sendResult = sendEmail(send);
applySendResult(send, sendResult);
sendRepository.save(send);
if (sendResult.status() == SendStatusType.FAIL) {
increaseBulkFailCount(send.getBulkSendKey(), now);
} else {
sendEmailService.afterPersistSendEntities(List.of(send));
}
sleepSilently(resolveDelay(send, templateMap));
}
}
private Map<Long, TTmplatEntity> loadTemplateMap(List<TSendEntity> standbyList) {
List<Long> tmplatIdxList = standbyList.stream()
.map(TSendEntity::getTmplatIdx)
.filter(Objects::nonNull)
.distinct()
.toList();
if (tmplatIdxList.isEmpty()) {
return Map.of();
}
return templateRepository.findAllById(tmplatIdxList).stream()
.collect(Collectors.toMap(
TTmplatEntity::getTmplatIdx,
Function.identity(),
(a, b) -> a
));
}
private void recoverStaleSending() {
LocalDateTime staleBefore = DateTimeUtil.nowKstLocalDateTime()
.minusMinutes(Math.max(1, sendingStaleMinutes));
sendRepository.recoverStaleBulkEmailSending(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_SENDING,
NotihubConst.EMAIL_STANDBY,
staleBefore
);
}
private boolean tryMarkSending(TSendEntity send) {
if (send == null || send.getSendIdx() == null) {
return false;
}
int updated = sendRepository.markEmailSending(
send.getSendIdx(),
NotihubConst.EMAIL_STANDBY,
NotihubConst.EMAIL_SENDING
);
if (updated != 1) {
return false;
}
send.setResultCode(NotihubConst.EMAIL_SENDING);
return true;
}
private SendInternalResultDto sendEmail(TSendEntity send) {
PringoSendRequestDto pringoReq = sendEmailService.buildPringoSendRequest(
send.getSendEml(),
send.getSendNm(),
send.getMsgTitle(),
send.getMsgBody(),
send.getTmplatIdx(),
send.getAtchFl(),
DestInfoDto.from(send)
);
return sendEmailService.sendPringoEmail(pringoReq);
}
private void applySendResult(TSendEntity send, SendInternalResultDto sendResult) {
send.setCmid(sendResult.cmid());
send.setSendStatus(sendResult.status().getCode());
send.setResultCode(sendResult.resultCode());
}
private void increaseBulkFailCount(String bulkSendKey, LocalDateTime now) {
if (bulkSendKey == null || bulkSendKey.isBlank()) {
return;
}
bulkSendRepository.findByBulkSendKey(bulkSendKey).ifPresent(bulk -> {
int fail = bulk.getFailCnt() == null ? 0 : bulk.getFailCnt();
bulk.setFailCnt(fail + 1);
completeBulkIfNeeded(bulk, now);
bulkSendRepository.save(bulk);
});
}
private void completeBulkIfNeeded(TBulkSendEntity bulk, LocalDateTime now) {
if (bulk.getCompleteDt() != null) {
return;
}
int sendCnt = bulk.getSendCnt() == null ? 0 : bulk.getSendCnt();
int successCnt = bulk.getSuccesCnt() == null ? 0 : bulk.getSuccesCnt();
int failCnt = bulk.getFailCnt() == null ? 0 : bulk.getFailCnt();
if (sendCnt <= successCnt + failCnt) {
bulk.setCompleteDt(now);
}
}
private long resolveDelay(TSendEntity send, Map<Long, TTmplatEntity> templateMap) {
long templateDelay = 0L;
if (send != null && send.getTmplatIdx() != null) {
TTmplatEntity template = templateMap.get(send.getTmplatIdx());
if (template != null && template.getDelayTime() != null) {
templateDelay = template.getDelayTime();
}
}
return Math.max(templateDelay, NotihubConst.EMAIL_DELAY);
}
private void sleepSilently(long ms) {
if (ms <= 0) {
return;
}
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

View File

@@ -0,0 +1,18 @@
package com.kri.notihub.server.scheduler;
import com.kri.notihub.server.service.EmailResultPoller;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class EmailResultPollScheduler {
private final EmailResultPoller emailResultPoller;
@Scheduled(cron = "${kri.email.result-poll.recover-cron:0 */5 * * * *}")
public void enqueueRecoverableEmailResults() {
emailResultPoller.enqueueRecoverableEmailResults();
}
}

Some files were not shown because too many files have changed in this diff Show More