Compare commits

..

5 Commits

51 changed files with 1679 additions and 244 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.

View File

@@ -1,55 +1,19 @@
## Generated Spring Boot Repository Rules # epolicy-dash-back Project Instruction Router
- This backend application was generated by `@kri/create-spring-app` with Java 17 and Spring Boot 3.5.7. ## Required Project References
- Consume KriCommon through `com.kri.common:starter:beta.1.6.4`; do not change that approved version or duplicate shared behavior without explicit approval.
- The selected primary database is `mysql`. Preserve its configured dialect, driver, transaction, schema, and migration conventions.
- Keep controllers thin and preserve the generated service, DTO, persistence, configuration, QueryDSL, JDBC, and optional MyBatis boundaries.
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
- After every `.agent/project.md` change, run `cd "D:\_____Dev\_________AgentHarnessBase"`, then `.\scripts\agent-harness.ps1 compose --project epolicy-dash-back` and `.\scripts\agent-harness.ps1 verify --project epolicy-dash-back` to keep the generated agent documents current and verified.
- Use the repository Gradle Wrapper and run `.\gradlew.bat compileJava` followed by focused tests for relevant changes.
## Project Data Management Premises Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
- Do not implement a frontend administration page at this stage. Do not add create, update, or delete features for individual information records unless a future approved requirement explicitly expands the scope. | Task scope | Required reference |
- Supply and maintain the data required by this project through Excel-based bulk upload instead of individual administration features. |---|---|
- Keep user and file data outside the Excel bulk-import scope. Import the remaining project data from one Excel workbook containing multiple sheets. | Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
- The Excel workbook contract uses nine required sheets named after their tables: `t_wave`, `t_wave_info`, `t_survey`, `t_survey_item`, `t_part`, `t_part_item`, `t_part_item_sub`, `t_part_item_base`, and `t_part_item_data`. Headers normally use database column names; append the complete allowed-value list in parentheses for constrained columns, such as `is_open (1, 0)`, `chart_type (bar)`, and `is_chart_visible (1, 0)`. The workbook must contain all logical parent rows referenced by its child rows. | Work covered by the dashboard domain contract contract | `.agent/references/dashboard-domain-contract.md` |
- Treat every database column whose name ends with `_idx` as an auto-increment identity. Do not include these columns in Excel import or template sheets, and preserve an existing identity by matching the row's logical key during repeat imports.
- For identity-backed Excel tables, use these import logical keys: `(wave_cd, wave_info_order)` for `t_wave_info`, `(wave_cd, survey_cd, survey_item_order)` for `t_survey_item`, `(wave_cd, part_cd, part_item_cd, survey_cd, part_item_sub_cd)` for `t_part_item_base`, and that same result-series key plus `part_item_data_order` for `t_part_item_data`.
- Define the Excel import/export schema once with KriCommon `ExcelColumn` DTOs. Use KriCommon `ExcelMapper` for workbook mapping and keep only project-specific type, value, and cross-sheet relationship rules in a consumer-local validator; do not duplicate a general-purpose Excel parser.
- Use `POST /api/v1/excel/import` for workbook import and `GET /api/v1/excel/template` for downloading an empty XLSX template. The exported template must contain the same nine required sheets in dependency order and the exact headers accepted by the importer.
- Apply a valid workbook atomically using upsert semantics: insert new primary/logical keys, update matching keys, and retain existing database rows that are absent from the workbook. Do not use a bulk import to delete omitted rows unless a future approved requirement explicitly changes this policy.
- A reference-file upload writes both the physical file and its `t_file` metadata. Accept `fileTitle` and `fileOrder` as multipart request fields, derive `file_type` from the lowercase filename extension, and keep the original filename as `file_name`.
- For reference-file uploads, accept `waveCd` as a path variable and store the file under `{kri.file.base-dir}/References/{waveCd}` using the original filename. Treat `(wave_cd, file_name)` as the upload logical key: uploading the same filename again preserves `file_idx`, replaces the physical file, and updates `file_title`, `file_order`, and `file_type`.
- Reject a reference-file upload when its `waveCd` does not exist. Coordinate the database transaction and filesystem replacement so a database rollback restores the previous file or removes a newly created file.
## Dashboard Data Model Contract If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
- Treat `t_wave` as the root of the dashboard hierarchy. Most child data is logically scoped by `wave_cd`. ## Harness Workflow
- Preserve this logical hierarchy: `t_wave` owns wave information, surveys, file metadata, and parts; a survey owns survey items; a part owns part items; and a part item owns optional sub-items, base counts, and result data.
- Do not add physical database foreign keys. The backend must validate all logical parent-child relationships during Excel import and any future data mutation.
- Treat `(wave_cd, part_cd, part_item_cd)` as the logical item key. Add `survey_cd` to identify a survey-specific result set and add `part_item_sub_cd` when a sub-item exists.
- `t_part_item_sub` has no physical primary key in the planned schema. Treat `(wave_cd, part_cd, part_item_cd, part_item_sub_cd)` as its logical identifier and lookup key.
- A normal item has no `t_part_item_sub` rows, and both base and data rows must use `part_item_sub_cd = NULL`. Never use `0` as a substitute for this `NULL` value.
- An item with sub-items has one or more `t_part_item_sub` rows. Every non-null `part_item_sub_cd` in its base and data rows must reference a sub-item belonging to the same `(wave_cd, part_cd, part_item_cd)`.
- Every survey code used by `t_part_item_base` or `t_part_item_data` must belong to the same Wave. Survey items must likewise belong to an existing `(wave_cd, survey_cd)`.
- Treat `t_survey.survey_color` as a required `VARCHAR(8)` value. Include it as the `survey_color` column in the Excel template/import contract and persist it with each survey.
- Use `t_part_item_base` as the preferred source for determining which survey audiences apply to an item. Display the single matching `survey_alias` when only one audience applies; display `공통` when all defined audiences apply.
- Store an optional display string in `t_part_item_base.base_text` (`VARCHAR(128)`). Do not reconstruct it from `base_count`, and do not retain the removed `base_pre_text` or `base_post_text` fields in entities, Excel contracts, or query assembly.
- Use the corresponding `*_order` column for API and screen ordering: `wave_info_order`, `survey_order`, `survey_item_order`, `file_order`, `part_order`, `part_item_order`, and `part_item_data_order`. Use `part_item_sub_cd` as the default sub-item order because the schema has no separate sub-item order column.
- Use the same `t_part_item_data` rows for both chart and statistical-table views. `is_chart_visible` is a required Boolean column with database default `1`; statistical tables use every row, while charts omit categories and matching values whose flag is false. Do not introduce a separate table-data source that could diverge from chart values.
- Avoid N+1 query patterns when assembling a Wave dashboard. Fetch the required Part, Item, Sub, Base, and Data ranges in batches and assemble the response hierarchy in the backend.
## Frontend API Contract - `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/`.
- Provide screen-oriented APIs rather than exposing table-shaped CRUD endpoints. Use `GET /api/v1/waves` for the header Wave list, `GET /api/v1/waves/{waveCd}` for the Wave overview/navigation/download model, and `GET /api/v1/waves/{waveCd}/parts/{partCd}` for all items and result data in one Part. - A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Return every Wave in the header list and include both `isOpen` and a backend-computed `accessible` value. A user with `userRole < 2010` may access open and closed Waves; a user with `userRole >= 2010`, or with no role, may access only Waves whose `is_open` is true. - Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.
- Revalidate Wave access on both Wave-detail and Part-detail requests. Throw a KriCommon `BusinessException` with forbidden status when a restricted user requests a closed Wave; frontend visibility is not an authorization boundary.
- Assemble normal and sub-item results through one `resultGroups` response shape. A normal item has one group with `subItem = null`; an item with sub-items has one group per Sub in `part_item_sub_cd` order.
- Return categories as objects containing `order`, `label`, and `chartVisible`, alongside complete survey value series. The frontend uses all category/value indexes for statistical tables and filters matching indexes only for chart rendering. Reject Excel imports when category labels, display orders, or chart-visibility flags differ between survey series in the same Item/Sub result group.
- Expose each survey's stored color as `color` in both Wave-detail survey objects and Part-detail series objects so the frontend uses one server-managed color mapping.
- Return the stored nullable `t_part_item_base.base_text` value unchanged as Part-detail `series[].baseText`; `baseCount` remains a separate numeric field.
- When importing `part_item_data_value`, round to scale 10 with `RoundingMode.HALF_UP` before validating and storing it as `DECIMAL(14,10)`. Reject only values that still exceed precision 14 after rounding.
- When `part_item_comment` is blank in Excel, store an empty string rather than `NULL` because the database column is required. Preserve the existing `NULL` semantics of other optional Excel fields.
- Manage chart types as code enums. The initial supported type is `BAR`; Excel accepts its label `bar` case-insensitively, the database stores code `BAR`, and frontend responses return code `BAR`. Reject unsupported labels during Excel validation.
- Build file download URLs in the backend from the configured file resource path and the stored file metadata. Do not require the frontend to construct filesystem paths.

View File

@@ -0,0 +1,51 @@
## Project Data Management Premises
- Do not implement a frontend administration page at this stage. Do not add create, update, or delete features for individual information records unless a future approved requirement explicitly expands the scope.
- Supply and maintain the data required by this project through Excel-based bulk upload instead of individual administration features.
- Keep user and file data outside the Excel bulk-import scope. Import the remaining project data from one Excel workbook containing multiple sheets.
- The Excel workbook has eleven required table-named sheets: `t_wave`, `t_wave_info`, `t_survey`, `t_survey_item`, `t_part`, `t_part_item`, `t_part_item_sub`, `t_part_item_base`, `t_part_item_chart`, `t_part_item_chart_highlight`, and `t_part_item_data`. Headers use database names and constrained headers list every allowed value in parentheses. The workbook must contain all referenced logical parents.
- Omit every auto-increment `_idx` column from Excel. Replacement imports regenerate identities.
- Reject duplicate Excel keys: Wave info `(wave_cd,wave_info_order)`; survey item `(wave_cd,survey_cd,survey_item_order)`; base `(wave_cd,part_cd,part_item_cd,survey_cd,part_item_sub_cd)`; chart/highlight omit `survey_cd`; data adds `part_item_data_order` to base.
- Define the Excel import/export schema once with KriCommon `ExcelColumn` DTOs. Use KriCommon `ExcelMapper` for workbook mapping and keep only project-specific type, value, and cross-sheet relationship rules in a consumer-local validator; do not duplicate a general-purpose Excel parser.
- Excel endpoints are `POST /api/v1/excel/import`, `GET /api/v1/excel/template`, `GET /api/v1/excel/waves/{waveCd}/export`, and `DELETE /api/v1/excel/waves/{waveCd}`. Downloads use the same eleven sheets, order, and headers; a missing Wave exports an empty workbook.
- Imports atomically replace every included Wave: validate first, delete all eleven managed tables, then insert. Failures restore prior data. Standalone reset uses the same child-to-root deletion and retains `t_file` metadata and physical files, allowing temporary orphans until that `wave_cd` is reimported.
- A reference-file upload writes both the physical file and its `t_file` metadata. Accept `fileTitle` and `fileOrder` as multipart request fields, derive `file_type` from the lowercase filename extension, and keep the original filename as `file_name`.
- For reference-file uploads, accept `waveCd` as a path variable and store files under `{kri.file.base-dir}/References/{waveCd}` using their original names. Treat `(wave_cd, file_order)` as the upload logical key: repeat uploads preserve `file_idx`, replace metadata and the physical file, and remove the prior filename after commit. Reject a filename already used by another order in the same Wave.
- Reject a reference-file upload when its `waveCd` does not exist. Coordinate the database transaction and filesystem replacement so a database rollback restores the previous file or removes a newly created file.
## Dashboard Data Model Contract
- Treat `t_wave` as the root of the dashboard hierarchy. Most child data is logically scoped by `wave_cd`.
- Preserve this logical hierarchy: `t_wave` owns wave information, surveys, file metadata, and parts; a survey owns survey items; a part owns part items; and a part item owns optional sub-items, base counts, and result data.
- Do not add physical database foreign keys. The backend must validate all logical parent-child relationships during Excel import and any future data mutation.
- Treat `(wave_cd, part_cd, part_item_cd)` as the logical item key. Add `survey_cd` to identify a survey-specific result set and add `part_item_sub_cd` when a sub-item exists.
- `t_part_item_sub` has no physical primary key in the planned schema. Treat `(wave_cd, part_cd, part_item_cd, part_item_sub_cd)` as its logical identifier and lookup key.
- Store the nullable `t_part_item_sub.part_item_sub_comment` value and expose it as `partItemSubComment` in Part-detail sub-item responses.
- A normal item has no `t_part_item_sub` rows, and both base and data rows must use `part_item_sub_cd = NULL`. Never use `0` as a substitute for this `NULL` value.
- An item with sub-items has one or more `t_part_item_sub` rows. Every non-null `part_item_sub_cd` in its base and data rows must reference a sub-item belonging to the same `(wave_cd, part_cd, part_item_cd)`.
- Every survey code used by `t_part_item_base` or `t_part_item_data` must belong to the same Wave. Survey items must likewise belong to an existing `(wave_cd, survey_cd)`.
- Store four `VARCHAR(8)` survey palette colors: required `survey_color` plus nullable highlight, negative, and negative-highlight colors. Include all in Excel/API; fall back to default, default, and negative/highlight/default respectively.
- Use `t_part_item_base` as the preferred source for determining which survey audiences apply to an item. Display the single matching `survey_alias` when only one audience applies; display `공통` when all defined audiences apply.
- Store an optional display string in `t_part_item_base.base_text` (`VARCHAR(128)`). Do not reconstruct it from `base_count`, and do not retain the removed `base_pre_text` or `base_post_text` fields in entities, Excel contracts, or query assembly.
- Use the corresponding `*_order` column for API and screen ordering: `wave_info_order`, `survey_order`, `survey_item_order`, `file_order`, `part_order`, `part_item_order`, and `part_item_data_order`. Use `part_item_sub_cd` as the default sub-item order because the schema has no separate sub-item order column.
- Use the same `t_part_item_data` rows for both chart and statistical-table views. `is_chart_visible` is a required Boolean column with database default `1`; statistical tables use every row, while charts omit categories and matching values whose flag is false. Do not introduce a separate table-data source that could diverge from chart values.
- Chart/highlight key is `(wave_cd,part_cd,part_item_cd,part_item_sub_cd)`; one config applies to all survey series in its group. Chart type/gap default to `BAR`/`NONE`; colors come from survey palettes.
- Resolve chart highlights independently and return mode/value without calculating highlighted categories. Supported modes are `MAX_VALUE`, `LAST_VISIBLE`, and `SPECIFIED`; only `SPECIFIED` accepts a non-null comma-separated integer list. Highlight colors come only from the survey palette.
- Store item and sub-item negative mode/order independently (`DEFAULT`, `NEGATIVE`, `SPECIFIED`); sub settings never inherit parent settings. Only `SPECIFIED` accepts an order list. Return these settings and survey palette colors so the frontend classifies rows and applies final colors.
- Treat null `part_item_sub_cd` values as equal when matching normal-item chart/highlight settings. Validate Excel logical-key uniqueness, null sub codes for normal items, negative/highlight order syntax, and palette colors as `#RRGGBB`.
- Avoid N+1 query patterns when assembling a Wave dashboard. Fetch the required Part, Item, Sub, Base, and Data ranges in batches and assemble the response hierarchy in the backend.
## Frontend API Contract
- Provide screen-oriented APIs rather than exposing table-shaped CRUD endpoints. Use `GET /api/v1/waves` for the header Wave list, `GET /api/v1/waves/{waveCd}` for the Wave overview/navigation/download model, and `GET /api/v1/waves/{waveCd}/parts/{partCd}` for all items and result data in one Part.
- Return every Wave in the header list and include both `isOpen` and a backend-computed `accessible` value. A user with `userRole < 2010` may access open and closed Waves; a user with `userRole >= 2010`, or with no role, may access only Waves whose `is_open` is true.
- Revalidate Wave access on both Wave-detail and Part-detail requests. Throw a KriCommon `BusinessException` with forbidden status when a restricted user requests a closed Wave; frontend visibility is not an authorization boundary.
- Assemble normal and sub-item results through one `resultGroups` response shape. A normal item has one group with `subItem = null`; an item with sub-items has one group per Sub in `part_item_sub_cd` order.
- Return categories as objects containing `order`, `label`, and `chartVisible`, alongside complete survey value series. The frontend uses all category/value indexes for statistical tables and filters matching indexes only for chart rendering. Reject Excel imports when category labels, display orders, or chart-visibility flags differ between survey series in the same Item/Sub result group.
- Expose effective `color`, `highlightColor`, `negativeColor`, and `negativeHighlightColor` in both Wave-detail surveys and Part-detail series. Return item/sub-item `negativeMode` and nullable `negativeOrder`; the frontend classifies and colors chart rows.
- Return the stored nullable `t_part_item_base.base_text` value unchanged as Part-detail `series[].baseText`; `baseCount` remains a separate numeric field.
- Return `series[].chartGapMode`; the frontend applies `NONE`, `ALL`, or `LAST_VISIBLE`, where the last mode uses the greatest visible `part_item_data_order`.
- When importing `part_item_data_value`, round to scale 10 with `RoundingMode.HALF_UP` before validating and storing it as `DECIMAL(14,10)`. Reject only values that still exceed precision 14 after rounding.
- When `part_item_comment` is blank in Excel, store an empty string rather than `NULL` because the database column is required. Preserve the existing `NULL` semantics of other optional Excel fields.
- Manage chart types as code enums in `t_part_item_chart`. The initial supported type is `BAR`; Excel accepts its label `bar` case-insensitively, the database stores code `BAR`, and Part-detail series responses return code `BAR`. Reject unsupported labels during Excel validation.
- Build file download URLs in the backend from the configured file resource path and the stored file metadata. Do not require the frontend to construct filesystem paths.

View File

@@ -0,0 +1,14 @@
## Generated Spring Boot Repository Rules
- This backend application was generated by `@kri/create-spring-app` with Java 17 and Spring Boot 3.5.7.
- Consume KriCommon through `com.kri.common:starter:beta.1.6.4`; do not change that approved version or duplicate shared behavior without explicit approval.
- The selected primary database is `mysql`. Preserve its configured dialect, driver, transaction, schema, and migration conventions.
- Keep controllers thin and preserve the generated service, DTO, persistence, configuration, QueryDSL, JDBC, and optional MyBatis boundaries.
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
- After every `.agent/project.md` change, run `cd "D:\_____Dev\_________AgentHarnessBase"`, then `.\scripts\agent-harness.ps1 compose --project epolicy-dash-back` and `.\scripts\agent-harness.ps1 verify --project epolicy-dash-back` to keep the generated agent documents current and verified.
- Use the repository Gradle Wrapper and run `.\gradlew.bat compileJava` followed by focused tests for relevant changes.
## Required Domain Reference
- Before changing Excel import/export, reference-file handling, dashboard data models, Wave authorization, chart/statistics behavior, or frontend-facing APIs, read `.agent/references/dashboard-domain-contract.md`.
- Treat that reference as binding project instruction for related work. Keep durable detail there and keep this routing file concise.

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.

121
AGENTS.md
View File

@@ -35,6 +35,13 @@ Later and more specific instructions may override earlier general instructions o
- Lead with the result or decision, then provide only the detail needed to verify it. - Lead with the result or decision, then provide only the detail needed to verify it.
- Do not create or retain a full session transcript. - 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 ## Work Authorization
- The default workflow is discussion first and explicit execution approval second. - The default workflow is discussion first and explicit execution approval second.
@@ -152,6 +159,13 @@ Preferred human-facing tools:
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action. - 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. - 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 ## Validation
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands. - Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
@@ -226,92 +240,39 @@ When implementation is complete, report in Korean:
## KriCommon Consumer Contract ## KriCommon Consumer Contract
### Dependency and API Boundary - 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.
- Consume KriCommon as `com.kri.common:starter:<approved-version>` using the consumer repository's established Gradle dependency and version-management conventions. - 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.
- Import service-facing APIs from `com.kri.common.feature.*`. Treat `com.kri.common.runtime.*` as internal and do not bind application code to it unless no public API exists and the exception is explicitly documented.
- 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.
- Prefer the shared feature or an approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, or utility behavior locally.
### Configuration and Overrides
- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `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.
### Major 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.
### 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.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope. - Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.
## Generated Spring Boot Repository Rules ### Required Shared References
- This backend application was generated by `@kri/create-spring-app` with Java 17 and Spring Boot 3.5.7. Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
- Consume KriCommon through `com.kri.common:starter:beta.1.6.4`; do not change that approved version or duplicate shared behavior without explicit approval.
- The selected primary database is `mysql`. Preserve its configured dialect, driver, transaction, schema, and migration conventions.
- Keep controllers thin and preserve the generated service, DTO, persistence, configuration, QueryDSL, JDBC, and optional MyBatis boundaries.
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
- After every `.agent/project.md` change, run `cd "D:\_____Dev\_________AgentHarnessBase"`, then `.\scripts\agent-harness.ps1 compose --project epolicy-dash-back` and `.\scripts\agent-harness.ps1 verify --project epolicy-dash-back` to keep the generated agent documents current and verified.
- Use the repository Gradle Wrapper and run `.\gradlew.bat compileJava` followed by focused tests for relevant changes.
## Project Data Management Premises | 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` |
- Do not implement a frontend administration page at this stage. Do not add create, update, or delete features for individual information records unless a future approved requirement explicitly expands the scope. 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.
- Supply and maintain the data required by this project through Excel-based bulk upload instead of individual administration features.
- Keep user and file data outside the Excel bulk-import scope. Import the remaining project data from one Excel workbook containing multiple sheets.
- The Excel workbook contract uses nine required sheets named after their tables: `t_wave`, `t_wave_info`, `t_survey`, `t_survey_item`, `t_part`, `t_part_item`, `t_part_item_sub`, `t_part_item_base`, and `t_part_item_data`. Headers normally use database column names; append the complete allowed-value list in parentheses for constrained columns, such as `is_open (1, 0)`, `chart_type (bar)`, and `is_chart_visible (1, 0)`. The workbook must contain all logical parent rows referenced by its child rows.
- Treat every database column whose name ends with `_idx` as an auto-increment identity. Do not include these columns in Excel import or template sheets, and preserve an existing identity by matching the row's logical key during repeat imports.
- For identity-backed Excel tables, use these import logical keys: `(wave_cd, wave_info_order)` for `t_wave_info`, `(wave_cd, survey_cd, survey_item_order)` for `t_survey_item`, `(wave_cd, part_cd, part_item_cd, survey_cd, part_item_sub_cd)` for `t_part_item_base`, and that same result-series key plus `part_item_data_order` for `t_part_item_data`.
- Define the Excel import/export schema once with KriCommon `ExcelColumn` DTOs. Use KriCommon `ExcelMapper` for workbook mapping and keep only project-specific type, value, and cross-sheet relationship rules in a consumer-local validator; do not duplicate a general-purpose Excel parser.
- Use `POST /api/v1/excel/import` for workbook import and `GET /api/v1/excel/template` for downloading an empty XLSX template. The exported template must contain the same nine required sheets in dependency order and the exact headers accepted by the importer.
- Apply a valid workbook atomically using upsert semantics: insert new primary/logical keys, update matching keys, and retain existing database rows that are absent from the workbook. Do not use a bulk import to delete omitted rows unless a future approved requirement explicitly changes this policy.
- A reference-file upload writes both the physical file and its `t_file` metadata. Accept `fileTitle` and `fileOrder` as multipart request fields, derive `file_type` from the lowercase filename extension, and keep the original filename as `file_name`.
- For reference-file uploads, accept `waveCd` as a path variable and store the file under `{kri.file.base-dir}/References/{waveCd}` using the original filename. Treat `(wave_cd, file_name)` as the upload logical key: uploading the same filename again preserves `file_idx`, replaces the physical file, and updates `file_title`, `file_order`, and `file_type`.
- Reject a reference-file upload when its `waveCd` does not exist. Coordinate the database transaction and filesystem replacement so a database rollback restores the previous file or removes a newly created file.
## Dashboard Data Model Contract # epolicy-dash-back Project Instruction Router
- Treat `t_wave` as the root of the dashboard hierarchy. Most child data is logically scoped by `wave_cd`. ## Required Project References
- Preserve this logical hierarchy: `t_wave` owns wave information, surveys, file metadata, and parts; a survey owns survey items; a part owns part items; and a part item owns optional sub-items, base counts, and result data.
- Do not add physical database foreign keys. The backend must validate all logical parent-child relationships during Excel import and any future data mutation.
- Treat `(wave_cd, part_cd, part_item_cd)` as the logical item key. Add `survey_cd` to identify a survey-specific result set and add `part_item_sub_cd` when a sub-item exists.
- `t_part_item_sub` has no physical primary key in the planned schema. Treat `(wave_cd, part_cd, part_item_cd, part_item_sub_cd)` as its logical identifier and lookup key.
- A normal item has no `t_part_item_sub` rows, and both base and data rows must use `part_item_sub_cd = NULL`. Never use `0` as a substitute for this `NULL` value.
- An item with sub-items has one or more `t_part_item_sub` rows. Every non-null `part_item_sub_cd` in its base and data rows must reference a sub-item belonging to the same `(wave_cd, part_cd, part_item_cd)`.
- Every survey code used by `t_part_item_base` or `t_part_item_data` must belong to the same Wave. Survey items must likewise belong to an existing `(wave_cd, survey_cd)`.
- Treat `t_survey.survey_color` as a required `VARCHAR(8)` value. Include it as the `survey_color` column in the Excel template/import contract and persist it with each survey.
- Use `t_part_item_base` as the preferred source for determining which survey audiences apply to an item. Display the single matching `survey_alias` when only one audience applies; display `공통` when all defined audiences apply.
- Store an optional display string in `t_part_item_base.base_text` (`VARCHAR(128)`). Do not reconstruct it from `base_count`, and do not retain the removed `base_pre_text` or `base_post_text` fields in entities, Excel contracts, or query assembly.
- Use the corresponding `*_order` column for API and screen ordering: `wave_info_order`, `survey_order`, `survey_item_order`, `file_order`, `part_order`, `part_item_order`, and `part_item_data_order`. Use `part_item_sub_cd` as the default sub-item order because the schema has no separate sub-item order column.
- Use the same `t_part_item_data` rows for both chart and statistical-table views. `is_chart_visible` is a required Boolean column with database default `1`; statistical tables use every row, while charts omit categories and matching values whose flag is false. Do not introduce a separate table-data source that could diverge from chart values.
- Avoid N+1 query patterns when assembling a Wave dashboard. Fetch the required Part, Item, Sub, Base, and Data ranges in batches and assemble the response hierarchy in the backend.
## Frontend API Contract Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
- Provide screen-oriented APIs rather than exposing table-shaped CRUD endpoints. Use `GET /api/v1/waves` for the header Wave list, `GET /api/v1/waves/{waveCd}` for the Wave overview/navigation/download model, and `GET /api/v1/waves/{waveCd}/parts/{partCd}` for all items and result data in one Part. | Task scope | Required reference |
- Return every Wave in the header list and include both `isOpen` and a backend-computed `accessible` value. A user with `userRole < 2010` may access open and closed Waves; a user with `userRole >= 2010`, or with no role, may access only Waves whose `is_open` is true. |---|---|
- Revalidate Wave access on both Wave-detail and Part-detail requests. Throw a KriCommon `BusinessException` with forbidden status when a restricted user requests a closed Wave; frontend visibility is not an authorization boundary. | Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
- Assemble normal and sub-item results through one `resultGroups` response shape. A normal item has one group with `subItem = null`; an item with sub-items has one group per Sub in `part_item_sub_cd` order. | Work covered by the dashboard domain contract contract | `.agent/references/dashboard-domain-contract.md` |
- Return categories as objects containing `order`, `label`, and `chartVisible`, alongside complete survey value series. The frontend uses all category/value indexes for statistical tables and filters matching indexes only for chart rendering. Reject Excel imports when category labels, display orders, or chart-visibility flags differ between survey series in the same Item/Sub result group.
- Expose each survey's stored color as `color` in both Wave-detail survey objects and Part-detail series objects so the frontend uses one server-managed color mapping. If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
- Return the stored nullable `t_part_item_base.base_text` value unchanged as Part-detail `series[].baseText`; `baseCount` remains a separate numeric field.
- When importing `part_item_data_value`, round to scale 10 with `RoundingMode.HALF_UP` before validating and storing it as `DECIMAL(14,10)`. Reject only values that still exceed precision 14 after rounding. ## Harness Workflow
- When `part_item_comment` is blank in Excel, store an empty string rather than `NULL` because the database column is required. Preserve the existing `NULL` semantics of other optional Excel fields.
- Manage chart types as code enums. The initial supported type is `BAR`; Excel accepts its label `bar` case-insensitively, the database stores code `BAR`, and frontend responses return code `BAR`. Reject unsupported labels during Excel validation. - `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Build file download URLs in the backend from the configured file resource path and the stored file metadata. Do not require the frontend to construct filesystem paths. - 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,19 @@
package com.kri.epolicy.dash.back.common.enums;
import java.util.Arrays;
public enum ChartGapMode {
NONE,
ALL,
LAST_VISIBLE;
public static ChartGapMode fromCodeOrDefault(String code) {
if (code == null) {
return NONE;
}
return Arrays.stream(values())
.filter(mode -> mode.name().equalsIgnoreCase(code.trim()))
.findFirst()
.orElse(NONE);
}
}

View File

@@ -0,0 +1,16 @@
package com.kri.epolicy.dash.back.common.enums;
import java.util.Arrays;
public enum ChartHighlightMode {
MAX_VALUE,
LAST_VISIBLE,
SPECIFIED;
public static ChartHighlightMode fromCode(String code) {
return Arrays.stream(values())
.filter(mode -> mode.name().equalsIgnoreCase(code))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("지원하지 않는 차트 강조 모드입니다: " + code));
}
}

View File

@@ -0,0 +1,19 @@
package com.kri.epolicy.dash.back.common.enums;
import java.util.Arrays;
public enum NegativeMode {
DEFAULT,
NEGATIVE,
SPECIFIED;
public static NegativeMode fromCodeOrDefault(String code) {
if (code == null) {
return DEFAULT;
}
return Arrays.stream(values())
.filter(mode -> mode.name().equalsIgnoreCase(code.trim()))
.findFirst()
.orElse(DEFAULT);
}
}

View File

@@ -1,7 +1,10 @@
package com.kri.epolicy.dash.back.controller; package com.kri.epolicy.dash.back.controller;
import com.kri.epolicy.dash.back.dto.response.ExcelImportResponse; import com.kri.epolicy.dash.back.dto.response.ExcelImportResponse;
import com.kri.epolicy.dash.back.dto.response.ExcelResetResponse;
import com.kri.epolicy.dash.back.service.ExcelExportService;
import com.kri.epolicy.dash.back.service.ExcelImportService; import com.kri.epolicy.dash.back.service.ExcelImportService;
import com.kri.epolicy.dash.back.service.ExcelResetService;
import com.kri.epolicy.dash.back.service.ExcelTemplateService; import com.kri.epolicy.dash.back.service.ExcelTemplateService;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -10,6 +13,8 @@ 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.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestPart;
@@ -23,6 +28,8 @@ public class ExcelController {
private final ExcelImportService excelImportService; private final ExcelImportService excelImportService;
private final ExcelTemplateService excelTemplateService; private final ExcelTemplateService excelTemplateService;
private final ExcelExportService excelExportService;
private final ExcelResetService excelResetService;
@PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ExcelImportResponse importExcel(@RequestPart("file") MultipartFile file) { public ExcelImportResponse importExcel(@RequestPart("file") MultipartFile file) {
@@ -39,4 +46,23 @@ public class ExcelController {
.contentType(MediaType.parseMediaType(ExcelTemplateService.EXCEL_CONTENT_TYPE)) .contentType(MediaType.parseMediaType(ExcelTemplateService.EXCEL_CONTENT_TYPE))
.body(excelTemplateService.createTemplate()); .body(excelTemplateService.createTemplate());
} }
@GetMapping(
value = "/waves/{waveCd}/export",
produces = ExcelTemplateService.EXCEL_CONTENT_TYPE
)
public ResponseEntity<byte[]> exportWave(@PathVariable Short waveCd) {
ContentDisposition disposition = ContentDisposition.attachment()
.filename("epolicy-wave-" + waveCd + ".xlsx", StandardCharsets.UTF_8)
.build();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString())
.contentType(MediaType.parseMediaType(ExcelTemplateService.EXCEL_CONTENT_TYPE))
.body(excelExportService.exportWave(waveCd));
}
@DeleteMapping("/waves/{waveCd}")
public ExcelResetResponse resetWave(@PathVariable Short waveCd) {
return excelResetService.resetWave(waveCd);
}
} }

View File

@@ -1,7 +1,9 @@
package com.kri.epolicy.dash.back.dto.excel; package com.kri.epolicy.dash.back.dto.excel;
import com.kri.common.feature.excel.ExcelColumn; import com.kri.common.feature.excel.ExcelColumn;
import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor;
public final class ExcelTemplateRows { public final class ExcelTemplateRows {
@@ -13,12 +15,16 @@ public final class ExcelTemplateRows {
public static final String PART_ITEM_SHEET = "t_part_item"; public static final String PART_ITEM_SHEET = "t_part_item";
public static final String PART_ITEM_SUB_SHEET = "t_part_item_sub"; public static final String PART_ITEM_SUB_SHEET = "t_part_item_sub";
public static final String PART_ITEM_BASE_SHEET = "t_part_item_base"; public static final String PART_ITEM_BASE_SHEET = "t_part_item_base";
public static final String PART_ITEM_CHART_SHEET = "t_part_item_chart";
public static final String PART_ITEM_CHART_HIGHLIGHT_SHEET = "t_part_item_chart_highlight";
public static final String PART_ITEM_DATA_SHEET = "t_part_item_data"; public static final String PART_ITEM_DATA_SHEET = "t_part_item_data";
private ExcelTemplateRows() { private ExcelTemplateRows() {
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class Wave { public static final class Wave {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "year", order = 1) private String year; @ExcelColumn(header = "year", order = 1) private String year;
@@ -28,6 +34,8 @@ public final class ExcelTemplateRows {
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class WaveInfo { public static final class WaveInfo {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "wave_info_order", order = 1) private String waveInfoOrder; @ExcelColumn(header = "wave_info_order", order = 1) private String waveInfoOrder;
@@ -36,6 +44,8 @@ public final class ExcelTemplateRows {
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class Survey { public static final class Survey {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "survey_cd", order = 1) private String surveyCd; @ExcelColumn(header = "survey_cd", order = 1) private String surveyCd;
@@ -43,9 +53,15 @@ public final class ExcelTemplateRows {
@ExcelColumn(header = "survey_title", order = 3) private String surveyTitle; @ExcelColumn(header = "survey_title", order = 3) private String surveyTitle;
@ExcelColumn(header = "survey_alias", order = 4) private String surveyAlias; @ExcelColumn(header = "survey_alias", order = 4) private String surveyAlias;
@ExcelColumn(header = "survey_color", order = 5) private String surveyColor; @ExcelColumn(header = "survey_color", order = 5) private String surveyColor;
@ExcelColumn(header = "survey_highlight_color", order = 6) private String surveyHighlightColor;
@ExcelColumn(header = "survey_negative_color", order = 7) private String surveyNegativeColor;
@ExcelColumn(header = "survey_negative_highlight_color", order = 8)
private String surveyNegativeHighlightColor;
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class SurveyItem { public static final class SurveyItem {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "survey_cd", order = 1) private String surveyCd; @ExcelColumn(header = "survey_cd", order = 1) private String surveyCd;
@@ -55,6 +71,8 @@ public final class ExcelTemplateRows {
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class Part { public static final class Part {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "part_cd", order = 1) private String partCd; @ExcelColumn(header = "part_cd", order = 1) private String partCd;
@@ -63,26 +81,41 @@ public final class ExcelTemplateRows {
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class PartItem { public static final class PartItem {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "part_cd", order = 1) private String partCd; @ExcelColumn(header = "part_cd", order = 1) private String partCd;
@ExcelColumn(header = "part_item_cd", order = 2) private String partItemCd; @ExcelColumn(header = "part_item_cd", order = 2) private String partItemCd;
@ExcelColumn(header = "part_item_order", order = 3) private String partItemOrder; @ExcelColumn(header = "part_item_order", order = 3) private String partItemOrder;
@ExcelColumn(header = "part_item_title", order = 4) private String partItemTitle; @ExcelColumn(header = "part_item_title", order = 4) private String partItemTitle;
@ExcelColumn(header = "chart_type (bar)", order = 5) private String chartType; @ExcelColumn(header = "part_item_comment", order = 5) private String partItemComment;
@ExcelColumn(header = "part_item_comment", order = 6) private String partItemComment; @ExcelColumn(header = "part_item_negative_mode (DEFAULT, NEGATIVE, SPECIFIED)", order = 6)
private String partItemNegativeMode;
@ExcelColumn(header = "part_item_negative_order", order = 7)
private String partItemNegativeOrder;
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class PartItemSub { public static final class PartItemSub {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "part_cd", order = 1) private String partCd; @ExcelColumn(header = "part_cd", order = 1) private String partCd;
@ExcelColumn(header = "part_item_cd", order = 2) private String partItemCd; @ExcelColumn(header = "part_item_cd", order = 2) private String partItemCd;
@ExcelColumn(header = "part_item_sub_cd", order = 3) private String partItemSubCd; @ExcelColumn(header = "part_item_sub_cd", order = 3) private String partItemSubCd;
@ExcelColumn(header = "part_item_sub_title", order = 4) private String partItemSubTitle; @ExcelColumn(header = "part_item_sub_title", order = 4) private String partItemSubTitle;
@ExcelColumn(header = "part_item_sub_comment", order = 5) private String partItemSubComment;
@ExcelColumn(
header = "part_item_sub_negative_mode (DEFAULT, NEGATIVE, SPECIFIED)", order = 6)
private String partItemSubNegativeMode;
@ExcelColumn(header = "part_item_sub_negative_order", order = 7)
private String partItemSubNegativeOrder;
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class PartItemBase { public static final class PartItemBase {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "part_cd", order = 1) private String partCd; @ExcelColumn(header = "part_cd", order = 1) private String partCd;
@@ -94,6 +127,8 @@ public final class ExcelTemplateRows {
} }
@Getter @Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class PartItemData { public static final class PartItemData {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd; @ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "part_cd", order = 1) private String partCd; @ExcelColumn(header = "part_cd", order = 1) private String partCd;
@@ -105,4 +140,32 @@ public final class ExcelTemplateRows {
@ExcelColumn(header = "part_item_data_value", order = 7) private String partItemDataValue; @ExcelColumn(header = "part_item_data_value", order = 7) private String partItemDataValue;
@ExcelColumn(header = "is_chart_visible (1, 0)", order = 8) private String isChartVisible; @ExcelColumn(header = "is_chart_visible (1, 0)", order = 8) private String isChartVisible;
} }
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class PartItemChart {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "part_cd", order = 1) private String partCd;
@ExcelColumn(header = "part_item_cd", order = 2) private String partItemCd;
@ExcelColumn(header = "part_item_sub_cd", order = 3) private String partItemSubCd;
@ExcelColumn(header = "chart_type (bar)", order = 4) private String chartType;
@ExcelColumn(header = "chart_gap_mode (NONE, ALL, LAST_VISIBLE)", order = 5)
private String chartGapMode;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static final class PartItemChartHighlight {
@ExcelColumn(header = "wave_cd", order = 0) private String waveCd;
@ExcelColumn(header = "part_cd", order = 1) private String partCd;
@ExcelColumn(header = "part_item_cd", order = 2) private String partItemCd;
@ExcelColumn(header = "part_item_sub_cd", order = 3) private String partItemSubCd;
@ExcelColumn(
header = "chart_highlight_mode (MAX_VALUE, LAST_VISIBLE, SPECIFIED)", order = 4)
private String chartHighlightMode;
@ExcelColumn(header = "chart_highlight_value", order = 5)
private String chartHighlightValue;
}
} }

View File

@@ -0,0 +1,24 @@
package com.kri.epolicy.dash.back.dto.excel;
import java.util.List;
public record ExcelWorkbookData(
List<ExcelTemplateRows.Wave> waves,
List<ExcelTemplateRows.WaveInfo> waveInfos,
List<ExcelTemplateRows.Survey> surveys,
List<ExcelTemplateRows.SurveyItem> surveyItems,
List<ExcelTemplateRows.Part> parts,
List<ExcelTemplateRows.PartItem> partItems,
List<ExcelTemplateRows.PartItemSub> partItemSubs,
List<ExcelTemplateRows.PartItemBase> partItemBases,
List<ExcelTemplateRows.PartItemChart> partItemCharts,
List<ExcelTemplateRows.PartItemChartHighlight> partItemChartHighlights,
List<ExcelTemplateRows.PartItemData> partItemData
) {
public static ExcelWorkbookData empty() {
return new ExcelWorkbookData(
List.of(), List.of(), List.of(), List.of(), List.of(), List.of(),
List.of(), List.of(), List.of(), List.of(), List.of());
}
}

View File

@@ -1,6 +1,8 @@
package com.kri.epolicy.dash.back.dto.request; package com.kri.epolicy.dash.back.dto.request;
import com.kri.epolicy.dash.back.common.enums.ChartType; import com.kri.epolicy.dash.back.common.enums.ChartType;
import com.kri.epolicy.dash.back.common.enums.ChartGapMode;
import com.kri.epolicy.dash.back.common.enums.NegativeMode;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.List; import java.util.List;
@@ -13,6 +15,8 @@ public record ExcelData(
List<PartItemRow> partItems, List<PartItemRow> partItems,
List<PartItemSubRow> partItemSubs, List<PartItemSubRow> partItemSubs,
List<PartItemBaseRow> partItemBases, List<PartItemBaseRow> partItemBases,
List<PartItemChartRow> partItemCharts,
List<PartItemChartHighlightRow> partItemChartHighlights,
List<PartItemDataRow> partItemData List<PartItemDataRow> partItemData
) { ) {
@@ -39,7 +43,10 @@ public record ExcelData(
Short surveyOrder, Short surveyOrder,
String surveyTitle, String surveyTitle,
String surveyAlias, String surveyAlias,
String surveyColor String surveyColor,
String surveyHighlightColor,
String surveyNegativeColor,
String surveyNegativeHighlightColor
) { ) {
} }
@@ -66,8 +73,9 @@ public record ExcelData(
Short partItemCd, Short partItemCd,
Short partItemOrder, Short partItemOrder,
String partItemTitle, String partItemTitle,
ChartType chartType, String partItemComment,
String partItemComment NegativeMode partItemNegativeMode,
String partItemNegativeOrder
) { ) {
} }
@@ -76,7 +84,10 @@ public record ExcelData(
Short partCd, Short partCd,
Short partItemCd, Short partItemCd,
Short partItemSubCd, Short partItemSubCd,
String partItemSubTitle String partItemSubTitle,
String partItemSubComment,
NegativeMode partItemSubNegativeMode,
String partItemSubNegativeOrder
) { ) {
} }
@@ -103,4 +114,24 @@ public record ExcelData(
Boolean isChartVisible Boolean isChartVisible
) { ) {
} }
public record PartItemChartRow(
Short waveCd,
Short partCd,
Short partItemCd,
Short partItemSubCd,
ChartType chartType,
ChartGapMode chartGapMode
) {
}
public record PartItemChartHighlightRow(
Short waveCd,
Short partCd,
Short partItemCd,
Short partItemSubCd,
String chartHighlightMode,
String chartHighlightValue
) {
}
} }

View File

@@ -9,6 +9,8 @@ public record ExcelImportResponse(
int partItemCount, int partItemCount,
int partItemSubCount, int partItemSubCount,
int partItemBaseCount, int partItemBaseCount,
int partItemChartCount,
int partItemChartHighlightCount,
int partItemDataCount int partItemDataCount
) { ) {
} }

View File

@@ -0,0 +1,17 @@
package com.kri.epolicy.dash.back.dto.response;
public record ExcelResetResponse(
Short waveCd,
int waveCount,
int waveInfoCount,
int surveyCount,
int surveyItemCount,
int partCount,
int partItemCount,
int partItemSubCount,
int partItemBaseCount,
int partItemChartCount,
int partItemChartHighlightCount,
int partItemDataCount
) {
}

View File

@@ -14,8 +14,9 @@ public record PartDetailResponse(
Short partItemCd, Short partItemCd,
Short order, Short order,
String title, String title,
String chartType,
String comment, String comment,
String negativeMode,
String negativeOrder,
Audience audience, Audience audience,
List<ResultGroup> resultGroups List<ResultGroup> resultGroups
) { ) {
@@ -38,13 +39,26 @@ public record PartDetailResponse(
) { ) {
} }
public record SubItem(Short partItemSubCd, String title) { public record SubItem(
Short partItemSubCd,
String title,
String partItemSubComment,
String negativeMode,
String negativeOrder
) {
} }
public record Series( public record Series(
Short surveyCd, Short surveyCd,
String label, String label,
String chartType,
String color, String color,
String highlightColor,
String negativeColor,
String negativeHighlightColor,
String chartGapMode,
String chartHighlightMode,
String chartHighlightValue,
Integer baseCount, Integer baseCount,
String baseText, String baseText,
List<BigDecimal> values List<BigDecimal> values

View File

@@ -18,6 +18,9 @@ public record WaveDetailResponse(
String title, String title,
String alias, String alias,
String color, String color,
String highlightColor,
String negativeColor,
String negativeHighlightColor,
List<SurveyItem> items List<SurveyItem> items
) { ) {
} }

View File

@@ -0,0 +1,54 @@
package com.kri.epolicy.dash.back.persistence.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter
@Setter
@Entity
@Table(name = "t_part_item_chart")
public class TPartItemChartEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "part_item_chart_idx", nullable = false)
private Integer id;
@NotNull
@Column(name = "wave_cd", nullable = false)
private Short waveCd;
@NotNull
@Column(name = "part_cd", nullable = false)
private Short partCd;
@NotNull
@Column(name = "part_item_cd", nullable = false)
private Short partItemCd;
@Column(name = "part_item_sub_cd")
private Short partItemSubCd;
@Size(max = 32)
@NotNull
@ColumnDefault("'BAR'")
@Column(name = "chart_type", nullable = false, length = 32)
private String chartType;
@Size(max = 32)
@NotNull
@ColumnDefault("'NONE'")
@Column(name = "chart_gap_mode", nullable = false, length = 32)
private String chartGapMode;
}

View File

@@ -0,0 +1,49 @@
package com.kri.epolicy.dash.back.persistence.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "t_part_item_chart_highlight")
public class TPartItemChartHighlightEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "chart_highlight_idx", nullable = false)
private Integer id;
@NotNull
@Column(name = "wave_cd", nullable = false)
private Short waveCd;
@NotNull
@Column(name = "part_cd", nullable = false)
private Short partCd;
@NotNull
@Column(name = "part_item_cd", nullable = false)
private Short partItemCd;
@Column(name = "part_item_sub_cd")
private Short partItemSubCd;
@Size(max = 32)
@NotNull
@Column(name = "chart_highlight_mode", nullable = false, length = 32)
private String chartHighlightMode;
@Size(max = 32)
@Column(name = "chart_highlight_value", length = 32)
private String chartHighlightValue;
}

View File

@@ -1,18 +1,16 @@
package com.kri.epolicy.dash.back.persistence.entity; package com.kri.epolicy.dash.back.persistence.entity;
import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemEntityId; import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemEntityId;
import com.kri.epolicy.dash.back.common.enums.ChartType;
import com.kri.epolicy.dash.back.persistence.converter.ChartTypeConverter;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId; import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Convert;
import jakarta.persistence.Lob; import jakarta.persistence.Lob;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Getter
@Setter @Setter
@@ -32,15 +30,19 @@ public class TPartItemEntity {
@Column(name = "part_item_title", nullable = false, length = 128) @Column(name = "part_item_title", nullable = false, length = 128)
private String partItemTitle; private String partItemTitle;
@NotNull
@Convert(converter = ChartTypeConverter.class)
@Column(name = "chart_type", nullable = false, length = 32)
private ChartType chartType;
@NotNull @NotNull
@Lob @Lob
@Column(name = "part_item_comment", nullable = false) @Column(name = "part_item_comment", nullable = false)
private String partItemComment; private String partItemComment;
@Size(max = 32)
@NotNull
@ColumnDefault("'DEFAULT'")
@Column(name = "part_item_negative_mode", nullable = false, length = 32)
private String partItemNegativeMode;
@Size(max = 32)
@Column(name = "part_item_negative_order", length = 32)
private String partItemNegativeOrder;
} }

View File

@@ -4,11 +4,13 @@ import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemSubEntityId;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId; import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.Lob;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Getter
@Setter @Setter
@@ -24,5 +26,18 @@ public class TPartItemSubEntity {
@Column(name = "part_item_sub_title", nullable = false, length = 128) @Column(name = "part_item_sub_title", nullable = false, length = 128)
private String partItemSubTitle; private String partItemSubTitle;
@Lob
@Column(name = "part_item_sub_comment")
private String partItemSubComment;
@Size(max = 32)
@NotNull
@ColumnDefault("'DEFAULT'")
@Column(name = "part_item_sub_negative_mode", nullable = false, length = 32)
private String partItemSubNegativeMode;
@Size(max = 32)
@Column(name = "part_item_sub_negative_order", length = 32)
private String partItemSubNegativeOrder;
} }

View File

@@ -38,5 +38,16 @@ public class TSurveyEntity {
@Column(name = "survey_color", nullable = false, length = 8) @Column(name = "survey_color", nullable = false, length = 8)
private String surveyColor; private String surveyColor;
@Size(max = 8)
@Column(name = "survey_highlight_color", length = 8)
private String surveyHighlightColor;
@Size(max = 8)
@Column(name = "survey_negative_color", length = 8)
private String surveyNegativeColor;
@Size(max = 8)
@Column(name = "survey_negative_highlight_color", length = 8)
private String surveyNegativeHighlightColor;
} }

View File

@@ -9,5 +9,7 @@ public interface FileRepository extends JpaRepository<TFileEntity, Integer> {
List<TFileEntity> findByWaveCdOrderByFileOrderAsc(Short waveCd); List<TFileEntity> findByWaveCdOrderByFileOrderAsc(Short waveCd);
Optional<TFileEntity> findFirstByWaveCdAndFileOrder(Short waveCd, Short fileOrder);
Optional<TFileEntity> findFirstByWaveCdAndFileName(Short waveCd, String fileName); Optional<TFileEntity> findFirstByWaveCdAndFileName(Short waveCd, String fileName);
} }

View File

@@ -4,10 +4,17 @@ import com.kri.epolicy.dash.back.persistence.entity.TPartItemBaseEntity;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface PartItemBaseRepository extends JpaRepository<TPartItemBaseEntity, Integer> { public interface PartItemBaseRepository extends JpaRepository<TPartItemBaseEntity, Integer> {
List<TPartItemBaseEntity> findByWaveCdAndPartCd(Short waveCd, Short partCd); List<TPartItemBaseEntity> findByWaveCdAndPartCd(Short waveCd, Short partCd);
List<TPartItemBaseEntity> findByWaveCdIn(Collection<Short> waveCodes); List<TPartItemBaseEntity> findByWaveCdIn(Collection<Short> waveCodes);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TPartItemBaseEntity e where e.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -0,0 +1,21 @@
package com.kri.epolicy.dash.back.persistence.repository;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemChartHighlightEntity;
import java.util.Collection;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface PartItemChartHighlightRepository
extends JpaRepository<TPartItemChartHighlightEntity, Integer> {
List<TPartItemChartHighlightEntity> findByWaveCdAndPartCd(Short waveCd, Short partCd);
List<TPartItemChartHighlightEntity> findByWaveCdIn(Collection<Short> waveCodes);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TPartItemChartHighlightEntity e where e.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
}

View File

@@ -0,0 +1,20 @@
package com.kri.epolicy.dash.back.persistence.repository;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemChartEntity;
import java.util.Collection;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface PartItemChartRepository extends JpaRepository<TPartItemChartEntity, Integer> {
List<TPartItemChartEntity> findByWaveCdAndPartCd(Short waveCd, Short partCd);
List<TPartItemChartEntity> findByWaveCdIn(Collection<Short> waveCodes);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TPartItemChartEntity e where e.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
}

View File

@@ -4,6 +4,9 @@ import com.kri.epolicy.dash.back.persistence.entity.TPartItemDataEntity;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface PartItemDataRepository extends JpaRepository<TPartItemDataEntity, Integer> { public interface PartItemDataRepository extends JpaRepository<TPartItemDataEntity, Integer> {
@@ -13,4 +16,8 @@ public interface PartItemDataRepository extends JpaRepository<TPartItemDataEntit
); );
List<TPartItemDataEntity> findByWaveCdIn(Collection<Short> waveCodes); List<TPartItemDataEntity> findByWaveCdIn(Collection<Short> waveCodes);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TPartItemDataEntity e where e.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -4,6 +4,9 @@ import com.kri.epolicy.dash.back.persistence.entity.TPartItemEntity;
import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemEntityId; import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemEntityId;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface PartItemRepository public interface PartItemRepository
extends JpaRepository<TPartItemEntity, TPartItemEntityId> { extends JpaRepository<TPartItemEntity, TPartItemEntityId> {
@@ -14,4 +17,8 @@ public interface PartItemRepository
Short waveCd, Short waveCd,
Short partCd Short partCd
); );
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TPartItemEntity e where e.id.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -4,12 +4,21 @@ import com.kri.epolicy.dash.back.persistence.entity.TPartItemSubEntity;
import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemSubEntityId; import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemSubEntityId;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface PartItemSubRepository public interface PartItemSubRepository
extends JpaRepository<TPartItemSubEntity, TPartItemSubEntityId> { extends JpaRepository<TPartItemSubEntity, TPartItemSubEntityId> {
List<TPartItemSubEntity> findByIdWaveCd(Short waveCd);
List<TPartItemSubEntity> findByIdWaveCdAndIdPartCdOrderByIdPartItemCdAscIdPartItemSubCdAsc( List<TPartItemSubEntity> findByIdWaveCdAndIdPartCdOrderByIdPartItemCdAscIdPartItemSubCdAsc(
Short waveCd, Short waveCd,
Short partCd Short partCd
); );
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TPartItemSubEntity e where e.id.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -4,8 +4,15 @@ import com.kri.epolicy.dash.back.persistence.entity.TPartEntity;
import com.kri.epolicy.dash.back.persistence.entity.id.TPartEntityId; import com.kri.epolicy.dash.back.persistence.entity.id.TPartEntityId;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface PartRepository extends JpaRepository<TPartEntity, TPartEntityId> { public interface PartRepository extends JpaRepository<TPartEntity, TPartEntityId> {
List<TPartEntity> findByIdWaveCdOrderByPartOrderAsc(Short waveCd); List<TPartEntity> findByIdWaveCdOrderByPartOrderAsc(Short waveCd);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TPartEntity e where e.id.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -4,6 +4,9 @@ import com.kri.epolicy.dash.back.persistence.entity.TSurveyItemEntity;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface SurveyItemRepository public interface SurveyItemRepository
extends JpaRepository<TSurveyItemEntity, Integer> { extends JpaRepository<TSurveyItemEntity, Integer> {
@@ -11,4 +14,8 @@ public interface SurveyItemRepository
List<TSurveyItemEntity> findByWaveCdOrderBySurveyItemOrderAsc(Short waveCd); List<TSurveyItemEntity> findByWaveCdOrderBySurveyItemOrderAsc(Short waveCd);
List<TSurveyItemEntity> findByWaveCdIn(Collection<Short> waveCodes); List<TSurveyItemEntity> findByWaveCdIn(Collection<Short> waveCodes);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TSurveyItemEntity e where e.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -4,8 +4,15 @@ import com.kri.epolicy.dash.back.persistence.entity.TSurveyEntity;
import com.kri.epolicy.dash.back.persistence.entity.id.TSurveyEntityId; import com.kri.epolicy.dash.back.persistence.entity.id.TSurveyEntityId;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface SurveyRepository extends JpaRepository<TSurveyEntity, TSurveyEntityId> { public interface SurveyRepository extends JpaRepository<TSurveyEntity, TSurveyEntityId> {
List<TSurveyEntity> findByIdWaveCdOrderBySurveyOrderAsc(Short waveCd); List<TSurveyEntity> findByIdWaveCdOrderBySurveyOrderAsc(Short waveCd);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TSurveyEntity e where e.id.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -4,10 +4,17 @@ import com.kri.epolicy.dash.back.persistence.entity.TWaveInfoEntity;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface WaveInfoRepository extends JpaRepository<TWaveInfoEntity, Integer> { public interface WaveInfoRepository extends JpaRepository<TWaveInfoEntity, Integer> {
List<TWaveInfoEntity> findByWaveCdOrderByWaveInfoOrderAsc(Short waveCd); List<TWaveInfoEntity> findByWaveCdOrderByWaveInfoOrderAsc(Short waveCd);
List<TWaveInfoEntity> findByWaveCdIn(Collection<Short> waveCodes); List<TWaveInfoEntity> findByWaveCdIn(Collection<Short> waveCodes);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TWaveInfoEntity e where e.waveCd = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -1,10 +1,24 @@
package com.kri.epolicy.dash.back.persistence.repository; package com.kri.epolicy.dash.back.persistence.repository;
import com.kri.epolicy.dash.back.persistence.entity.TWaveEntity; import com.kri.epolicy.dash.back.persistence.entity.TWaveEntity;
import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface WaveRepository extends JpaRepository<TWaveEntity, Short> { public interface WaveRepository extends JpaRepository<TWaveEntity, Short> {
List<TWaveEntity> findAllByOrderByYearDescWaveDesc(); List<TWaveEntity> findAllByOrderByYearDescWaveDesc();
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select e from TWaveEntity e where e.id = :waveCd")
Optional<TWaveEntity> findForUpdateById(@Param("waveCd") Short waveCd);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TWaveEntity e where e.id = :waveCd")
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
} }

View File

@@ -0,0 +1,187 @@
package com.kri.epolicy.dash.back.service;
import com.kri.epolicy.dash.back.common.enums.ChartType;
import com.kri.epolicy.dash.back.common.enums.ChartGapMode;
import com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows;
import com.kri.epolicy.dash.back.dto.excel.ExcelWorkbookData;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemBaseEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemChartEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemChartHighlightEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemDataEntity;
import com.kri.epolicy.dash.back.persistence.repository.PartItemBaseRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemChartHighlightRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemChartRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemDataRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemSubRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartRepository;
import com.kri.epolicy.dash.back.persistence.repository.SurveyItemRepository;
import com.kri.epolicy.dash.back.persistence.repository.SurveyRepository;
import com.kri.epolicy.dash.back.persistence.repository.WaveInfoRepository;
import com.kri.epolicy.dash.back.persistence.repository.WaveRepository;
import java.util.Comparator;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class ExcelExportService {
private static final Comparator<Short> NULLABLE_SHORT =
Comparator.nullsFirst(Comparator.naturalOrder());
private final ExcelTemplateService excelTemplateService;
private final WaveRepository waveRepository;
private final WaveInfoRepository waveInfoRepository;
private final SurveyRepository surveyRepository;
private final SurveyItemRepository surveyItemRepository;
private final PartRepository partRepository;
private final PartItemRepository partItemRepository;
private final PartItemSubRepository partItemSubRepository;
private final PartItemBaseRepository partItemBaseRepository;
private final PartItemChartRepository partItemChartRepository;
private final PartItemChartHighlightRepository partItemChartHighlightRepository;
private final PartItemDataRepository partItemDataRepository;
public byte[] exportWave(Short waveCd) {
var wave = waveRepository.findById(waveCd);
if (wave.isEmpty()) {
return excelTemplateService.createTemplate();
}
List<Short> waveCodes = List.of(waveCd);
List<TPartItemBaseEntity> bases = partItemBaseRepository.findByWaveCdIn(waveCodes).stream()
.sorted(resultSeriesComparator())
.toList();
List<TPartItemChartEntity> charts = partItemChartRepository.findByWaveCdIn(waveCodes).stream()
.sorted(resultSeriesComparatorForChart())
.toList();
List<TPartItemChartHighlightEntity> highlights = partItemChartHighlightRepository
.findByWaveCdIn(waveCodes).stream()
.sorted(resultSeriesComparatorForHighlight())
.toList();
List<TPartItemDataEntity> itemData = partItemDataRepository.findByWaveCdIn(waveCodes).stream()
.sorted(resultDataComparator())
.toList();
ExcelWorkbookData data = new ExcelWorkbookData(
wave.stream()
.map(entity -> new ExcelTemplateRows.Wave(
value(entity.getId()), value(entity.getYear()), value(entity.getWave()),
entity.getLabel(), booleanValue(entity.getIsOpen())))
.toList(),
waveInfoRepository.findByWaveCdOrderByWaveInfoOrderAsc(waveCd).stream()
.map(info -> new ExcelTemplateRows.WaveInfo(
value(info.getWaveCd()), value(info.getWaveInfoOrder()),
info.getWaveInfoTitle(), info.getWaveInfoContent()))
.toList(),
surveyRepository.findByIdWaveCdOrderBySurveyOrderAsc(waveCd).stream()
.map(survey -> new ExcelTemplateRows.Survey(
value(survey.getId().getWaveCd()), value(survey.getId().getSurveyCd()),
value(survey.getSurveyOrder()), survey.getSurveyTitle(), survey.getSurveyAlias(),
survey.getSurveyColor(), survey.getSurveyHighlightColor(),
survey.getSurveyNegativeColor(), survey.getSurveyNegativeHighlightColor()))
.toList(),
surveyItemRepository.findByWaveCdOrderBySurveyItemOrderAsc(waveCd).stream()
.sorted(Comparator.comparing(
com.kri.epolicy.dash.back.persistence.entity.TSurveyItemEntity::getSurveyCd)
.thenComparing(
com.kri.epolicy.dash.back.persistence.entity.TSurveyItemEntity
::getSurveyItemOrder))
.map(item -> new ExcelTemplateRows.SurveyItem(
value(item.getWaveCd()), value(item.getSurveyCd()),
value(item.getSurveyItemOrder()), item.getSurveyItemTitle(),
item.getSurveyItemContent()))
.toList(),
partRepository.findByIdWaveCdOrderByPartOrderAsc(waveCd).stream()
.map(part -> new ExcelTemplateRows.Part(
value(part.getId().getWaveCd()), value(part.getId().getPartCd()),
value(part.getPartOrder()), part.getPartTitle()))
.toList(),
partItemRepository.findByIdWaveCdOrderByPartItemOrderAsc(waveCd).stream()
.sorted(Comparator.comparing(
(com.kri.epolicy.dash.back.persistence.entity.TPartItemEntity item) ->
item.getId().getPartCd())
.thenComparing(item -> item.getPartItemOrder()))
.map(item -> new ExcelTemplateRows.PartItem(
value(item.getId().getWaveCd()), value(item.getId().getPartCd()),
value(item.getId().getPartItemCd()), value(item.getPartItemOrder()),
item.getPartItemTitle(), item.getPartItemComment(),
item.getPartItemNegativeMode(), item.getPartItemNegativeOrder()))
.toList(),
partItemSubRepository.findByIdWaveCd(waveCd).stream()
.sorted(Comparator.comparing(
(com.kri.epolicy.dash.back.persistence.entity.TPartItemSubEntity sub) ->
sub.getId().getPartCd())
.thenComparing(sub -> sub.getId().getPartItemCd())
.thenComparing(sub -> sub.getId().getPartItemSubCd()))
.map(sub -> new ExcelTemplateRows.PartItemSub(
value(sub.getId().getWaveCd()), value(sub.getId().getPartCd()),
value(sub.getId().getPartItemCd()), value(sub.getId().getPartItemSubCd()),
sub.getPartItemSubTitle(), sub.getPartItemSubComment(),
sub.getPartItemSubNegativeMode(), sub.getPartItemSubNegativeOrder()))
.toList(),
bases.stream().map(base -> new ExcelTemplateRows.PartItemBase(
value(base.getWaveCd()), value(base.getPartCd()), value(base.getPartItemCd()),
value(base.getSurveyCd()), value(base.getPartItemSubCd()),
value(base.getBaseCount()), base.getBaseText())).toList(),
charts.stream().map(chart -> new ExcelTemplateRows.PartItemChart(
value(chart.getWaveCd()), value(chart.getPartCd()), value(chart.getPartItemCd()),
value(chart.getPartItemSubCd()), chartTypeLabel(chart.getChartType()),
ChartGapMode.fromCodeOrDefault(chart.getChartGapMode()).name())).toList(),
highlights.stream().map(highlight -> new ExcelTemplateRows.PartItemChartHighlight(
value(highlight.getWaveCd()), value(highlight.getPartCd()),
value(highlight.getPartItemCd()), value(highlight.getPartItemSubCd()),
highlight.getChartHighlightMode(),
highlight.getChartHighlightValue())).toList(),
itemData.stream().map(item -> new ExcelTemplateRows.PartItemData(
value(item.getWaveCd()), value(item.getPartCd()), value(item.getPartItemCd()),
value(item.getSurveyCd()), value(item.getPartItemSubCd()),
value(item.getPartItemDataOrder()), item.getPartItemDataLabel(),
item.getPartItemDataValue().toPlainString(), booleanValue(item.getIsChartVisible())))
.toList()
);
return excelTemplateService.createWorkbook(data);
}
private Comparator<TPartItemBaseEntity> resultSeriesComparator() {
return Comparator.comparing(TPartItemBaseEntity::getPartCd)
.thenComparing(TPartItemBaseEntity::getPartItemCd)
.thenComparing(TPartItemBaseEntity::getSurveyCd)
.thenComparing(TPartItemBaseEntity::getPartItemSubCd, NULLABLE_SHORT);
}
private Comparator<TPartItemChartEntity> resultSeriesComparatorForChart() {
return Comparator.comparing(TPartItemChartEntity::getPartCd)
.thenComparing(TPartItemChartEntity::getPartItemCd)
.thenComparing(TPartItemChartEntity::getPartItemSubCd, NULLABLE_SHORT);
}
private Comparator<TPartItemChartHighlightEntity> resultSeriesComparatorForHighlight() {
return Comparator.comparing(TPartItemChartHighlightEntity::getPartCd)
.thenComparing(TPartItemChartHighlightEntity::getPartItemCd)
.thenComparing(TPartItemChartHighlightEntity::getPartItemSubCd, NULLABLE_SHORT);
}
private Comparator<TPartItemDataEntity> resultDataComparator() {
return Comparator.comparing(TPartItemDataEntity::getPartCd)
.thenComparing(TPartItemDataEntity::getPartItemCd)
.thenComparing(TPartItemDataEntity::getSurveyCd)
.thenComparing(TPartItemDataEntity::getPartItemSubCd, NULLABLE_SHORT)
.thenComparing(TPartItemDataEntity::getPartItemDataOrder);
}
private String chartTypeLabel(String code) {
return code == null ? ChartType.BAR.getLabel() : ChartType.fromCode(code).getLabel();
}
private String booleanValue(Boolean value) {
return Boolean.TRUE.equals(value) ? "1" : "0";
}
private String value(Object value) {
return value == null ? null : value.toString();
}
}

View File

@@ -4,6 +4,8 @@ import com.kri.epolicy.dash.back.dto.request.ExcelData;
import com.kri.epolicy.dash.back.dto.response.ExcelImportResponse; import com.kri.epolicy.dash.back.dto.response.ExcelImportResponse;
import com.kri.epolicy.dash.back.persistence.entity.TPartEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemBaseEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartItemBaseEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemChartEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemChartHighlightEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemDataEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartItemDataEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartItemEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemSubEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartItemSubEntity;
@@ -16,6 +18,8 @@ import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemEntityId;
import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemSubEntityId; import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemSubEntityId;
import com.kri.epolicy.dash.back.persistence.entity.id.TSurveyEntityId; import com.kri.epolicy.dash.back.persistence.entity.id.TSurveyEntityId;
import com.kri.epolicy.dash.back.persistence.repository.PartItemBaseRepository; import com.kri.epolicy.dash.back.persistence.repository.PartItemBaseRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemChartHighlightRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemChartRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemDataRepository; import com.kri.epolicy.dash.back.persistence.repository.PartItemDataRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemRepository; import com.kri.epolicy.dash.back.persistence.repository.PartItemRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemSubRepository; import com.kri.epolicy.dash.back.persistence.repository.PartItemSubRepository;
@@ -24,7 +28,6 @@ import com.kri.epolicy.dash.back.persistence.repository.SurveyItemRepository;
import com.kri.epolicy.dash.back.persistence.repository.SurveyRepository; import com.kri.epolicy.dash.back.persistence.repository.SurveyRepository;
import com.kri.epolicy.dash.back.persistence.repository.WaveInfoRepository; import com.kri.epolicy.dash.back.persistence.repository.WaveInfoRepository;
import com.kri.epolicy.dash.back.persistence.repository.WaveRepository; import com.kri.epolicy.dash.back.persistence.repository.WaveRepository;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -37,6 +40,7 @@ import org.springframework.web.multipart.MultipartFile;
public class ExcelImportService { public class ExcelImportService {
private final ExcelImportValidator excelImportValidator; private final ExcelImportValidator excelImportValidator;
private final ExcelResetService excelResetService;
private final WaveRepository waveRepository; private final WaveRepository waveRepository;
private final WaveInfoRepository waveInfoRepository; private final WaveInfoRepository waveInfoRepository;
private final SurveyRepository surveyRepository; private final SurveyRepository surveyRepository;
@@ -45,6 +49,8 @@ public class ExcelImportService {
private final PartItemRepository partItemRepository; private final PartItemRepository partItemRepository;
private final PartItemSubRepository partItemSubRepository; private final PartItemSubRepository partItemSubRepository;
private final PartItemBaseRepository partItemBaseRepository; private final PartItemBaseRepository partItemBaseRepository;
private final PartItemChartRepository partItemChartRepository;
private final PartItemChartHighlightRepository partItemChartHighlightRepository;
private final PartItemDataRepository partItemDataRepository; private final PartItemDataRepository partItemDataRepository;
@Transactional @Transactional
@@ -53,32 +59,7 @@ public class ExcelImportService {
Set<Short> waveCodes = data.waves().stream() Set<Short> waveCodes = data.waves().stream()
.map(ExcelData.WaveRow::waveCd) .map(ExcelData.WaveRow::waveCd)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
Map<WaveInfoKey, Integer> waveInfoIds = waveInfoRepository.findByWaveCdIn(waveCodes) excelResetService.resetWaves(waveCodes);
.stream().collect(Collectors.toMap(
entity -> new WaveInfoKey(entity.getWaveCd(), entity.getWaveInfoOrder()),
TWaveInfoEntity::getId,
firstValue()));
Map<SurveyItemKey, Integer> surveyItemIds = surveyItemRepository
.findByWaveCdIn(waveCodes).stream().collect(Collectors.toMap(
entity -> new SurveyItemKey(
entity.getWaveCd(), entity.getSurveyCd(), entity.getSurveyItemOrder()),
TSurveyItemEntity::getId,
firstValue()));
Map<ResultSeriesKey, Integer> partItemBaseIds = partItemBaseRepository
.findByWaveCdIn(waveCodes).stream().collect(Collectors.toMap(
entity -> new ResultSeriesKey(
entity.getWaveCd(), entity.getPartCd(), entity.getPartItemCd(),
entity.getSurveyCd(), entity.getPartItemSubCd()),
TPartItemBaseEntity::getId,
firstValue()));
Map<ResultCategoryKey, Integer> partItemDataIds = partItemDataRepository
.findByWaveCdIn(waveCodes).stream().collect(Collectors.toMap(
entity -> new ResultCategoryKey(
entity.getWaveCd(), entity.getPartCd(), entity.getPartItemCd(),
entity.getSurveyCd(), entity.getPartItemSubCd(),
entity.getPartItemDataOrder()),
TPartItemDataEntity::getId,
firstValue()));
waveRepository.saveAll(data.waves().stream().map(row -> { waveRepository.saveAll(data.waves().stream().map(row -> {
TWaveEntity entity = new TWaveEntity(); TWaveEntity entity = new TWaveEntity();
@@ -92,7 +73,6 @@ public class ExcelImportService {
waveInfoRepository.saveAll(data.waveInfos().stream().map(row -> { waveInfoRepository.saveAll(data.waveInfos().stream().map(row -> {
TWaveInfoEntity entity = new TWaveInfoEntity(); TWaveInfoEntity entity = new TWaveInfoEntity();
entity.setId(waveInfoIds.get(new WaveInfoKey(row.waveCd(), row.waveInfoOrder())));
entity.setWaveCd(row.waveCd()); entity.setWaveCd(row.waveCd());
entity.setWaveInfoOrder(row.waveInfoOrder()); entity.setWaveInfoOrder(row.waveInfoOrder());
entity.setWaveInfoTitle(row.waveInfoTitle()); entity.setWaveInfoTitle(row.waveInfoTitle());
@@ -107,13 +87,14 @@ public class ExcelImportService {
entity.setSurveyTitle(row.surveyTitle()); entity.setSurveyTitle(row.surveyTitle());
entity.setSurveyAlias(row.surveyAlias()); entity.setSurveyAlias(row.surveyAlias());
entity.setSurveyColor(row.surveyColor()); entity.setSurveyColor(row.surveyColor());
entity.setSurveyHighlightColor(row.surveyHighlightColor());
entity.setSurveyNegativeColor(row.surveyNegativeColor());
entity.setSurveyNegativeHighlightColor(row.surveyNegativeHighlightColor());
return entity; return entity;
}).toList()); }).toList());
surveyItemRepository.saveAll(data.surveyItems().stream().map(row -> { surveyItemRepository.saveAll(data.surveyItems().stream().map(row -> {
TSurveyItemEntity entity = new TSurveyItemEntity(); TSurveyItemEntity entity = new TSurveyItemEntity();
entity.setId(surveyItemIds.get(
new SurveyItemKey(row.waveCd(), row.surveyCd(), row.surveyItemOrder())));
entity.setWaveCd(row.waveCd()); entity.setWaveCd(row.waveCd());
entity.setSurveyCd(row.surveyCd()); entity.setSurveyCd(row.surveyCd());
entity.setSurveyItemOrder(row.surveyItemOrder()); entity.setSurveyItemOrder(row.surveyItemOrder());
@@ -135,8 +116,9 @@ public class ExcelImportService {
entity.setId(partItemId(row.waveCd(), row.partCd(), row.partItemCd())); entity.setId(partItemId(row.waveCd(), row.partCd(), row.partItemCd()));
entity.setPartItemOrder(row.partItemOrder()); entity.setPartItemOrder(row.partItemOrder());
entity.setPartItemTitle(row.partItemTitle()); entity.setPartItemTitle(row.partItemTitle());
entity.setChartType(row.chartType());
entity.setPartItemComment(row.partItemComment()); entity.setPartItemComment(row.partItemComment());
entity.setPartItemNegativeMode(row.partItemNegativeMode().name());
entity.setPartItemNegativeOrder(row.partItemNegativeOrder());
return entity; return entity;
}).toList()); }).toList());
@@ -145,13 +127,14 @@ public class ExcelImportService {
entity.setId(partItemSubId( entity.setId(partItemSubId(
row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd())); row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd()));
entity.setPartItemSubTitle(row.partItemSubTitle()); entity.setPartItemSubTitle(row.partItemSubTitle());
entity.setPartItemSubComment(row.partItemSubComment());
entity.setPartItemSubNegativeMode(row.partItemSubNegativeMode().name());
entity.setPartItemSubNegativeOrder(row.partItemSubNegativeOrder());
return entity; return entity;
}).toList()); }).toList());
partItemBaseRepository.saveAll(data.partItemBases().stream().map(row -> { partItemBaseRepository.saveAll(data.partItemBases().stream().map(row -> {
TPartItemBaseEntity entity = new TPartItemBaseEntity(); TPartItemBaseEntity entity = new TPartItemBaseEntity();
entity.setId(partItemBaseIds.get(new ResultSeriesKey(
row.waveCd(), row.partCd(), row.partItemCd(), row.surveyCd(), row.partItemSubCd())));
entity.setWaveCd(row.waveCd()); entity.setWaveCd(row.waveCd());
entity.setPartCd(row.partCd()); entity.setPartCd(row.partCd());
entity.setPartItemCd(row.partItemCd()); entity.setPartItemCd(row.partItemCd());
@@ -162,11 +145,30 @@ public class ExcelImportService {
return entity; return entity;
}).toList()); }).toList());
partItemChartRepository.saveAll(data.partItemCharts().stream().map(row -> {
TPartItemChartEntity entity = new TPartItemChartEntity();
entity.setWaveCd(row.waveCd());
entity.setPartCd(row.partCd());
entity.setPartItemCd(row.partItemCd());
entity.setPartItemSubCd(row.partItemSubCd());
entity.setChartType(row.chartType().getCode());
entity.setChartGapMode(row.chartGapMode().name());
return entity;
}).toList());
partItemChartHighlightRepository.saveAll(data.partItemChartHighlights().stream().map(row -> {
TPartItemChartHighlightEntity entity = new TPartItemChartHighlightEntity();
entity.setWaveCd(row.waveCd());
entity.setPartCd(row.partCd());
entity.setPartItemCd(row.partItemCd());
entity.setPartItemSubCd(row.partItemSubCd());
entity.setChartHighlightMode(row.chartHighlightMode());
entity.setChartHighlightValue(row.chartHighlightValue());
return entity;
}).toList());
partItemDataRepository.saveAll(data.partItemData().stream().map(row -> { partItemDataRepository.saveAll(data.partItemData().stream().map(row -> {
TPartItemDataEntity entity = new TPartItemDataEntity(); TPartItemDataEntity entity = new TPartItemDataEntity();
entity.setId(partItemDataIds.get(new ResultCategoryKey(
row.waveCd(), row.partCd(), row.partItemCd(), row.surveyCd(), row.partItemSubCd(),
row.partItemDataOrder())));
entity.setWaveCd(row.waveCd()); entity.setWaveCd(row.waveCd());
entity.setPartCd(row.partCd()); entity.setPartCd(row.partCd());
entity.setPartItemCd(row.partItemCd()); entity.setPartItemCd(row.partItemCd());
@@ -188,6 +190,8 @@ public class ExcelImportService {
data.partItems().size(), data.partItems().size(),
data.partItemSubs().size(), data.partItemSubs().size(),
data.partItemBases().size(), data.partItemBases().size(),
data.partItemCharts().size(),
data.partItemChartHighlights().size(),
data.partItemData().size() data.partItemData().size()
); );
} }
@@ -228,32 +232,4 @@ public class ExcelImportService {
return id; return id;
} }
private <T> java.util.function.BinaryOperator<T> firstValue() {
return (first, ignored) -> first;
}
private record WaveInfoKey(Short waveCd, Short order) {
}
private record SurveyItemKey(Short waveCd, Short surveyCd, Short order) {
}
private record ResultSeriesKey(
Short waveCd,
Short partCd,
Short partItemCd,
Short surveyCd,
Short partItemSubCd
) {
}
private record ResultCategoryKey(
Short waveCd,
Short partCd,
Short partItemCd,
Short surveyCd,
Short partItemSubCd,
Short order
) {
}
} }

View File

@@ -4,9 +4,14 @@ import com.kri.common.feature.excel.ExcelColumn;
import com.kri.common.feature.excel.ExcelMapper; import com.kri.common.feature.excel.ExcelMapper;
import com.kri.common.feature.web.BusinessException; import com.kri.common.feature.web.BusinessException;
import com.kri.epolicy.dash.back.common.enums.ChartType; import com.kri.epolicy.dash.back.common.enums.ChartType;
import com.kri.epolicy.dash.back.common.enums.ChartHighlightMode;
import com.kri.epolicy.dash.back.common.enums.ChartGapMode;
import com.kri.epolicy.dash.back.common.enums.NegativeMode;
import com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows; import com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows;
import com.kri.epolicy.dash.back.dto.request.ExcelData; import com.kri.epolicy.dash.back.dto.request.ExcelData;
import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemBaseRow; import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemBaseRow;
import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemChartHighlightRow;
import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemChartRow;
import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemDataRow; import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemDataRow;
import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemRow; import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemRow;
import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemSubRow; import com.kri.epolicy.dash.back.dto.request.ExcelData.PartItemSubRow;
@@ -34,6 +39,7 @@ import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.regex.Pattern;
import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
@@ -46,6 +52,8 @@ import org.springframework.web.multipart.MultipartFile;
public class ExcelImportValidator { public class ExcelImportValidator {
private static final int HEADER_ROW_NUMBER = 1; private static final int HEADER_ROW_NUMBER = 1;
private static final Pattern COLOR_PATTERN = Pattern.compile("#[0-9A-Fa-f]{6}");
private static final Pattern SPECIFIED_VALUE_PATTERN = Pattern.compile("\\d+(,\\d+)*");
public ExcelData validateAndConvert(MultipartFile file) { public ExcelData validateAndConvert(MultipartFile file) {
validateFile(file); validateFile(file);
@@ -60,7 +68,9 @@ public class ExcelImportValidator {
row.getWaveInfoContent()), this::toWaveInfoRow), row.getWaveInfoContent()), this::toWaveInfoRow),
readRows(workbook, ExcelTemplateRows.SURVEY_SHEET, ExcelTemplateRows.Survey.class, readRows(workbook, ExcelTemplateRows.SURVEY_SHEET, ExcelTemplateRows.Survey.class,
row -> allBlank(row.getWaveCd(), row.getSurveyCd(), row.getSurveyOrder(), row -> allBlank(row.getWaveCd(), row.getSurveyCd(), row.getSurveyOrder(),
row.getSurveyTitle(), row.getSurveyAlias(), row.getSurveyColor()), row.getSurveyTitle(), row.getSurveyAlias(), row.getSurveyColor(),
row.getSurveyHighlightColor(), row.getSurveyNegativeColor(),
row.getSurveyNegativeHighlightColor()),
this::toSurveyRow), this::toSurveyRow),
readRows(workbook, ExcelTemplateRows.SURVEY_ITEM_SHEET, readRows(workbook, ExcelTemplateRows.SURVEY_ITEM_SHEET,
ExcelTemplateRows.SurveyItem.class, ExcelTemplateRows.SurveyItem.class,
@@ -71,17 +81,31 @@ public class ExcelImportValidator {
row.getPartTitle()), this::toPartRow), row.getPartTitle()), this::toPartRow),
readRows(workbook, ExcelTemplateRows.PART_ITEM_SHEET, ExcelTemplateRows.PartItem.class, readRows(workbook, ExcelTemplateRows.PART_ITEM_SHEET, ExcelTemplateRows.PartItem.class,
row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(), row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(),
row.getPartItemOrder(), row.getPartItemTitle(), row.getChartType(), row.getPartItemOrder(), row.getPartItemTitle(), row.getPartItemComment(),
row.getPartItemComment()), this::toPartItemRow), row.getPartItemNegativeMode(), row.getPartItemNegativeOrder()),
this::toPartItemRow),
readRows(workbook, ExcelTemplateRows.PART_ITEM_SUB_SHEET, readRows(workbook, ExcelTemplateRows.PART_ITEM_SUB_SHEET,
ExcelTemplateRows.PartItemSub.class, ExcelTemplateRows.PartItemSub.class,
row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(), row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(),
row.getPartItemSubCd(), row.getPartItemSubTitle()), this::toPartItemSubRow), row.getPartItemSubCd(), row.getPartItemSubTitle(),
row.getPartItemSubComment(), row.getPartItemSubNegativeMode(),
row.getPartItemSubNegativeOrder()), this::toPartItemSubRow),
readRows(workbook, ExcelTemplateRows.PART_ITEM_BASE_SHEET, readRows(workbook, ExcelTemplateRows.PART_ITEM_BASE_SHEET,
ExcelTemplateRows.PartItemBase.class, ExcelTemplateRows.PartItemBase.class,
row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(), row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(),
row.getSurveyCd(), row.getPartItemSubCd(), row.getBaseCount(), row.getSurveyCd(), row.getPartItemSubCd(), row.getBaseCount(),
row.getBaseText()), this::toPartItemBaseRow), row.getBaseText()), this::toPartItemBaseRow),
readRows(workbook, ExcelTemplateRows.PART_ITEM_CHART_SHEET,
ExcelTemplateRows.PartItemChart.class,
row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(),
row.getPartItemSubCd(), row.getChartType(),
row.getChartGapMode()), this::toPartItemChartRow),
readRows(workbook, ExcelTemplateRows.PART_ITEM_CHART_HIGHLIGHT_SHEET,
ExcelTemplateRows.PartItemChartHighlight.class,
row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(),
row.getPartItemSubCd(), row.getChartHighlightMode(),
row.getChartHighlightValue()),
this::toPartItemChartHighlightRow),
readRows(workbook, ExcelTemplateRows.PART_ITEM_DATA_SHEET, readRows(workbook, ExcelTemplateRows.PART_ITEM_DATA_SHEET,
ExcelTemplateRows.PartItemData.class, ExcelTemplateRows.PartItemData.class,
row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(), row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(),
@@ -190,7 +214,11 @@ public class ExcelImportValidator {
requiredShort(row.getSurveyOrder(), "survey_order", context), requiredShort(row.getSurveyOrder(), "survey_order", context),
requiredString(row.getSurveyTitle(), "survey_title", 128, context), requiredString(row.getSurveyTitle(), "survey_title", 128, context),
requiredString(row.getSurveyAlias(), "survey_alias", 32, context), requiredString(row.getSurveyAlias(), "survey_alias", 32, context),
requiredString(row.getSurveyColor(), "survey_color", 8, context) requiredColor(row.getSurveyColor(), "survey_color", context),
optionalColor(row.getSurveyHighlightColor(), "survey_highlight_color", context),
optionalColor(row.getSurveyNegativeColor(), "survey_negative_color", context),
optionalColor(
row.getSurveyNegativeHighlightColor(), "survey_negative_highlight_color", context)
); );
} }
@@ -217,15 +245,20 @@ public class ExcelImportValidator {
} }
private PartItemRow toPartItemRow(ExcelTemplateRows.PartItem row, RowContext context) { private PartItemRow toPartItemRow(ExcelTemplateRows.PartItem row, RowContext context) {
NegativeMode mode = NegativeMode.fromCodeOrDefault(normalized(row.getPartItemNegativeMode()));
String order = optionalString(
row.getPartItemNegativeOrder(), "part_item_negative_order", 32, context);
validateNegativeValue(mode, order, "part_item_negative_order", context);
return new PartItemRow( return new PartItemRow(
requiredShort(row.getWaveCd(), "wave_cd", context), requiredShort(row.getWaveCd(), "wave_cd", context),
requiredShort(row.getPartCd(), "part_cd", context), requiredShort(row.getPartCd(), "part_cd", context),
requiredShort(row.getPartItemCd(), "part_item_cd", context), requiredShort(row.getPartItemCd(), "part_item_cd", context),
requiredShort(row.getPartItemOrder(), "part_item_order", context), requiredShort(row.getPartItemOrder(), "part_item_order", context),
requiredString(row.getPartItemTitle(), "part_item_title", 128, context), requiredString(row.getPartItemTitle(), "part_item_title", 128, context),
requiredChartType(row.getChartType(), "chart_type", context),
Objects.requireNonNullElse( Objects.requireNonNullElse(
optionalString(row.getPartItemComment(), "part_item_comment", null, context), "") optionalString(row.getPartItemComment(), "part_item_comment", null, context), ""),
mode,
order
); );
} }
@@ -233,12 +266,20 @@ public class ExcelImportValidator {
ExcelTemplateRows.PartItemSub row, ExcelTemplateRows.PartItemSub row,
RowContext context RowContext context
) { ) {
NegativeMode mode = NegativeMode.fromCodeOrDefault(
normalized(row.getPartItemSubNegativeMode()));
String order = optionalString(
row.getPartItemSubNegativeOrder(), "part_item_sub_negative_order", 32, context);
validateNegativeValue(mode, order, "part_item_sub_negative_order", context);
return new PartItemSubRow( return new PartItemSubRow(
requiredShort(row.getWaveCd(), "wave_cd", context), requiredShort(row.getWaveCd(), "wave_cd", context),
requiredShort(row.getPartCd(), "part_cd", context), requiredShort(row.getPartCd(), "part_cd", context),
requiredShort(row.getPartItemCd(), "part_item_cd", context), requiredShort(row.getPartItemCd(), "part_item_cd", context),
requiredShort(row.getPartItemSubCd(), "part_item_sub_cd", context), requiredShort(row.getPartItemSubCd(), "part_item_sub_cd", context),
requiredString(row.getPartItemSubTitle(), "part_item_sub_title", 128, context) requiredString(row.getPartItemSubTitle(), "part_item_sub_title", 128, context),
optionalString(row.getPartItemSubComment(), "part_item_sub_comment", null, context),
mode,
order
); );
} }
@@ -274,6 +315,39 @@ public class ExcelImportValidator {
); );
} }
private PartItemChartRow toPartItemChartRow(
ExcelTemplateRows.PartItemChart row,
RowContext context
) {
return new PartItemChartRow(
requiredShort(row.getWaveCd(), "wave_cd", context),
requiredShort(row.getPartCd(), "part_cd", context),
requiredShort(row.getPartItemCd(), "part_item_cd", context),
optionalShort(row.getPartItemSubCd(), "part_item_sub_cd", context),
requiredChartType(row.getChartType(), "chart_type", context),
ChartGapMode.fromCodeOrDefault(normalized(row.getChartGapMode()))
);
}
private PartItemChartHighlightRow toPartItemChartHighlightRow(
ExcelTemplateRows.PartItemChartHighlight row,
RowContext context
) {
ChartHighlightMode mode = requiredChartHighlightMode(
row.getChartHighlightMode(), "chart_highlight_mode", context);
String value = optionalString(
row.getChartHighlightValue(), "chart_highlight_value", 32, context);
validateHighlightValue(mode, value, context);
return new PartItemChartHighlightRow(
requiredShort(row.getWaveCd(), "wave_cd", context),
requiredShort(row.getPartCd(), "part_cd", context),
requiredShort(row.getPartItemCd(), "part_item_cd", context),
optionalShort(row.getPartItemSubCd(), "part_item_sub_cd", context),
mode.name(),
value
);
}
private void validateRelationships(ExcelData data) { private void validateRelationships(ExcelData data) {
Set<Short> waveKeys = uniqueKeys( Set<Short> waveKeys = uniqueKeys(
data.waves(), WaveRow::waveCd, ExcelTemplateRows.WAVE_SHEET); data.waves(), WaveRow::waveCd, ExcelTemplateRows.WAVE_SHEET);
@@ -293,6 +367,10 @@ public class ExcelImportValidator {
Set<SubKey> subKeys = uniqueKeys(data.partItemSubs(), Set<SubKey> subKeys = uniqueKeys(data.partItemSubs(),
row -> new SubKey(row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd()), row -> new SubKey(row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd()),
ExcelTemplateRows.PART_ITEM_SUB_SHEET); ExcelTemplateRows.PART_ITEM_SUB_SHEET);
uniqueKeys(data.partItemCharts(), this::chartConfigKey,
ExcelTemplateRows.PART_ITEM_CHART_SHEET);
uniqueKeys(data.partItemChartHighlights(), this::chartConfigKey,
ExcelTemplateRows.PART_ITEM_CHART_HIGHLIGHT_SHEET);
requireParents(data.waveInfos(), WaveInfoRow::waveCd, waveKeys, requireParents(data.waveInfos(), WaveInfoRow::waveCd, waveKeys,
ExcelTemplateRows.WAVE_INFO_SHEET, "wave_cd"); ExcelTemplateRows.WAVE_INFO_SHEET, "wave_cd");
@@ -323,10 +401,30 @@ public class ExcelImportValidator {
row.partItemSubCd(), itemKeys, surveyKeys, subKeys, itemsWithSubs, row.partItemSubCd(), itemKeys, surveyKeys, subKeys, itemsWithSubs,
ExcelTemplateRows.PART_ITEM_DATA_SHEET); ExcelTemplateRows.PART_ITEM_DATA_SHEET);
} }
for (PartItemChartRow row : data.partItemCharts()) {
validateItemSubRelationship(row.waveCd(), row.partCd(), row.partItemCd(),
row.partItemSubCd(), itemKeys, subKeys, itemsWithSubs,
ExcelTemplateRows.PART_ITEM_CHART_SHEET);
}
for (PartItemChartHighlightRow row : data.partItemChartHighlights()) {
validateItemSubRelationship(row.waveCd(), row.partCd(), row.partItemCd(),
row.partItemSubCd(), itemKeys, subKeys, itemsWithSubs,
ExcelTemplateRows.PART_ITEM_CHART_HIGHLIGHT_SHEET);
}
validateResultBases(data.partItemBases(), data.partItemData()); validateResultBases(data.partItemBases(), data.partItemData());
validateCategoryConsistency(data.partItemData()); validateCategoryConsistency(data.partItemData());
} }
private ResultGroupKey chartConfigKey(PartItemChartRow row) {
return new ResultGroupKey(
row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd());
}
private ResultGroupKey chartConfigKey(PartItemChartHighlightRow row) {
return new ResultGroupKey(
row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd());
}
private void validateResultBases(List<PartItemBaseRow> bases, List<PartItemDataRow> data) { private void validateResultBases(List<PartItemBaseRow> bases, List<PartItemDataRow> data) {
Set<ResultSeriesKey> baseKeys = uniqueKeys(bases, Set<ResultSeriesKey> baseKeys = uniqueKeys(bases,
row -> new ResultSeriesKey( row -> new ResultSeriesKey(
@@ -386,21 +484,36 @@ public class ExcelImportValidator {
Set<ItemKey> itemsWithSubs, Set<ItemKey> itemsWithSubs,
String sheetName String sheetName
) { ) {
ItemKey itemKey = new ItemKey(waveCd, partCd, partItemCd); validateItemSubRelationship(
if (!itemKeys.contains(itemKey)) { waveCd, partCd, partItemCd, partItemSubCd,
throw relationshipError(sheetName, "존재하지 않는 문항을 참조합니다: " + itemKey); itemKeys, subKeys, itemsWithSubs, sheetName);
}
if (!surveyKeys.contains(new SurveyKey(waveCd, surveyCd))) { if (!surveyKeys.contains(new SurveyKey(waveCd, surveyCd))) {
throw relationshipError(sheetName, throw relationshipError(sheetName,
"동일 Wave에 존재하지 않는 조사대상을 참조합니다: " + surveyCd); "동일 Wave에 존재하지 않는 조사대상을 참조합니다: " + surveyCd);
} }
}
private void validateItemSubRelationship(
Short waveCd,
Short partCd,
Short partItemCd,
Short partItemSubCd,
Set<ItemKey> itemKeys,
Set<SubKey> subKeys,
Set<ItemKey> itemsWithSubs,
String sheetName
) {
ItemKey itemKey = new ItemKey(waveCd, partCd, partItemCd);
if (!itemKeys.contains(itemKey)) {
throw relationshipError(sheetName, "존재하지 않는 문항을 참조합니다: " + itemKey);
}
if (itemsWithSubs.contains(itemKey)) { if (itemsWithSubs.contains(itemKey)) {
if (partItemSubCd == null) { if (partItemSubCd == null) {
throw relationshipError(sheetName, throw relationshipError(sheetName,
"Sub가 있는 문항의 part_item_sub_cd는 필수입니다: " + itemKey); "Sub가 있는 문항의 part_item_sub_cd는 필수입니다: " + itemKey);
} }
if (!subKeys.contains(new SubKey(waveCd, partCd, partItemCd, partItemSubCd))) { if (!subKeys.contains(new SubKey(waveCd, partCd, partItemCd, partItemSubCd))) {
throw relationshipError(sheetName, "존재하지 않는 Sub를 참조합니다: " + partItemSubCd); throw relationshipError(sheetName, "존재하지 않는 Sub를 참조합니다: " + partItemCd + "/" + partItemSubCd);
} }
} else if (partItemSubCd != null) { } else if (partItemSubCd != null) {
throw relationshipError(sheetName, throw relationshipError(sheetName,
@@ -551,6 +664,72 @@ public class ExcelImportValidator {
} }
} }
private ChartHighlightMode requiredChartHighlightMode(
String rawValue,
String column,
RowContext context
) {
String code = requiredRaw(rawValue, column, context);
try {
return ChartHighlightMode.fromCode(code);
} catch (IllegalArgumentException exception) {
throw cellError(context, column,
"MAX_VALUE, LAST_VISIBLE 또는 SPECIFIED여야 합니다.");
}
}
private String requiredColor(String rawValue, String column, RowContext context) {
String color = requiredString(rawValue, column, 8, context);
validateColor(color, column, context);
return color;
}
private String optionalColor(String rawValue, String column, RowContext context) {
String color = optionalString(rawValue, column, 8, context);
if (color != null) {
validateColor(color, column, context);
}
return color;
}
private void validateColor(String color, String column, RowContext context) {
if (!COLOR_PATTERN.matcher(color).matches()) {
throw cellError(context, column, "#RRGGBB 형식이어야 합니다.");
}
}
private void validateHighlightValue(
ChartHighlightMode mode,
String value,
RowContext context
) {
if (mode == ChartHighlightMode.SPECIFIED) {
if (value == null || !SPECIFIED_VALUE_PATTERN.matcher(value).matches()) {
throw cellError(context, "chart_highlight_value",
"SPECIFIED 모드는 공백 없는 정수 목록이어야 합니다. 예: 1,3,5");
}
} else if (value != null) {
throw cellError(context, "chart_highlight_value",
mode.name() + " 모드에서는 NULL이어야 합니다.");
}
}
private void validateNegativeValue(
NegativeMode mode,
String value,
String column,
RowContext context
) {
if (mode == NegativeMode.SPECIFIED) {
if (value == null || !SPECIFIED_VALUE_PATTERN.matcher(value).matches()) {
throw cellError(context, column,
"SPECIFIED 모드는 공백 없는 정수 목록이어야 합니다. 예: 1,3,5");
}
} else if (value != null) {
throw cellError(context, column, mode.name() + " 모드에서는 NULL이어야 합니다.");
}
}
private String requiredRaw(String rawValue, String column, RowContext context) { private String requiredRaw(String rawValue, String column, RowContext context) {
String value = normalized(rawValue); String value = normalized(rawValue);
if (value == null) { if (value == null) {

View File

@@ -0,0 +1,70 @@
package com.kri.epolicy.dash.back.service;
import com.kri.epolicy.dash.back.dto.response.ExcelResetResponse;
import com.kri.epolicy.dash.back.persistence.repository.PartItemBaseRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemChartHighlightRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemChartRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemDataRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemSubRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartRepository;
import com.kri.epolicy.dash.back.persistence.repository.SurveyItemRepository;
import com.kri.epolicy.dash.back.persistence.repository.SurveyRepository;
import com.kri.epolicy.dash.back.persistence.repository.WaveInfoRepository;
import com.kri.epolicy.dash.back.persistence.repository.WaveRepository;
import java.util.Collection;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class ExcelResetService {
private final WaveRepository waveRepository;
private final WaveInfoRepository waveInfoRepository;
private final SurveyRepository surveyRepository;
private final SurveyItemRepository surveyItemRepository;
private final PartRepository partRepository;
private final PartItemRepository partItemRepository;
private final PartItemSubRepository partItemSubRepository;
private final PartItemBaseRepository partItemBaseRepository;
private final PartItemChartRepository partItemChartRepository;
private final PartItemChartHighlightRepository partItemChartHighlightRepository;
private final PartItemDataRepository partItemDataRepository;
@Transactional
public ExcelResetResponse resetWave(Short waveCd) {
int partItemDataCount = partItemDataRepository.deleteForResetByWaveCd(waveCd);
int partItemChartHighlightCount =
partItemChartHighlightRepository.deleteForResetByWaveCd(waveCd);
int partItemChartCount = partItemChartRepository.deleteForResetByWaveCd(waveCd);
int partItemBaseCount = partItemBaseRepository.deleteForResetByWaveCd(waveCd);
int partItemSubCount = partItemSubRepository.deleteForResetByWaveCd(waveCd);
int partItemCount = partItemRepository.deleteForResetByWaveCd(waveCd);
int partCount = partRepository.deleteForResetByWaveCd(waveCd);
int surveyItemCount = surveyItemRepository.deleteForResetByWaveCd(waveCd);
int surveyCount = surveyRepository.deleteForResetByWaveCd(waveCd);
int waveInfoCount = waveInfoRepository.deleteForResetByWaveCd(waveCd);
int waveCount = waveRepository.deleteForResetByWaveCd(waveCd);
return new ExcelResetResponse(
waveCd,
waveCount,
waveInfoCount,
surveyCount,
surveyItemCount,
partCount,
partItemCount,
partItemSubCount,
partItemBaseCount,
partItemChartCount,
partItemChartHighlightCount,
partItemDataCount
);
}
@Transactional
public void resetWaves(Collection<Short> waveCodes) {
waveCodes.forEach(this::resetWave);
}
}

View File

@@ -3,7 +3,10 @@ package com.kri.epolicy.dash.back.service;
import com.kri.common.feature.excel.ExcelMapper; import com.kri.common.feature.excel.ExcelMapper;
import com.kri.common.feature.web.BusinessException; import com.kri.common.feature.web.BusinessException;
import com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows; import com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows;
import com.kri.epolicy.dash.back.dto.excel.ExcelWorkbookData;
import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_BASE_SHEET; import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_BASE_SHEET;
import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_CHART_HIGHLIGHT_SHEET;
import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_CHART_SHEET;
import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_DATA_SHEET; import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_DATA_SHEET;
import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_SHEET; import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_SHEET;
import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_SUB_SHEET; import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_ITEM_SUB_SHEET;
@@ -26,17 +29,28 @@ public class ExcelTemplateService {
public static final String TEMPLATE_FILENAME = "epolicy-data-template.xlsx"; public static final String TEMPLATE_FILENAME = "epolicy-data-template.xlsx";
public byte[] createTemplate() { public byte[] createTemplate() {
return createWorkbook(ExcelWorkbookData.empty());
}
public byte[] createWorkbook(ExcelWorkbookData data) {
try (Workbook workbook = ExcelMapper.writeToWorkbook( try (Workbook workbook = ExcelMapper.writeToWorkbook(
List.<ExcelTemplateRows.Wave>of(), ExcelTemplateRows.Wave.class, WAVE_SHEET); data.waves(), ExcelTemplateRows.Wave.class, WAVE_SHEET);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
append(workbook, WAVE_INFO_SHEET, ExcelTemplateRows.WaveInfo.class); append(workbook, WAVE_INFO_SHEET, data.waveInfos(), ExcelTemplateRows.WaveInfo.class);
append(workbook, SURVEY_SHEET, ExcelTemplateRows.Survey.class); append(workbook, SURVEY_SHEET, data.surveys(), ExcelTemplateRows.Survey.class);
append(workbook, SURVEY_ITEM_SHEET, ExcelTemplateRows.SurveyItem.class); append(workbook, SURVEY_ITEM_SHEET, data.surveyItems(), ExcelTemplateRows.SurveyItem.class);
append(workbook, PART_SHEET, ExcelTemplateRows.Part.class); append(workbook, PART_SHEET, data.parts(), ExcelTemplateRows.Part.class);
append(workbook, PART_ITEM_SHEET, ExcelTemplateRows.PartItem.class); append(workbook, PART_ITEM_SHEET, data.partItems(), ExcelTemplateRows.PartItem.class);
append(workbook, PART_ITEM_SUB_SHEET, ExcelTemplateRows.PartItemSub.class); append(workbook, PART_ITEM_SUB_SHEET, data.partItemSubs(),
append(workbook, PART_ITEM_BASE_SHEET, ExcelTemplateRows.PartItemBase.class); ExcelTemplateRows.PartItemSub.class);
append(workbook, PART_ITEM_DATA_SHEET, ExcelTemplateRows.PartItemData.class); append(workbook, PART_ITEM_BASE_SHEET, data.partItemBases(),
ExcelTemplateRows.PartItemBase.class);
append(workbook, PART_ITEM_CHART_SHEET, data.partItemCharts(),
ExcelTemplateRows.PartItemChart.class);
append(workbook, PART_ITEM_CHART_HIGHLIGHT_SHEET,
data.partItemChartHighlights(), ExcelTemplateRows.PartItemChartHighlight.class);
append(workbook, PART_ITEM_DATA_SHEET, data.partItemData(),
ExcelTemplateRows.PartItemData.class);
workbook.write(outputStream); workbook.write(outputStream);
return outputStream.toByteArray(); return outputStream.toByteArray();
} catch (IOException | RuntimeException exception) { } catch (IOException | RuntimeException exception) {
@@ -45,7 +59,12 @@ public class ExcelTemplateService {
} }
} }
private <T> void append(Workbook workbook, String sheetName, Class<T> rowType) { private <T> void append(
ExcelMapper.appendSheetToWorkbook(workbook, List.of(), rowType, sheetName, 1); Workbook workbook,
String sheetName,
List<T> rows,
Class<T> rowType
) {
ExcelMapper.appendSheetToWorkbook(workbook, rows, rowType, sheetName, 1);
} }
} }

View File

@@ -43,7 +43,7 @@ public class ReferenceFileStorageService {
MultipartFile file MultipartFile file
) { ) {
validateRequest(waveCd, fileTitle, fileOrder, file); validateRequest(waveCd, fileTitle, fileOrder, file);
if (!waveRepository.existsById(waveCd)) { if (waveRepository.findForUpdateById(waveCd).isEmpty()) {
throw BusinessException.validationError( throw BusinessException.validationError(
"WAVE_NOT_FOUND", "존재하지 않는 waveCd입니다.").with("waveCd", waveCd); "WAVE_NOT_FOUND", "존재하지 않는 waveCd입니다.").with("waveCd", waveCd);
} }
@@ -61,10 +61,15 @@ public class ReferenceFileStorageService {
throw invalidFilename("허용되지 않는 파일 경로입니다."); throw invalidFilename("허용되지 않는 파일 경로입니다.");
} }
TFileEntity entity = fileRepository.findFirstByWaveCdAndFileOrder(waveCd, fileOrder)
.orElseGet(TFileEntity::new);
validateFilenameConflict(waveCd, originalFilename, entity.getId());
String previousFilename = entity.getFileName();
Path previousTarget = previousFilename == null
? null : resolveStoredTarget(targetDirectory, previousFilename);
Path stagedFile = stageFile(targetDirectory, file); Path stagedFile = stageFile(targetDirectory, file);
try { try {
TFileEntity entity = fileRepository.findFirstByWaveCdAndFileName(waveCd, originalFilename)
.orElseGet(TFileEntity::new);
entity.setWaveCd(waveCd); entity.setWaveCd(waveCd);
entity.setFileOrder(fileOrder); entity.setFileOrder(fileOrder);
entity.setFileTitle(normalizedTitle); entity.setFileTitle(normalizedTitle);
@@ -74,6 +79,9 @@ public class ReferenceFileStorageService {
replaceFileWithRollbackProtection(stagedFile, target); replaceFileWithRollbackProtection(stagedFile, target);
stagedFile = null; stagedFile = null;
if (previousTarget != null && !previousTarget.equals(target)) {
removeFileWithRollbackProtection(previousTarget);
}
String relativePath = REFERENCES_DIRECTORY + "/" + waveCd + "/" + originalFilename; String relativePath = REFERENCES_DIRECTORY + "/" + waveCd + "/" + originalFilename;
return new ReferenceFileUploadResponse( return new ReferenceFileUploadResponse(
@@ -154,6 +162,30 @@ public class ReferenceFileStorageService {
return fileType; return fileType;
} }
private void validateFilenameConflict(
Short waveCd,
String originalFilename,
Integer currentFileId
) {
fileRepository.findFirstByWaveCdAndFileName(waveCd, originalFilename)
.filter(existing -> !existing.getId().equals(currentFileId))
.ifPresent(existing -> {
throw BusinessException.validationError(
"REFERENCE_FILENAME_CONFLICT",
"같은 Wave의 다른 파일 순서에서 이미 사용 중인 파일명입니다.")
.with("waveCd", waveCd)
.with("fileOrder", existing.getFileOrder());
});
}
private Path resolveStoredTarget(Path targetDirectory, String filename) {
Path storedTarget = targetDirectory.resolve(filename).normalize();
if (!storedTarget.startsWith(targetDirectory)) {
throw storageError();
}
return storedTarget;
}
private Path stageFile(Path targetDirectory, MultipartFile file) { private Path stageFile(Path targetDirectory, MultipartFile file) {
Path stagedFile = null; Path stagedFile = null;
try { try {
@@ -215,6 +247,58 @@ public class ReferenceFileStorageService {
}); });
} }
private void removeFileWithRollbackProtection(Path target) {
if (!Files.exists(target)) {
return;
}
Path backupFile = null;
boolean targetMoved = false;
try {
backupFile = Files.createTempFile(target.getParent(), ".backup-", ".tmp");
moveReplacing(target, backupFile);
targetMoved = true;
registerRemovedFileSynchronization(target, backupFile);
} catch (IOException | RuntimeException exception) {
if (targetMoved) {
restoreRemovedFile(target, backupFile);
} else {
deleteQuietly(backupFile, "완성되지 않은 이전 파일 백업을 삭제하지 못했습니다.");
}
throw storageError();
}
}
private void registerRemovedFileSynchronization(Path target, Path backupFile) {
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
restoreRemovedFile(target, backupFile);
throw BusinessException.internalError(
"REFERENCE_FILE_TRANSACTION_REQUIRED", "파일 저장 트랜잭션을 시작할 수 없습니다.");
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCompletion(int status) {
if (status == STATUS_COMMITTED) {
deleteQuietly(backupFile, "교체된 이전 파일의 백업을 삭제하지 못했습니다.");
return;
}
restoreRemovedFile(target, backupFile);
}
});
}
private void restoreRemovedFile(Path target, Path backupFile) {
if (backupFile == null || !Files.exists(backupFile)) {
return;
}
try {
moveReplacing(backupFile, target);
} catch (IOException exception) {
log.error("트랜잭션 롤백 중 교체 전 파일을 복구하지 못했습니다: {}", target, exception);
} finally {
deleteQuietly(backupFile, "교체 전 파일의 백업을 삭제하지 못했습니다.");
}
}
private void restoreFile(Path target, Path backupFile, boolean targetExisted) { private void restoreFile(Path target, Path backupFile, boolean targetExisted) {
try { try {
if (targetExisted && backupFile != null && Files.exists(backupFile)) { if (targetExisted && backupFile != null && Files.exists(backupFile)) {

View File

@@ -2,6 +2,10 @@ package com.kri.epolicy.dash.back.service;
import com.kri.common.feature.web.BusinessException; import com.kri.common.feature.web.BusinessException;
import com.kri.common.feature.web.RequestUserContext; import com.kri.common.feature.web.RequestUserContext;
import com.kri.epolicy.dash.back.common.enums.ChartGapMode;
import com.kri.epolicy.dash.back.common.enums.ChartHighlightMode;
import com.kri.epolicy.dash.back.common.enums.ChartType;
import com.kri.epolicy.dash.back.common.enums.NegativeMode;
import com.kri.epolicy.dash.back.config.FileStorageProperties; import com.kri.epolicy.dash.back.config.FileStorageProperties;
import com.kri.epolicy.dash.back.dto.response.PartDetailResponse; import com.kri.epolicy.dash.back.dto.response.PartDetailResponse;
import com.kri.epolicy.dash.back.dto.response.PartDetailResponse.Audience; import com.kri.epolicy.dash.back.dto.response.PartDetailResponse.Audience;
@@ -15,6 +19,8 @@ import com.kri.epolicy.dash.back.dto.response.WaveSummaryResponse;
import com.kri.epolicy.dash.back.persistence.entity.TFileEntity; import com.kri.epolicy.dash.back.persistence.entity.TFileEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemBaseEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartItemBaseEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemChartEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemChartHighlightEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemDataEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartItemDataEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartItemEntity;
import com.kri.epolicy.dash.back.persistence.entity.TPartItemSubEntity; import com.kri.epolicy.dash.back.persistence.entity.TPartItemSubEntity;
@@ -24,6 +30,8 @@ import com.kri.epolicy.dash.back.persistence.entity.TWaveEntity;
import com.kri.epolicy.dash.back.persistence.entity.id.TPartEntityId; import com.kri.epolicy.dash.back.persistence.entity.id.TPartEntityId;
import com.kri.epolicy.dash.back.persistence.repository.FileRepository; import com.kri.epolicy.dash.back.persistence.repository.FileRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemBaseRepository; import com.kri.epolicy.dash.back.persistence.repository.PartItemBaseRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemChartHighlightRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemChartRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemDataRepository; import com.kri.epolicy.dash.back.persistence.repository.PartItemDataRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemRepository; import com.kri.epolicy.dash.back.persistence.repository.PartItemRepository;
import com.kri.epolicy.dash.back.persistence.repository.PartItemSubRepository; import com.kri.epolicy.dash.back.persistence.repository.PartItemSubRepository;
@@ -38,6 +46,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -60,6 +69,8 @@ public class WaveQueryService {
private final PartItemRepository partItemRepository; private final PartItemRepository partItemRepository;
private final PartItemSubRepository partItemSubRepository; private final PartItemSubRepository partItemSubRepository;
private final PartItemBaseRepository partItemBaseRepository; private final PartItemBaseRepository partItemBaseRepository;
private final PartItemChartRepository partItemChartRepository;
private final PartItemChartHighlightRepository partItemChartHighlightRepository;
private final PartItemDataRepository partItemDataRepository; private final PartItemDataRepository partItemDataRepository;
private final WaveAccessPolicy waveAccessPolicy; private final WaveAccessPolicy waveAccessPolicy;
private final FileStorageProperties fileStorageProperties; private final FileStorageProperties fileStorageProperties;
@@ -94,6 +105,9 @@ public class WaveQueryService {
survey.getSurveyTitle(), survey.getSurveyTitle(),
survey.getSurveyAlias(), survey.getSurveyAlias(),
survey.getSurveyColor(), survey.getSurveyColor(),
highlightColor(survey),
negativeColor(survey),
negativeHighlightColor(survey),
surveyItems.getOrDefault(survey.getId().getSurveyCd(), List.of()).stream() surveyItems.getOrDefault(survey.getId().getSurveyCd(), List.of()).stream()
.map(item -> new WaveDetailResponse.SurveyItem( .map(item -> new WaveDetailResponse.SurveyItem(
item.getSurveyItemTitle(), item.getSurveyItemContent())) item.getSurveyItemTitle(), item.getSurveyItemContent()))
@@ -134,6 +148,10 @@ public class WaveQueryService {
List<TPartItemSubEntity> subs = partItemSubRepository List<TPartItemSubEntity> subs = partItemSubRepository
.findByIdWaveCdAndIdPartCdOrderByIdPartItemCdAscIdPartItemSubCdAsc(waveCd, partCd); .findByIdWaveCdAndIdPartCdOrderByIdPartItemCdAscIdPartItemSubCdAsc(waveCd, partCd);
List<TPartItemBaseEntity> bases = partItemBaseRepository.findByWaveCdAndPartCd(waveCd, partCd); List<TPartItemBaseEntity> bases = partItemBaseRepository.findByWaveCdAndPartCd(waveCd, partCd);
List<TPartItemChartEntity> charts = partItemChartRepository
.findByWaveCdAndPartCd(waveCd, partCd);
List<TPartItemChartHighlightEntity> highlights = partItemChartHighlightRepository
.findByWaveCdAndPartCd(waveCd, partCd);
List<TPartItemDataEntity> data = partItemDataRepository List<TPartItemDataEntity> data = partItemDataRepository
.findByWaveCdAndPartCdOrderByPartItemDataOrderAsc(waveCd, partCd); .findByWaveCdAndPartCdOrderByPartItemDataOrderAsc(waveCd, partCd);
@@ -144,7 +162,8 @@ public class WaveQueryService {
waveCd, waveCd,
partCd, partCd,
part.getPartTitle(), part.getPartTitle(),
items.stream().map(item -> toItem(item, surveys, surveyByCode, subsByItem, bases, data)) items.stream().map(item -> toItem(
item, surveys, surveyByCode, subsByItem, bases, charts, highlights, data))
.toList() .toList()
); );
} }
@@ -155,6 +174,8 @@ public class WaveQueryService {
Map<Short, TSurveyEntity> surveyByCode, Map<Short, TSurveyEntity> surveyByCode,
Map<Short, List<TPartItemSubEntity>> subsByItem, Map<Short, List<TPartItemSubEntity>> subsByItem,
List<TPartItemBaseEntity> allBases, List<TPartItemBaseEntity> allBases,
List<TPartItemChartEntity> allCharts,
List<TPartItemChartHighlightEntity> allHighlights,
List<TPartItemDataEntity> allData List<TPartItemDataEntity> allData
) { ) {
Short itemCd = item.getId().getPartItemCd(); Short itemCd = item.getId().getPartItemCd();
@@ -162,17 +183,36 @@ public class WaveQueryService {
.filter(base -> base.getPartItemCd().equals(itemCd)).toList(); .filter(base -> base.getPartItemCd().equals(itemCd)).toList();
List<TPartItemDataEntity> data = allData.stream() List<TPartItemDataEntity> data = allData.stream()
.filter(value -> value.getPartItemCd().equals(itemCd)).toList(); .filter(value -> value.getPartItemCd().equals(itemCd)).toList();
List<TPartItemChartEntity> charts = allCharts.stream()
.filter(chart -> chart.getPartItemCd().equals(itemCd)).toList();
List<TPartItemChartHighlightEntity> highlights = allHighlights.stream()
.filter(highlight -> highlight.getPartItemCd().equals(itemCd)).toList();
List<TPartItemSubEntity> subs = subsByItem.getOrDefault(itemCd, List.of()); List<TPartItemSubEntity> subs = subsByItem.getOrDefault(itemCd, List.of());
List<ResultGroup> groups = new ArrayList<>(); List<ResultGroup> groups = new ArrayList<>();
if (subs.isEmpty()) { if (subs.isEmpty()) {
groups.add(toResultGroup(null, bases, data, surveyByCode)); groups.add(toResultGroup(
null,
bases.stream().filter(base -> base.getPartItemSubCd() == null).toList(),
charts.stream().filter(chart -> chart.getPartItemSubCd() == null).toList(),
highlights.stream().filter(highlight -> highlight.getPartItemSubCd() == null).toList(),
data.stream().filter(value -> value.getPartItemSubCd() == null).toList(),
surveyByCode));
} else { } else {
for (TPartItemSubEntity sub : subs) { for (TPartItemSubEntity sub : subs) {
Short subCd = sub.getId().getPartItemSubCd(); Short subCd = sub.getId().getPartItemSubCd();
groups.add(toResultGroup( groups.add(toResultGroup(
new SubItem(subCd, sub.getPartItemSubTitle()), new SubItem(
subCd,
sub.getPartItemSubTitle(),
sub.getPartItemSubComment(),
negativeMode(sub.getPartItemSubNegativeMode()),
negativeOrder(
sub.getPartItemSubNegativeMode(), sub.getPartItemSubNegativeOrder())),
bases.stream().filter(base -> subCd.equals(base.getPartItemSubCd())).toList(), bases.stream().filter(base -> subCd.equals(base.getPartItemSubCd())).toList(),
charts.stream().filter(chart -> subCd.equals(chart.getPartItemSubCd())).toList(),
highlights.stream()
.filter(highlight -> subCd.equals(highlight.getPartItemSubCd())).toList(),
data.stream().filter(value -> subCd.equals(value.getPartItemSubCd())).toList(), data.stream().filter(value -> subCd.equals(value.getPartItemSubCd())).toList(),
surveyByCode)); surveyByCode));
} }
@@ -185,8 +225,9 @@ public class WaveQueryService {
itemCd, itemCd,
item.getPartItemOrder(), item.getPartItemOrder(),
item.getPartItemTitle(), item.getPartItemTitle(),
item.getChartType().getCode(),
item.getPartItemComment(), item.getPartItemComment(),
negativeMode(item.getPartItemNegativeMode()),
negativeOrder(item.getPartItemNegativeMode(), item.getPartItemNegativeOrder()),
toAudience(audienceCodes, surveys, surveyByCode), toAudience(audienceCodes, surveys, surveyByCode),
List.copyOf(groups) List.copyOf(groups)
); );
@@ -195,12 +236,16 @@ public class WaveQueryService {
private ResultGroup toResultGroup( private ResultGroup toResultGroup(
SubItem subItem, SubItem subItem,
List<TPartItemBaseEntity> bases, List<TPartItemBaseEntity> bases,
List<TPartItemChartEntity> charts,
List<TPartItemChartHighlightEntity> highlights,
List<TPartItemDataEntity> data, List<TPartItemDataEntity> data,
Map<Short, TSurveyEntity> surveyByCode Map<Short, TSurveyEntity> surveyByCode
) { ) {
Map<Short, TPartItemBaseEntity> baseBySurvey = bases.stream().collect(Collectors.toMap( Map<Short, TPartItemBaseEntity> baseBySurvey = bases.stream().collect(Collectors.toMap(
TPartItemBaseEntity::getSurveyCd, Function.identity(), (left, right) -> left, TPartItemBaseEntity::getSurveyCd, Function.identity(), (left, right) -> left,
LinkedHashMap::new)); LinkedHashMap::new));
TPartItemChartEntity chart = charts.stream().findFirst().orElse(null);
TPartItemChartHighlightEntity highlight = highlights.stream().findFirst().orElse(null);
Map<Short, List<TPartItemDataEntity>> dataBySurvey = data.stream().collect( Map<Short, List<TPartItemDataEntity>> dataBySurvey = data.stream().collect(
Collectors.groupingBy(TPartItemDataEntity::getSurveyCd, Collectors.groupingBy(TPartItemDataEntity::getSurveyCd,
LinkedHashMap::new, Collectors.toList())); LinkedHashMap::new, Collectors.toList()));
@@ -221,7 +266,15 @@ public class WaveQueryService {
return new Series( return new Series(
surveyCd, surveyCd,
survey.getSurveyAlias(), survey.getSurveyAlias(),
chartType(chart == null ? null : chart.getChartType()),
survey.getSurveyColor(), survey.getSurveyColor(),
highlightColor(survey),
negativeColor(survey),
negativeHighlightColor(survey),
ChartGapMode.fromCodeOrDefault(
chart == null ? null : chart.getChartGapMode()).name(),
highlightMode(highlight == null ? null : highlight.getChartHighlightMode()),
highlightValue(highlight),
base == null ? null : base.getBaseCount(), base == null ? null : base.getBaseCount(),
base == null ? null : base.getBaseText(), base == null ? null : base.getBaseText(),
dataBySurvey.get(surveyCd).stream() dataBySurvey.get(surveyCd).stream()
@@ -233,6 +286,58 @@ public class WaveQueryService {
return new ResultGroup(subItem, categories, series); return new ResultGroup(subItem, categories, series);
} }
private String highlightColor(TSurveyEntity survey) {
return survey.getSurveyHighlightColor() == null
? survey.getSurveyColor() : survey.getSurveyHighlightColor();
}
private String negativeColor(TSurveyEntity survey) {
return survey.getSurveyNegativeColor() == null
? survey.getSurveyColor() : survey.getSurveyNegativeColor();
}
private String negativeHighlightColor(TSurveyEntity survey) {
if (survey.getSurveyNegativeHighlightColor() != null) {
return survey.getSurveyNegativeHighlightColor();
}
if (survey.getSurveyNegativeColor() != null) {
return survey.getSurveyNegativeColor();
}
return highlightColor(survey);
}
private String negativeMode(String code) {
return NegativeMode.fromCodeOrDefault(code).name();
}
private String negativeOrder(String modeCode, String order) {
return NegativeMode.fromCodeOrDefault(modeCode) == NegativeMode.SPECIFIED
? order : null;
}
private String chartType(String code) {
try {
return ChartType.fromCode(code).getCode();
} catch (IllegalArgumentException exception) {
return ChartType.BAR.getCode();
}
}
private String highlightMode(String code) {
try {
return ChartHighlightMode.fromCode(code).name();
} catch (IllegalArgumentException exception) {
return null;
}
}
private String highlightValue(TPartItemChartHighlightEntity highlight) {
return highlight != null
&& ChartHighlightMode.SPECIFIED.name()
.equals(highlightMode(highlight.getChartHighlightMode()))
? highlight.getChartHighlightValue() : null;
}
private Audience toAudience( private Audience toAudience(
Set<Short> audienceCodes, Set<Short> audienceCodes,
List<TSurveyEntity> surveys, List<TSurveyEntity> surveys,
@@ -244,7 +349,7 @@ public class WaveQueryService {
} }
String label = audienceCodes.stream() String label = audienceCodes.stream()
.map(surveyByCode::get) .map(surveyByCode::get)
.filter(java.util.Objects::nonNull) .filter(Objects::nonNull)
.sorted(Comparator.comparing(TSurveyEntity::getSurveyOrder)) .sorted(Comparator.comparing(TSurveyEntity::getSurveyOrder))
.map(TSurveyEntity::getSurveyAlias) .map(TSurveyEntity::getSurveyAlias)
.collect(Collectors.joining(", ")); .collect(Collectors.joining(", "));

Binary file not shown.