Compare commits

..

14 Commits

Author SHA1 Message Date
47d741de16 261026_01_ENH: 공연 상세정보에 관리번호(NCAS), 변경 메모 추가 2026-10-26 16:19:41 +09:00
b4f08e9e3a 261013_01_ENH: 사업 분류에 4추가 2026-10-13 14:59:46 +09:00
25bacaad45 260914_01_ENH: 사업 분류에 3추가 2026-09-14 15:54:18 +09:00
71a470ccb4 chore: adopt agent harness and update common starter 2026-08-07 15:42:01 +09:00
e3d0c83e7a 260713_01_ENH: 평가 파일 업로드 시 regUser를 지정 가능하게 수정 2026-07-13 11:28:52 +09:00
7ef2a78212 260708_06_ENH: pdf 변환 시작전 변환일시 null로 초기화 2026-07-08 16:55:09 +09:00
9c1b8a8649 260708_05_ENH: pdf 변환 종료(성공/실패)에 대한 일시 기입 추가 2026-07-08 16:39:59 +09:00
8e4e30c4e6 260708_04_DOC: git ignore 수정 2026-07-08 16:23:31 +09:00
21047390ac 260708_03_ENH: 파일 업로드 시 pdf 변환 async로 분리 2026-07-08 16:06:49 +09:00
91880ff65f 260708_02_ENH: 파일 업로드 시 pdf 변환 async로 분리 2026-07-08 15:46:40 +09:00
097cbddeb2 260708_01_ENH: 파일 업로드 용량 늘림 2026-07-08 14:29:30 +09:00
d2f3f195d3 260707_01_ENH: 출발 도착 삭제 가능기능 추가 2026-07-07 15:08:33 +09:00
6fc5b5ccf1 260702_02_ENH: KON ST LIST에서 BANNER로 수정 2026-07-02 16:34:44 +09:00
c61fa5f54b 260702_01_ENH: 사업 전체내용 조회 public path로 설정 2026-07-02 16:13:58 +09:00
41 changed files with 1188 additions and 112 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: gwcf-review-back
name: GWCF Monitoring Backend
type: requested-project
layer: backend
legacy: false
stack:
- java-springboot
shared_contracts:
consumes:
- kri-common
databases:
- id: gwcf-review
engine: mysql
role: primary-monitoring-data
access: read-write
- id: kon
engine: mssql
role: kon-reference-data
access: read-only

18
.agent/project.md Normal file
View File

@@ -0,0 +1,18 @@
# GWCF Monitoring Backend 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,21 @@
## GWCF Monitoring Backend Repository Rules
### Deliverable and Domain
- This Spring Boot backend manages GWCF performance records, monitoring assignments, schedules, visits, reviews, users, codes, files, templates, and event history.
- Its operational character is similar to KriContact, but its API, data, permissions, and deliverables remain project-specific contracts.
- Treat approved planning material and acceptance criteria as the scope boundary. Preserve assignment, confirmation, monitoring, visit, review, and user workflow state transitions.
### Data, File, and Integration Safety
- Preserve organization, performance, user, assignment, and role authorization boundaries for every query and mutation.
- Treat Excel uploads/downloads, review templates, PDF conversion, visit files, and stored paths as sensitive file-lifecycle operations. Validate names, paths, sizes, types, cleanup, and partial failures.
- Keep MySQL JPA/QueryDSL persistence separate from the read-only KON MSSQL/MyBatis integration. Do not mix dialects, transactions, entities, or mapper assumptions.
- Make retries and duplicate submissions safe for assignment, confirmation, visit, upload, and review operations.
- Do not expose personal information, monitoring details, customer documents, raw file paths, or unrestricted event logs.
### Shared Library and Verification
- Consume `com.kri.common:starter:beta.1.6.3` and use public `com.kri.common.feature.*` APIs. Do not duplicate a KriCommon feature locally.
- `AGENTS.md` and `CLAUDE.md` are generated. Edit `.agent/profile.yml` or `.agent/project.md`, then recompose instead of editing generated files.
- Use the Gradle Wrapper and narrow safe checks. Do not connect to real databases, run the PDF converter, or process customer files during validation without separate 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.

5
.gitattributes vendored
View File

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

3
.gitignore vendored
View File

@@ -1,6 +1,8 @@
HELP.md HELP.md
.gradle .gradle
build/ build/
logs/
upload-file/
!gradle/wrapper/gradle-wrapper.jar !gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/ !**/src/main/**/build/
!**/src/test/**/build/ !**/src/test/**/build/
@@ -19,6 +21,7 @@ bin/
### IntelliJ IDEA ### ### IntelliJ IDEA ###
.idea .idea
.idea_bak
*.iws *.iws
*.iml *.iml
*.ipr *.ipr

288
AGENTS.md Normal file
View File

@@ -0,0 +1,288 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: gwcf-review-back
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.
## Requested Project Rules
- Treat the approved requirements, acceptance criteria, and recorded decisions as the primary scope boundary.
- Do not infer a requirement solely from a file name, folder date, or apparently newer document.
- When requirements conflict, report the exact sources and request a decision.
- Preserve original customer, partner, and planning documents as read-only evidence unless document editing is explicitly approved.
- Summarize durable implementation requirements inside the repository rather than relying only on files outside the repository.
- Do not expand the deliverable with speculative features, infrastructure, or architectural changes.
- Record material assumptions and unresolved decisions in the project-specific rules or existing project documentation.
- Define observable acceptance criteria before implementation.
- Treat separately managed Frontend and Backend repositories as independent deliverables with a coordinated contract.
- Protect customer, partner, survey, and field data as sensitive information.
- Keep handoff, operation, configuration, and validation instructions usable by the requesting team.
- Report deviations from the requested scope and obtain approval before proceeding.
## 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.
## Microsoft SQL Server
- Use T-SQL syntax and behavior only for data sources whose declared engine is `mssql`.
- Preserve the configured SQL Server version, database and schema names, collation, naming, migration, and access conventions.
- Parameterize values. Do not build SQL by concatenating untrusted input.
- Preserve Unicode behavior and use the repository's established `nvarchar`/`nchar` and parameter conventions where Korean or other Unicode text is possible.
- Treat stored-procedure parameters, result sets, return values, transaction behavior, and error behavior as public contracts.
- Consider indexes and actual execution characteristics for changed filters, joins, ordering, grouping, and pagination.
- Do not introduce MySQL or other dialect syntax into MSSQL paths.
- Keep read-only legacy integrations read-only. A source-code change approval authorizes SQL analysis and script drafting only; execution requires 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.
# GWCF Monitoring Backend 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

View File

@@ -30,7 +30,7 @@ repositories {
} }
} }
dependencies { dependencies {
implementation "com.kri.common:starter:beta.1.1.29" implementation "com.kri.common:starter:beta.1.6.4"
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'

View File

@@ -11,6 +11,14 @@ public final class GwcfConstant {
public static final Integer MONITORING_USER_ROLE = 9003; public static final Integer MONITORING_USER_ROLE = 9003;
public static final Short REJECT_ASSIGN_ORDER = 9999; public static final Short REJECT_ASSIGN_ORDER = 9999;
public static final Integer MONITORING_REVIEW_TYPE = 1;
public static final Integer MONITORING_VISIT_DEPARTURE_STATUS = 2;
public static final Integer MONITORING_VISIT_ARRIVAL_STATUS = 3;
public static final List<Integer> REVIEW_TYPE = List.of(1, 3); public static final List<Integer> REVIEW_TYPE = List.of(1, 3);
public static final List<Integer> REVIEW_CLASSIFICATION = List.of(1, 5, 99); public static final List<Integer> REVIEW_CLASSIFICATION = List.of(1, 3, 4, 5, 99);
public static final List<Integer> MONITORING_VISIT_RESETTABLE_REVIEW_STATUS = List.of(
MONITORING_VISIT_DEPARTURE_STATUS,
MONITORING_VISIT_ARRIVAL_STATUS
);
} }

View File

@@ -32,6 +32,7 @@ public enum SystemEventType implements CodeEnum<Short> {
VISIT_START((short) 2011), //모니터링 출발 VISIT_START((short) 2011), //모니터링 출발
VISIT_END((short) 2012), //모니터링 도착 VISIT_END((short) 2012), //모니터링 도착
VISIT_RESET((short) 2099), //모니터링 출발.도착 초기화
UPLOAD_MONITORING_REVIEW((short) 2041), //모니터링 결과보고서 업로드 UPLOAD_MONITORING_REVIEW((short) 2041), //모니터링 결과보고서 업로드
UPLOAD_LOCAL_GOV_REVIEW((short) 2042), //지자체 결과보고서 업로드 UPLOAD_LOCAL_GOV_REVIEW((short) 2042), //지자체 결과보고서 업로드

View File

@@ -0,0 +1,23 @@
package com.kri.gwcf.review.back.config;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "pdfConvertTaskExecutor")
public Executor pdfConvertTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("pdf-convert-");
executor.initialize();
return executor;
}
}

View File

@@ -124,7 +124,7 @@ public class AssignController {
ctx.getUserId(), ctx.getUserId(),
now, now,
ctx.getClientIp(), ctx.getClientIp(),
UploadContentDto.from(file) UploadContentDto.from(file, ctx.getUserId())
); );
return result; return result;
} }

View File

@@ -16,6 +16,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
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.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@@ -79,6 +80,25 @@ public class MonitoringVisitController {
return visitService.findEvidence(performanceId, userId); return visitService.findEvidence(performanceId, userId);
} }
@Operation(summary = "모니터링 방문 초기화")
@DeleteMapping("/reset/{performanceId}/{userId}")
public void reset(
@PathVariable Integer performanceId,
@PathVariable String userId,
RequestUserContext ctx
) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
visitService.reset(performanceId, userId);
systemEventLogService.writeVisitResetLog(
ctx.getUserId(),
now,
ctx.getClientIp(),
performanceId,
userId
);
}
@Operation(summary = "증빙 사진 ZIP 다운로드") @Operation(summary = "증빙 사진 ZIP 다운로드")
@GetMapping("/evidence/zip/{performanceId}/{userId}") @GetMapping("/evidence/zip/{performanceId}/{userId}")
public ResponseEntity<byte[]> downloadEvidenceZip( public ResponseEntity<byte[]> downloadEvidenceZip(

View File

@@ -89,7 +89,7 @@ public class PerformanceController {
ExcelUploadResultDto result = performanceService.createPerformancesFromExcel(file, regId, now); ExcelUploadResultDto result = performanceService.createPerformancesFromExcel(file, regId, now);
systemEventLogService.writeUploadPerformanceLog(regId, now, clientIp, UploadContentDto.from(file)); systemEventLogService.writeUploadPerformanceLog(regId, now, clientIp, UploadContentDto.from(file, regId));
return result; return result;
} }

View File

@@ -65,18 +65,21 @@ public class ReviewController {
public PerformanceReviewDto uploadReviewFile( public PerformanceReviewDto uploadReviewFile(
@PathVariable Integer performanceId, @PathVariable Integer performanceId,
@PathVariable Integer reviewType, @PathVariable Integer reviewType,
@RequestParam(required = false) String paramUserId,
@RequestParam("file") MultipartFile file, @RequestParam("file") MultipartFile file,
RequestUserContext ctx RequestUserContext ctx
) { ) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime(); LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
PerformanceReviewDto result = reviewService.uploadReviewFile(performanceId, reviewType, file, ctx.getUserId(), now); String userId = paramUserId != null ? paramUserId : ctx.getUserId();
PerformanceReviewDto result = reviewService.uploadReviewFile(performanceId, reviewType, file, userId, now);
systemEventLogService.writeUploadReviewFileLog( systemEventLogService.writeUploadReviewFileLog(
ctx.getUserId(), ctx.getUserId(),
now, now,
ctx.getClientIp(), ctx.getClientIp(),
performanceId, performanceId,
reviewType, reviewType,
UploadContentDto.from(file) UploadContentDto.from(file, userId)
); );
return result; return result;
} }

View File

@@ -86,7 +86,7 @@ public class UserController {
ExcelUploadResultDto result = userService.createUsersFromExcel(userRole, file, regId, now); ExcelUploadResultDto result = userService.createUsersFromExcel(userRole, file, regId, now);
systemEventLogService.writeUploadUserLog(regId, now, clientIp, UploadContentDto.from(file)); systemEventLogService.writeUploadUserLog(regId, now, clientIp, UploadContentDto.from(file, regId));
return result; return result;
} }

View File

@@ -15,51 +15,60 @@ import lombok.experimental.SuperBuilder;
@AllArgsConstructor @AllArgsConstructor
public class PerformanceDownloadDto extends PerformanceUploadDto { public class PerformanceDownloadDto extends PerformanceUploadDto {
@ExcelColumn(header = "지자체 평가자", order = 31, width = 16) @ExcelColumn(header = "지자체 평가자", order = 32, width = 16)
@Schema(description = "지자체 평가자") @Schema(description = "지자체 평가자")
private String localReviewUser; private String localReviewUser;
@ExcelColumn(header = "지자체 평가 상태", order = 32, width = 16) @ExcelColumn(header = "지자체 평가 상태", order = 33, width = 16)
@Schema(description = "지자체 평가 상태") @Schema(description = "지자체 평가 상태")
private String localReviewStatus; private String localReviewStatus;
@ExcelColumn(header = "지자체 평가 일시", order = 33, width = 16) @ExcelColumn(header = "지자체 평가 일시", order = 34, width = 16)
@Schema(description = "지자체 평가 일시") @Schema(description = "지자체 평가 일시")
private String localReviewDt; private String localReviewDt;
@ExcelColumn(header = "모니터링1 평가자", order = 34, width = 16) @ExcelColumn(header = "모니터링1 평가자", order = 35, width = 16)
@Schema(description = "모니터링1 평가자") @Schema(description = "모니터링1 평가자")
private String monitoringReviewUser1; private String monitoringReviewUser1;
@ExcelColumn(header = "모니터링1 평가 상태", order = 35, width = 16) @ExcelColumn(header = "모니터링1 평가 상태", order = 36, width = 16)
@Schema(description = "모니터링1 평가 상태") @Schema(description = "모니터링1 평가 상태")
private String monitoringReviewStatus1; private String monitoringReviewStatus1;
@ExcelColumn(header = "모니터링1 평가 일시", order = 36, width = 16) @ExcelColumn(header = "모니터링1 평가 일시", order = 37, width = 16)
@Schema(description = "모니터링1 평가 일시") @Schema(description = "모니터링1 평가 일시")
private String monitoringReviewDt1; private String monitoringReviewDt1;
@ExcelColumn(header = "모니터링2 평가자", order = 37, width = 16) @ExcelColumn(header = "모니터링2 평가자", order = 38, width = 16)
@Schema(description = "모니터링2 평가자") @Schema(description = "모니터링2 평가자")
private String monitoringReviewUser2; private String monitoringReviewUser2;
@ExcelColumn(header = "모니터링2 평가 상태", order = 38, width = 16) @ExcelColumn(header = "모니터링2 평가 상태", order = 39, width = 16)
@Schema(description = "모니터링2 평가 상태") @Schema(description = "모니터링2 평가 상태")
private String monitoringReviewStatus2; private String monitoringReviewStatus2;
@ExcelColumn(header = "모니터링2 평가 일시", order = 32, width = 16) @ExcelColumn(header = "모니터링2 평가 일시", order = 40, width = 16)
@Schema(description = "모니터링2 평가 일시") @Schema(description = "모니터링2 평가 일시")
private String monitoringReviewDt2; private String monitoringReviewDt2;
@ExcelColumn(header = "서면 평가 위원", order = 33, width = 16) @ExcelColumn(header = "서면 평가 위원", order = 41, width = 16)
@Schema(description = "서면 평가 위원") @Schema(description = "서면 평가 위원")
private String writtenReviewUser; private String writtenReviewUser;
@ExcelColumn(header = "서면 평가 상태", order = 34, width = 16) @ExcelColumn(header = "서면 평가 상태", order = 42, width = 16)
@Schema(description = "서면 평가 상태") @Schema(description = "서면 평가 상태")
private String writtenReviewStatus; private String writtenReviewStatus;
@ExcelColumn(header = "서면 평가 일시", order = 35, width = 16) @ExcelColumn(header = "서면 평가 일시", order = 43, width = 16)
@Schema(description = "서면 평가 일시") @Schema(description = "서면 평가 일시")
private String writtenReviewDt; private String writtenReviewDt;
@ExcelColumn(header = "변경 사항", order = 44, width = 20)
private String updateNoticeTarget;
@ExcelColumn(header = "변경 내용", order = 45, width = 40)
private String updateNoticeMemo;
@ExcelColumn(header = "변경 일시", order = 46, width = 26)
private String updateNoticeDt;
} }

View File

@@ -23,119 +23,123 @@ public class PerformanceUploadDto {
@Schema(description = "연번") @Schema(description = "연번")
private String performanceId; private String performanceId;
@ExcelColumn(header = "사업유형", order = 2, width = 10) @ExcelColumn(header = "관리번호", order = 2, width = 18)
@Schema(description = "숫자로 구성된 관리번호")
private String ncas;
@ExcelColumn(header = "사업유형", order = 3, width = 10)
@Schema(description = "사업유형") @Schema(description = "사업유형")
private String businessType; private String businessType;
@ExcelColumn(header = "분야(장르)", order = 3, width = 10) @ExcelColumn(header = "분야(장르)", order = 4, width = 10)
@Schema(description = "분야(장르)") @Schema(description = "분야(장르)")
private String genre; private String genre;
@ExcelColumn(header = "지역", order = 4, width = 10) @ExcelColumn(header = "지역", order = 5, width = 10)
@Schema(description = "지역") @Schema(description = "지역")
private String performanceArea; private String performanceArea;
@ExcelColumn(header = "지역 세부", order = 5, width = 10) @ExcelColumn(header = "지역 세부", order = 6, width = 10)
@Schema(description = "지역 세부") @Schema(description = "지역 세부")
private String performanceAreaDetail; private String performanceAreaDetail;
@ExcelColumn(header = "단체(인) 명", order = 6, width = 11) @ExcelColumn(header = "단체(인) 명", order = 7, width = 11)
@Schema(description = "단체(인) 명") @Schema(description = "단체(인) 명")
private String artistName; private String artistName;
@ExcelColumn(header = "사업 명", order = 7, width = 10) @ExcelColumn(header = "사업 명", order = 8, width = 10)
@Schema(description = "사업 명") @Schema(description = "사업 명")
private String performanceName; private String performanceName;
@ExcelColumn(header = "사업 수행 월", order = 8, width = 12) @ExcelColumn(header = "사업 수행 월", order = 9, width = 12)
@Schema(description = "사업 수행 월") @Schema(description = "사업 수행 월")
private String performanceStartMonth; private String performanceStartMonth;
@ExcelColumn(header = "사업 일정", order = 9, width = 10) @ExcelColumn(header = "사업 일정", order = 10, width = 10)
@Schema(description = "사업 일정") @Schema(description = "사업 일정")
private String performanceDtInfo; private String performanceDtInfo;
@ExcelColumn(header = "운영 시간", order = 10, width = 10) @ExcelColumn(header = "운영 시간", order = 11, width = 10)
@Schema(description = "운영 시간") @Schema(description = "운영 시간")
private String performanceTimeInfo; private String performanceTimeInfo;
@ExcelColumn(header = "티켓 예약", order = 11, width = 10) @ExcelColumn(header = "티켓 예약", order = 12, width = 10)
@Schema(description = "티켓 예약") @Schema(description = "티켓 예약")
private String ticketReservationStatus; private String ticketReservationStatus;
@ExcelColumn(header = "티켓 비고", order = 12, width = 10) @ExcelColumn(header = "티켓 비고", order = 13, width = 10)
@Schema(description = "티켓 비고") @Schema(description = "티켓 비고")
private String ticketReservationMemo; private String ticketReservationMemo;
@ExcelColumn(header = "모니터링 일정", order = 13, width = 14) @ExcelColumn(header = "모니터링 일정", order = 14, width = 14)
@Schema(description = "모니터링 일정") @Schema(description = "모니터링 일정")
private String monitoringDate; private String monitoringDate;
@ExcelColumn(header = "모니터링 시간", order = 14, width = 14) @ExcelColumn(header = "모니터링 시간", order = 15, width = 14)
@Schema(description = "모니터링 시간") @Schema(description = "모니터링 시간")
private String monitoringTimeInfo; private String monitoringTimeInfo;
@ExcelColumn(header = "모니터링 필요여부", order = 15, width = 14) @ExcelColumn(header = "모니터링 필요여부", order = 16, width = 14)
@Schema(description = "모니터링 필요여부") @Schema(description = "모니터링 필요여부")
private String needMonitoring; private String needMonitoring;
@ExcelColumn(header = "서면평가 필요여부", order = 16, width = 14) @ExcelColumn(header = "서면평가 필요여부", order = 17, width = 14)
@Schema(description = "서면평가 필요여부") @Schema(description = "서면평가 필요여부")
private String needWrittenReview; private String needWrittenReview;
@ExcelColumn(header = "교부여부", order = 17, width = 14) @ExcelColumn(header = "교부여부", order = 18, width = 14)
@Schema(description = "교부여부") @Schema(description = "교부여부")
private String checkDeliver; private String checkDeliver;
@ExcelColumn(header = "타임트리 확인일시", order = 18, width = 14) @ExcelColumn(header = "타임트리 확인일시", order = 19, width = 14)
@Schema(description = "타임트리 확인일시") @Schema(description = "타임트리 확인일시")
private String timeTreeCheckDt; private String timeTreeCheckDt;
@ExcelColumn(header = "모니터링 방문 장소", order = 19, width = 18) @ExcelColumn(header = "모니터링 방문 장소", order = 20, width = 18)
@Schema(description = "모니터링 방문 장소") @Schema(description = "모니터링 방문 장소")
private String monitoringAddress; private String monitoringAddress;
@ExcelColumn(header = "메모", order = 20, width = 10) @ExcelColumn(header = "메모", order = 21, width = 10)
@Schema(description = "메모") @Schema(description = "메모")
private String performanceMemo; private String performanceMemo;
@ExcelColumn(header = "보고서 확인여부", order = 21, width = 10) @ExcelColumn(header = "보고서 확인여부", order = 22, width = 10)
@Schema(description = "보고서 확인여부") @Schema(description = "보고서 확인여부")
private String checkReport; private String checkReport;
@ExcelColumn(header = "요원 비용지급일", order = 22, width = 16) @ExcelColumn(header = "요원 비용지급일", order = 23, width = 16)
@Schema(description = "요원 비용지급일") @Schema(description = "요원 비용지급일")
private String monitoringPaymentDate; private String monitoringPaymentDate;
@ExcelColumn(header = "대표자 명", order = 23, width = 10) @ExcelColumn(header = "대표자 명", order = 24, width = 10)
@Schema(description = "대표자 명") @Schema(description = "대표자 명")
private String ownStaffName; private String ownStaffName;
@ExcelColumn(header = "대표자 연락처1", order = 24, width = 14) @ExcelColumn(header = "대표자 연락처1", order = 25, width = 14)
@Schema(description = "대표자 연락처1") @Schema(description = "대표자 연락처1")
private String ownStaffTel1; private String ownStaffTel1;
@ExcelColumn(header = "대표자 연락처2", order = 25, width = 14) @ExcelColumn(header = "대표자 연락처2", order = 26, width = 14)
@Schema(description = "대표자 연락처2") @Schema(description = "대표자 연락처2")
private String ownStaffTel2; private String ownStaffTel2;
@ExcelColumn(header = "대표자 이메일", order = 26, width = 14) @ExcelColumn(header = "대표자 이메일", order = 27, width = 14)
@Schema(description = "대표자 이메일") @Schema(description = "대표자 이메일")
private String ownStaffEmail; private String ownStaffEmail;
@ExcelColumn(header = "실무자 명", order = 27, width = 10) @ExcelColumn(header = "실무자 명", order = 28, width = 10)
@Schema(description = "실무자 명") @Schema(description = "실무자 명")
private String contactStaffName; private String contactStaffName;
@ExcelColumn(header = "실무자 연락처1", order = 28, width = 14) @ExcelColumn(header = "실무자 연락처1", order = 29, width = 14)
@Schema(description = "실무자 연락처1") @Schema(description = "실무자 연락처1")
private String contactStaffTel1; private String contactStaffTel1;
@ExcelColumn(header = "실무자 연락처2", order = 29, width = 14) @ExcelColumn(header = "실무자 연락처2", order = 30, width = 14)
@Schema(description = "실무자 연락처2") @Schema(description = "실무자 연락처2")
private String contactStaffTel2; private String contactStaffTel2;
@ExcelColumn(header = "실무자 이메일", order = 30, width = 14) @ExcelColumn(header = "실무자 이메일", order = 31, width = 14)
@Schema(description = "실무자 이메일") @Schema(description = "실무자 이메일")
private String contactStaffEmail; private String contactStaffEmail;
} }

View File

@@ -36,7 +36,7 @@ public class PerformanceReviewDto {
private String uploadFileName; private String uploadFileName;
@Schema(description = "pdf로 변환성공 여부") @Schema(description = "pdf로 변환성공 여부")
private Boolean pdfConvert; private Short pdfConvert;
@Schema(description = "pdf로 변환된 파일명") @Schema(description = "pdf로 변환된 파일명")
private String pdfFileName; private String pdfFileName;

View File

@@ -16,12 +16,14 @@ public class UploadContentDto {
String fileName; String fileName;
String fileType; String fileType;
Long fileSize; Long fileSize;
String uploadUserId;
public static UploadContentDto from(MultipartFile file){ public static UploadContentDto from(MultipartFile file, String uploadUserId){
return UploadContentDto.builder() return UploadContentDto.builder()
.fileName(file.getOriginalFilename()) .fileName(file.getOriginalFilename())
.fileType(file.getContentType()) .fileType(file.getContentType())
.fileSize(file.getSize()) .fileSize(file.getSize())
.uploadUserId(uploadUserId)
.build(); .build();
} }
} }

View File

@@ -36,12 +36,15 @@ public class TPerformanceReviewEntity {
@NotNull @NotNull
@Column(name = "is_pdf_convert", nullable = false) @Column(name = "is_pdf_convert", nullable = false)
private Boolean pdfConvert; private Short pdfConvert;
@NotNull @NotNull
@Column(name = "pdf_file_name", nullable = false, length = 512) @Column(name = "pdf_file_name", nullable = false, length = 512)
private String pdfFileName; private String pdfFileName;
@Column(name = "pdf_convert_dt", insertable = false)
private LocalDateTime pdfConvertDt;
@NotNull @NotNull
@ColumnDefault("CURRENT_TIMESTAMP") @ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false, updatable = false) @Column(name = "reg_dt", nullable = false, updatable = false)

View File

@@ -16,4 +16,9 @@ public interface PerformanceMonitoringVisitRepository extends JpaRepository<TPer
Integer performanceId, Integer performanceId,
String regUser String regUser
); );
void deleteByPerformanceIdAndRegUser(
Integer performanceId,
String regUser
);
} }

View File

@@ -20,6 +20,13 @@ public interface PerformanceReviewRepository extends JpaRepository<TPerformanceR
String regUser String regUser
); );
Optional<TPerformanceReviewEntity> findByIdPerformanceIdAndIdReviewTypeAndIdRegUserAndReviewStatusIn(
Integer performanceId,
Integer reviewType,
String regUser,
List<Integer> reviewStatuses
);
boolean existsByIdPerformanceIdAndIdReviewTypeAndIdRegUser( boolean existsByIdPerformanceIdAndIdReviewTypeAndIdRegUser(
Integer performanceId, Integer performanceId,
Integer reviewType, Integer reviewType,

View File

@@ -63,7 +63,7 @@ import org.springframework.web.multipart.MultipartFile;
@RequiredArgsConstructor @RequiredArgsConstructor
public class PerformanceService { public class PerformanceService {
private static final DateTimeFormatter REVIEW_DT_FORMATTER = private static final DateTimeFormatter EXCEL_DT_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final KonMapper konMapper; private final KonMapper konMapper;
@@ -247,12 +247,15 @@ public class PerformanceService {
} }
public byte[] exportPerformance(String[] performanceIds) { public byte[] exportPerformance(String[] performanceIds) {
Map<String, String> updateNoticeTargetLabels = codeService
.findByCodeGroup("update_notice_target").stream()
.collect(toMap(code -> code.getCodeValue().toString(), CodeDto::getCodeLabel));
Set<String> selectedPerformanceIds = performanceIds == null Set<String> selectedPerformanceIds = performanceIds == null
? Collections.emptySet() ? Collections.emptySet()
: Arrays.stream(performanceIds).collect(Collectors.toSet()); : Arrays.stream(performanceIds).collect(Collectors.toSet());
List<PerformanceDownloadDto> performanceList = getPerformanceList().stream() List<PerformanceDownloadDto> performanceList = getPerformanceList().stream()
.filter(performance -> selectedPerformanceIds.contains(String.valueOf(performance.getId()))) .filter(performance -> selectedPerformanceIds.contains(String.valueOf(performance.getId())))
.map(this::toPerformanceDownloadRow) .map(performance -> toPerformanceDownloadRow(performance, updateNoticeTargetLabels))
.toList(); .toList();
List<CodeDto> businessTypeList = codeService.findByCodeGroup("business_type"); List<CodeDto> businessTypeList = codeService.findByCodeGroup("business_type");
@@ -279,7 +282,10 @@ public class PerformanceService {
} }
} }
private PerformanceDownloadDto toPerformanceDownloadRow(PerformanceFullDto performance) { private PerformanceDownloadDto toPerformanceDownloadRow(
PerformanceFullDto performance,
Map<String, String> updateNoticeTargetLabels
) {
Map<String, String> detail = performance.getPerformanceDetail() == null Map<String, String> detail = performance.getPerformanceDetail() == null
? Collections.emptyMap() ? Collections.emptyMap()
: performance.getPerformanceDetail(); : performance.getPerformanceDetail();
@@ -308,6 +314,12 @@ public class PerformanceService {
); );
return PerformanceDownloadDto.builder() return PerformanceDownloadDto.builder()
.ncas(detail.get("NCAS"))
.updateNoticeTarget(updateNoticeTargetLabels.getOrDefault(
detail.get("UpdateNoticeTarget"),
detail.get("UpdateNoticeTarget")))
.updateNoticeMemo(detail.get("UpdateNoticeMemo"))
.updateNoticeDt(formatUpdateNoticeDt(detail.get("UpdateNoticeDt")))
.performanceId(toStringValue(performance.getId())) .performanceId(toStringValue(performance.getId()))
.businessType(toStringValue(performance.getBusinessType())) .businessType(toStringValue(performance.getBusinessType()))
.genre(toStringValue(performance.getPerformanceGenre())) .genre(toStringValue(performance.getPerformanceGenre()))
@@ -418,7 +430,13 @@ public class PerformanceService {
private String formatReviewDt(PerformanceReviewDto review) { private String formatReviewDt(PerformanceReviewDto review) {
return review == null || review.getReviewDt() == null return review == null || review.getReviewDt() == null
? null ? null
: review.getReviewDt().format(REVIEW_DT_FORMATTER); : review.getReviewDt().format(EXCEL_DT_FORMATTER);
}
private String formatUpdateNoticeDt(String value) {
return StringUtil.isNullOrBlank(value)
? null
: LocalDateTime.parse(value).format(EXCEL_DT_FORMATTER);
} }
private String toStringValue(Object value) { private String toStringValue(Object value) {
@@ -597,6 +615,11 @@ public class PerformanceService {
) { ) {
List<ExcelErrorDto> errors = new ArrayList<>(); List<ExcelErrorDto> errors = new ArrayList<>();
String ncas = Objects.toString(row.getNcas(), "");
if (!ncas.matches("[0-9]*") || ncas.length() > 2048) {
errors.add(ExcelErrorDto.of(rowNumber, "관리번호", "관리번호는 2048자 이내의 숫자만 입력할 수 있습니다."));
}
Integer performanceNo = NumericUtil.parseOnlyInteger(row.getPerformanceNo()); Integer performanceNo = NumericUtil.parseOnlyInteger(row.getPerformanceNo());
if (performanceNo == null) { if (performanceNo == null) {
errors.add(ExcelErrorDto.of(rowNumber, "No", "No는 숫자여야 합니다.")); errors.add(ExcelErrorDto.of(rowNumber, "No", "No는 숫자여야 합니다."));
@@ -692,6 +715,7 @@ public class PerformanceService {
LocalDateTime regDt LocalDateTime regDt
) { ) {
Map<String, String> detail = new LinkedHashMap<>(); Map<String, String> detail = new LinkedHashMap<>();
detail.put("NCAS", Objects.toString(row.getNcas(), ""));
detail.put("monitoringPaymentDate", Objects.toString(StringUtil.normalizeBlank(row.getMonitoringPaymentDate()), "")); detail.put("monitoringPaymentDate", Objects.toString(StringUtil.normalizeBlank(row.getMonitoringPaymentDate()), ""));
detail.put("performanceNo", Objects.toString(StringUtil.normalizeBlank(row.getPerformanceNo()), "")); detail.put("performanceNo", Objects.toString(StringUtil.normalizeBlank(row.getPerformanceNo()), ""));
@@ -883,9 +907,7 @@ public class PerformanceService {
String modUser, String modUser,
LocalDateTime modDt LocalDateTime modDt
) { ) {
Map<String, String> detail = performanceDetail == null Map<String, String> detail = preparePerformanceDetail(performanceId, performanceDetail, modDt);
? Collections.emptyMap()
: performanceDetail;
List<TPerformanceDetailEntity> detailEntities = detail.entrySet().stream() List<TPerformanceDetailEntity> detailEntities = detail.entrySet().stream()
.map(entry -> TPerformanceDetailEntity.update( .map(entry -> TPerformanceDetailEntity.update(
@@ -900,6 +922,56 @@ public class PerformanceService {
performanceDetailRepository.saveAll(detailEntities); performanceDetailRepository.saveAll(detailEntities);
} }
private Map<String, String> preparePerformanceDetail(
Integer performanceId,
Map<String, String> performanceDetail,
LocalDateTime modDt
) {
Map<String, String> detail = performanceDetail == null
? new LinkedHashMap<>() : new LinkedHashMap<>(performanceDetail);
// 변경 일시는 클라이언트 값으로 수정할 수 없다.
detail.remove("UpdateNoticeDt");
if (detail.containsKey("NCAS")) {
String ncas = Objects.toString(detail.get("NCAS"), "");
if (!ncas.matches("[0-9]*") || ncas.length() > 2048) {
throw BusinessException.badRequest("INVALID_NCAS", "관리번호는 2048자 이내의 숫자만 입력할 수 있습니다.");
}
detail.put("NCAS", ncas);
}
if (!detail.containsKey("UpdateNoticeTarget")
&& !detail.containsKey("UpdateNoticeMemo")) {
return detail;
}
Map<String, String> existing = getPerformanceDetailMap(performanceId);
String target = Objects.toString(detail.getOrDefault("UpdateNoticeTarget",
existing.get("UpdateNoticeTarget")), "");
String memo = Objects.toString(detail.getOrDefault("UpdateNoticeMemo",
existing.get("UpdateNoticeMemo")), "");
if (!target.isEmpty()) {
boolean valid = codeService.findByCodeGroup("update_notice_target").stream()
.anyMatch(code -> code.getCodeValue().toString().equals(target));
if (!valid) {
throw BusinessException.badRequest("INVALID_UPDATE_NOTICE_TARGET", "변경 사항 코드가 유효하지 않습니다.");
}
if (memo.isBlank()) {
throw BusinessException.badRequest("EMPTY_UPDATE_NOTICE_MEMO", "변경 사항 저장 시 변경 내용은 필수입니다.");
}
} else if (!memo.isBlank()) {
throw BusinessException.badRequest("EMPTY_UPDATE_NOTICE_TARGET", "변경 내용을 저장하려면 변경 사항을 선택해야 합니다.");
}
if (memo.length() > 2048) {
throw BusinessException.badRequest("INVALID_UPDATE_NOTICE_MEMO", "변경 내용은 2048자 이내로 입력해야 합니다.");
}
detail.put("UpdateNoticeTarget", target);
detail.put("UpdateNoticeMemo", memo);
if (!Objects.equals(target, Objects.toString(existing.get("UpdateNoticeTarget"), ""))
|| !Objects.equals(memo, Objects.toString(existing.get("UpdateNoticeMemo"), ""))) {
detail.put("UpdateNoticeDt", target.isEmpty() ? "" : modDt.toString());
}
return detail;
}
private void updatePerformanceStaff( private void updatePerformanceStaff(
Integer performanceId, Integer performanceId,
List<PerformanceStaffDto> performanceStaff, List<PerformanceStaffDto> performanceStaff,

View File

@@ -0,0 +1,133 @@
package com.kri.gwcf.review.back.service;
import com.kri.common.feature.util.StringUtil;
import com.kri.gwcf.review.back.persistence.entity.TPerformanceReviewEntity;
import com.kri.gwcf.review.back.persistence.repository.PerformanceReviewRepository;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class ReviewPdfConvertService {
private static final short PDF_CONVERT_COMPLETE = 1;
private static final short PDF_CONVERT_FAILED = 9;
private final PerformanceReviewRepository performanceReviewRepository;
@Value("${kri.file.pdf-converter-command:soffice}")
private String pdfConverterCommand;
public void convertReviewFileToPdf(
Integer performanceId,
Integer reviewType,
String userId,
String uploadFileName,
Path source,
Path dir
) {
String pdfFileName = convertToPdfIfPossible(source, dir);
if (StringUtil.isNullOrBlank(pdfFileName)) {
updatePdfConvertFailure(performanceId, reviewType, userId, uploadFileName);
log.warn(
"Review PDF conversion failed. performanceId={}, reviewType={}, userId={}, uploadFileName={}",
performanceId,
reviewType,
userId,
uploadFileName
);
return;
}
performanceReviewRepository
.findByIdPerformanceIdAndIdReviewTypeAndIdRegUser(performanceId, reviewType, userId)
.filter(entity -> uploadFileName.equals(entity.getUploadFileName()))
.ifPresentOrElse(
entity -> updatePdfConvertResult(entity, pdfFileName),
() -> log.info(
"Skipped stale review PDF conversion result. performanceId={}, reviewType={}, userId={}, uploadFileName={}, pdfFileName={}",
performanceId,
reviewType,
userId,
uploadFileName,
pdfFileName
)
);
}
private void updatePdfConvertResult(TPerformanceReviewEntity entity, String pdfFileName) {
entity.setPdfConvert(PDF_CONVERT_COMPLETE);
entity.setPdfFileName(pdfFileName);
entity.setPdfConvertDt(LocalDateTime.now());
performanceReviewRepository.save(entity);
}
private void updatePdfConvertFailure(
Integer performanceId,
Integer reviewType,
String userId,
String uploadFileName
) {
performanceReviewRepository
.findByIdPerformanceIdAndIdReviewTypeAndIdRegUser(performanceId, reviewType, userId)
.filter(entity -> uploadFileName.equals(entity.getUploadFileName()))
.ifPresent(entity -> {
entity.setPdfConvert(PDF_CONVERT_FAILED);
entity.setPdfFileName("");
entity.setPdfConvertDt(LocalDateTime.now());
performanceReviewRepository.save(entity);
});
}
private String convertToPdfIfPossible(Path source, Path dir) {
String extension = extractExtension(source.getFileName().toString()).toLowerCase();
Set<String> targets = new HashSet<>(Set.of(".docx", ".hwpx", ".hwp", ".pptx", ".xlsx"));
if (!targets.contains(extension)) {
return "";
}
try {
Process process = new ProcessBuilder(
pdfConverterCommand,
"--headless",
"--convert-to",
"pdf",
"--outdir",
dir.toString(),
source.toString()
).redirectErrorStream(true).start();
boolean finished = process.waitFor(300, TimeUnit.SECONDS);
if (!finished || process.exitValue() != 0) {
process.destroyForcibly();
return "";
}
String baseName = stripExtension(source.getFileName().toString());
Path pdf = dir.resolve(baseName + ".pdf").normalize();
return Files.exists(pdf) ? pdf.getFileName().toString() : "";
} catch (Exception e) {
log.warn("Review PDF conversion error. source={}", source, e);
return "";
}
}
private String stripExtension(String fileName) {
int dot = fileName.lastIndexOf('.');
return dot > 0 ? fileName.substring(0, dot) : fileName;
}
private String extractExtension(String fileName) {
int dot = fileName.lastIndexOf('.');
return dot >= 0 ? fileName.substring(dot) : "";
}
}

View File

@@ -16,26 +16,41 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.Executor;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.PathResource; import org.springframework.core.io.PathResource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@Service @Service
@RequiredArgsConstructor
public class ReviewService extends AbstractFileService { public class ReviewService extends AbstractFileService {
private static final short PDF_CONVERT_PENDING = 0;
private static final short PDF_CONVERT_COMPLETE = 1;
private static final short PDF_CONVERT_NOT_TARGET = 8;
private final PerformanceReviewRepository performanceReviewRepository; private final PerformanceReviewRepository performanceReviewRepository;
private final FileStorageProperties fileStorageProperties; private final FileStorageProperties fileStorageProperties;
private final ReviewPdfConvertService reviewPdfConvertService;
private final Executor pdfConvertTaskExecutor;
@Value("${kri.file.pdf-converter-command:soffice}") public ReviewService(
private String pdfConverterCommand; PerformanceReviewRepository performanceReviewRepository,
FileStorageProperties fileStorageProperties,
ReviewPdfConvertService reviewPdfConvertService,
@Qualifier("pdfConvertTaskExecutor") Executor pdfConvertTaskExecutor
) {
this.performanceReviewRepository = performanceReviewRepository;
this.fileStorageProperties = fileStorageProperties;
this.reviewPdfConvertService = reviewPdfConvertService;
this.pdfConvertTaskExecutor = pdfConvertTaskExecutor;
}
@Override @Override
protected Path getBaseDir() { protected Path getBaseDir() {
@@ -76,7 +91,7 @@ public class ReviewService extends AbstractFileService {
.regUser(userId) .regUser(userId)
.build()) .build())
.uploadFileName("") .uploadFileName("")
.pdfConvert(false) .pdfConvert(PDF_CONVERT_NOT_TARGET)
.pdfFileName("") .pdfFileName("")
.regDt(now) .regDt(now)
.build()); .build());
@@ -109,7 +124,7 @@ public class ReviewService extends AbstractFileService {
.regUser(userId) .regUser(userId)
.build()) .build())
.uploadFileName("") .uploadFileName("")
.pdfConvert(false) .pdfConvert(PDF_CONVERT_NOT_TARGET)
.pdfFileName("") .pdfFileName("")
.regDt(now) .regDt(now)
.build()); .build());
@@ -139,10 +154,10 @@ public class ReviewService extends AbstractFileService {
saveFile(dir, file, uploadFileName); saveFile(dir, file, uploadFileName);
Path uploadPath = dir.resolve(uploadFileName).normalize(); Path uploadPath = dir.resolve(uploadFileName).normalize();
String pdfFileName = isPdf(uploadFileName) boolean pdfFile = isPdf(uploadFileName);
? uploadFileName boolean pdfConvertTarget = isPdfConvertTarget(uploadFileName);
: convertToPdfIfPossible(uploadPath, dir); String pdfFileName = pdfFile ? uploadFileName : "";
boolean pdfConvert = StringUtil.hasText(pdfFileName); Short pdfConvert = resolveInitialPdfConvertStatus(pdfFile, pdfConvertTarget);
TPerformanceReviewEntity entity = performanceReviewRepository TPerformanceReviewEntity entity = performanceReviewRepository
.findByIdPerformanceIdAndIdReviewTypeAndIdRegUser(performanceId, reviewType, userId) .findByIdPerformanceIdAndIdReviewTypeAndIdRegUser(performanceId, reviewType, userId)
@@ -159,6 +174,7 @@ public class ReviewService extends AbstractFileService {
entity.setUploadFileName(uploadFileName); entity.setUploadFileName(uploadFileName);
entity.setPdfConvert(pdfConvert); entity.setPdfConvert(pdfConvert);
entity.setPdfFileName(pdfFileName); entity.setPdfFileName(pdfFileName);
entity.setPdfConvertDt(null);
if (entity.getRegUser() == null) { if (entity.getRegUser() == null) {
entity.setRegUser(userId); entity.setRegUser(userId);
entity.setRegDt(now); entity.setRegDt(now);
@@ -167,7 +183,12 @@ public class ReviewService extends AbstractFileService {
entity.setModDt(now); entity.setModDt(now);
} }
return PerformanceReviewDto.from(performanceReviewRepository.save(entity)); TPerformanceReviewEntity saved = performanceReviewRepository.save(entity);
if (pdfConvert == PDF_CONVERT_PENDING) {
convertPdfAfterCommit(performanceId, reviewType, userId, uploadFileName, uploadPath, dir);
}
return PerformanceReviewDto.from(saved);
} catch (IOException e) { } catch (IOException e) {
throw BusinessException.internalError("REVIEW_FILE_SAVE_FAILED", "평가/모니터링 파일 저장 중 오류가 발생했습니다."); throw BusinessException.internalError("REVIEW_FILE_SAVE_FAILED", "평가/모니터링 파일 저장 중 오류가 발생했습니다.");
} }
@@ -177,6 +198,36 @@ public class ReviewService extends AbstractFileService {
return PerformanceReviewDto.from(getReviewEntity(performanceId, reviewType, userId)); return PerformanceReviewDto.from(getReviewEntity(performanceId, reviewType, userId));
} }
private void convertPdfAfterCommit(
Integer performanceId,
Integer reviewType,
String userId,
String uploadFileName,
Path uploadPath,
Path dir
) {
Runnable task = () -> reviewPdfConvertService.convertReviewFileToPdf(
performanceId,
reviewType,
userId,
uploadFileName,
uploadPath,
dir
);
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
pdfConvertTaskExecutor.execute(task);
}
});
return;
}
pdfConvertTaskExecutor.execute(task);
}
public PathResource getOriginalFileResource(Integer performanceId, Integer reviewType, String userId) { public PathResource getOriginalFileResource(Integer performanceId, Integer reviewType, String userId) {
TPerformanceReviewEntity entity = getReviewEntity(performanceId, reviewType, userId); TPerformanceReviewEntity entity = getReviewEntity(performanceId, reviewType, userId);
return toResource(reviewDir(performanceId, reviewType).resolve(entity.getUploadFileName())); return toResource(reviewDir(performanceId, reviewType).resolve(entity.getUploadFileName()));
@@ -303,38 +354,6 @@ public class ReviewService extends AbstractFileService {
.normalize(); .normalize();
} }
private String convertToPdfIfPossible(Path source, Path dir) {
String extension = extractExtension(source.getFileName().toString()).toLowerCase();
Set<String> targets = new HashSet<>(Set.of(".docx", ".hwpx", ".hwp", ".pptx", ".xlsx"));
if (!targets.contains(extension)) {
return "";
}
try {
Process process = new ProcessBuilder(
pdfConverterCommand,
"--headless",
"--convert-to",
"pdf",
"--outdir",
dir.toString(),
source.toString()
).redirectErrorStream(true).start();
boolean finished = process.waitFor(60, TimeUnit.SECONDS);
if (!finished || process.exitValue() != 0) {
process.destroyForcibly();
return "";
}
String baseName = stripExtension(source.getFileName().toString());
Path pdf = dir.resolve(baseName + ".pdf").normalize();
return Files.exists(pdf) ? pdf.getFileName().toString() : "";
} catch (Exception e) {
return "";
}
}
private String stripExtension(String fileName) { private String stripExtension(String fileName) {
int dot = fileName.lastIndexOf('.'); int dot = fileName.lastIndexOf('.');
return dot > 0 ? fileName.substring(0, dot) : fileName; return dot > 0 ? fileName.substring(0, dot) : fileName;
@@ -344,6 +363,18 @@ public class ReviewService extends AbstractFileService {
return ".pdf".equalsIgnoreCase(extractExtension(fileName)); return ".pdf".equalsIgnoreCase(extractExtension(fileName));
} }
private Short resolveInitialPdfConvertStatus(boolean pdfFile, boolean pdfConvertTarget) {
if (pdfFile) {
return PDF_CONVERT_COMPLETE;
}
return pdfConvertTarget ? PDF_CONVERT_PENDING : PDF_CONVERT_NOT_TARGET;
}
private boolean isPdfConvertTarget(String fileName) {
String extension = extractExtension(fileName).toLowerCase();
return Set.of(".docx", ".hwpx", ".hwp", ".pptx", ".xlsx").contains(extension);
}
private String removeTimestampPrefix(String fileName) { private String removeTimestampPrefix(String fileName) {
if (StringUtil.isNullOrBlank(fileName)) { if (StringUtil.isNullOrBlank(fileName)) {
return fileName; return fileName;

View File

@@ -1,12 +1,19 @@
package com.kri.gwcf.review.back.service; package com.kri.gwcf.review.back.service;
import static com.kri.gwcf.review.back.common.consts.GwcfConstant.MONITORING_REVIEW_TYPE;
import static com.kri.gwcf.review.back.common.consts.GwcfConstant.MONITORING_VISIT_ARRIVAL_STATUS;
import static com.kri.gwcf.review.back.common.consts.GwcfConstant.MONITORING_VISIT_DEPARTURE_STATUS;
import static com.kri.gwcf.review.back.common.consts.GwcfConstant.MONITORING_VISIT_RESETTABLE_REVIEW_STATUS;
import com.kri.common.feature.util.StringUtil; import com.kri.common.feature.util.StringUtil;
import com.kri.common.feature.web.BusinessException; import com.kri.common.feature.web.BusinessException;
import com.kri.gwcf.review.back.config.FileStorageProperties; import com.kri.gwcf.review.back.config.FileStorageProperties;
import com.kri.gwcf.review.back.dto.monitoring.MonitoringGpsRequestDto; import com.kri.gwcf.review.back.dto.monitoring.MonitoringGpsRequestDto;
import com.kri.gwcf.review.back.dto.performance.PerformanceMonitoringVisitDto; import com.kri.gwcf.review.back.dto.performance.PerformanceMonitoringVisitDto;
import com.kri.gwcf.review.back.persistence.entity.TPerformanceMonitoringVisitEntity; import com.kri.gwcf.review.back.persistence.entity.TPerformanceMonitoringVisitEntity;
import com.kri.gwcf.review.back.persistence.entity.TPerformanceReviewEntity;
import com.kri.gwcf.review.back.persistence.repository.PerformanceMonitoringVisitRepository; import com.kri.gwcf.review.back.persistence.repository.PerformanceMonitoringVisitRepository;
import com.kri.gwcf.review.back.persistence.repository.PerformanceReviewRepository;
import com.kri.gwcf.review.back.service.file.AbstractFileService; import com.kri.gwcf.review.back.service.file.AbstractFileService;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@@ -29,6 +36,7 @@ import org.springframework.web.multipart.MultipartFile;
public class VisitService extends AbstractFileService { public class VisitService extends AbstractFileService {
private final PerformanceMonitoringVisitRepository performanceMonitoringVisitRepository; private final PerformanceMonitoringVisitRepository performanceMonitoringVisitRepository;
private final PerformanceReviewRepository performanceReviewRepository;
private final FileStorageProperties fileStorageProperties; private final FileStorageProperties fileStorageProperties;
private final ReviewService reviewService; private final ReviewService reviewService;
@@ -65,13 +73,13 @@ public class VisitService extends AbstractFileService {
//validateGps(gps); //validateGps(gps);
TPerformanceMonitoringVisitEntity entity = saveVisit( TPerformanceMonitoringVisitEntity entity = saveVisit(
performanceId, performanceId,
2, MONITORING_VISIT_DEPARTURE_STATUS,
"", "",
gps, gps,
regUser, regUser,
regDt regDt
); );
reviewService.saveMonitoringReviewStatus(performanceId, 2, regUser, regDt); reviewService.saveMonitoringReviewStatus(performanceId, MONITORING_VISIT_DEPARTURE_STATUS, regUser, regDt);
return PerformanceMonitoringVisitDto.from(entity); return PerformanceMonitoringVisitDto.from(entity);
} }
@@ -88,16 +96,36 @@ public class VisitService extends AbstractFileService {
TPerformanceMonitoringVisitEntity entity = saveVisit( TPerformanceMonitoringVisitEntity entity = saveVisit(
performanceId, performanceId,
3, MONITORING_VISIT_ARRIVAL_STATUS,
evidenceImg, evidenceImg,
gps, gps,
regUser, regUser,
regDt regDt
); );
reviewService.saveMonitoringReviewStatus(performanceId, 3, regUser, regDt); reviewService.saveMonitoringReviewStatus(performanceId, MONITORING_VISIT_ARRIVAL_STATUS, regUser, regDt);
return PerformanceMonitoringVisitDto.from(entity); return PerformanceMonitoringVisitDto.from(entity);
} }
@Transactional
public void reset(Integer performanceId, String userId) {
TPerformanceReviewEntity review = performanceReviewRepository
.findByIdPerformanceIdAndIdReviewTypeAndIdRegUserAndReviewStatusIn(
performanceId,
MONITORING_REVIEW_TYPE,
userId,
MONITORING_VISIT_RESETTABLE_REVIEW_STATUS
)
.orElseThrow(() -> BusinessException.badRequest(
"MONITORING_VISIT_RESET_NOT_ALLOWED",
"출발 또는 도착 상태의 모니터링 방문만 초기화할 수 있습니다."
)
.with("performanceId", performanceId)
.with("userId", userId));
performanceMonitoringVisitRepository.deleteByPerformanceIdAndRegUser(performanceId, userId);
performanceReviewRepository.delete(review);
}
public List<PerformanceMonitoringVisitDto> findEvidence(Integer performanceId, String userId) { public List<PerformanceMonitoringVisitDto> findEvidence(Integer performanceId, String userId) {
return performanceMonitoringVisitRepository.findByPerformanceIdAndRegUser(performanceId, userId) return performanceMonitoringVisitRepository.findByPerformanceIdAndRegUser(performanceId, userId)
.stream() .stream()

View File

@@ -175,6 +175,26 @@ public class SystemEventLogService {
); );
} }
public void writeVisitResetLog(
String regId,
LocalDateTime regDt,
String clientIp,
Integer performanceId,
String userId
) {
saveLog(
SystemEventType.VISIT_RESET,
"Visit Reset",
regId,
regDt,
clientIp,
Map.of(
"performanceId", performanceId,
"userId", userId
)
);
}
public void writeStartWrittenReviewLog( public void writeStartWrittenReviewLog(
String regId, String regId,
LocalDateTime regDt, LocalDateTime regDt,

View File

@@ -7,7 +7,7 @@ spring:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
kon: kon:
survey-type: LIST survey-type: BANNER
kri: kri:
file: file:

View File

@@ -2,7 +2,7 @@ server:
port: 6105 port: 6105
forward-headers-strategy: framework forward-headers-strategy: framework
tomcat: tomcat:
max-http-form-post-size: 100MB max-http-form-post-size: 500MB
max-swallow-size: -1 max-swallow-size: -1
spring: spring:
@@ -22,8 +22,8 @@ spring:
servlet: servlet:
multipart: multipart:
max-file-size: 100MB max-file-size: 500MB
max-request-size: 100MB max-request-size: 500MB
logging: logging:
file: file:
@@ -55,6 +55,7 @@ kri:
- /api/v1/assign/confirm/*/* - /api/v1/assign/confirm/*/*
- /api/v1/assign/reject/*/* - /api/v1/assign/reject/*/*
- /api/v1/performance/list/compact - /api/v1/performance/list/compact
- /api/v1/performance/list
- /api/v1/review/start/** - /api/v1/review/start/**
- /api/v1/review/end/** - /api/v1/review/end/**
- /api/v1/code/* - /api/v1/code/*