commit c595ab41b815d1ed16deb56764b09b011e21ad5c Author: kric_jspark Date: Thu Aug 13 17:14:13 2026 +0900 260813_01_FST: First Commit diff --git a/.agent/profile.yml b/.agent/profile.yml new file mode 100644 index 0000000..ae0e369 --- /dev/null +++ b/.agent/profile.yml @@ -0,0 +1,21 @@ +schema_version: 1 + +project: + id: epolicy-dash-back + name: "epolicy-dash-back" + type: requested-project + layer: backend + legacy: false + +stack: + - java-springboot + +shared_contracts: + consumes: + - kri-common + +databases: + - id: primary + engine: mysql + role: primary + access: read-write diff --git a/.agent/project.md b/.agent/project.md new file mode 100644 index 0000000..519f1ad --- /dev/null +++ b/.agent/project.md @@ -0,0 +1,51 @@ +## 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. + +## 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 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 + +- 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. +- 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)`. +- 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. +- 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 + +- 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. +- 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. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e081a32 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary +/AGENTS.md text eol=lf +/CLAUDE.md text eol=lf +/.agent/*.md text eol=lf +/.agent/*.yml text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..996f440 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr +out/ + +### VS Code ### +.vscode/ + +### Logs / runtime files ### +logs/ +upload-file/ +docs/ +*.log + +### OS ### +.DS_Store +Thumbs.db diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..85821a0 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,313 @@ + + +# KRI Development Base Instructions + +This document defines the shared working rules for KRI development repositories. +Keep project-specific facts and commands in the project profile and project rules. + +## Instruction Resolution + +Apply repository instructions in this order: + +1. Base rules +2. Project-type rules +3. Technology-stack rules +4. Shared consumer contracts +5. Project-specific rules +6. The explicitly approved task scope + +Later and more specific instructions may override earlier general instructions only within their stated scope. + +- Apply a shared consumer contract only when `.agent/profile.yml` declares it. +- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files. +- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive. + +## Communication + +- Respond to the user in Korean unless the user requests another language. +- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form. +- Follow the repository's existing language conventions for code comments and user-facing messages. +- Lead with the result or decision, then provide only the detail needed to verify it. +- Do not create or retain a full session transcript. + +## Work Authorization + +- The default workflow is discussion first and explicit execution approval second. +- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection. +- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup. +- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state. +- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks. +- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands. +- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope. +- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages. + +## Local Development Environment + +- Primary OS: Windows 11. +- Primary shell: PowerShell. +- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior. +- Prefer repository-provided wrappers and scripts over globally installed commands. +- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them. +- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration. +- Do not install or modify global toolchains as part of a project task. + +Preferred human-facing tools: + +- Classic ASP: Visual Studio Code +- Java and Spring Boot: IntelliJ IDEA +- C# and .NET: JetBrains Rider +- JavaScript, TypeScript, and Next.js: JetBrains WebStorm +- Python: JetBrains PyCharm +- Microsoft SQL Server: SQL Server Management Studio +- Other databases: JetBrains DataGrip + +- These preferences do not authorize launching or controlling a GUI application. +- Prefer IDE-independent commands that can also run in CI. +- Do not modify global IDE settings. +- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it. +- Preserve existing shared IDE configuration when it is already tracked. + +## PowerShell and Path Safety + +- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters. +- Prefer `-LiteralPath` when operating on an exact filesystem path. +- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`. +- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations. +- Keep a filesystem operation within one shell from target resolution through execution. +- Before a recursive delete or move, resolve and verify every absolute target. +- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target. +- Prefer recoverable operations when practical. + +## Change Discipline + +- Preserve all existing user changes, including uncommitted and untracked work. +- Keep changes minimal but complete for the approved objective. +- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring. +- Do not overwrite or revert unrelated changes. +- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely. +- Prefer changing an authoritative source over editing generated output. +- Treat files marked as generated as read-only unless regeneration is part of the approved plan. +- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required. +- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope. + +## Text Encoding and Korean Content Safety + +- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract. +- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them. +- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text. +- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them. +- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change. +- Avoid whole-file rewrites for small changes. +- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit. +- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding. +- Treat a console display problem and an on-disk encoding problem as separate issues. +- After editing Korean text, inspect the diff for replacement characters (`�`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes. +- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding. +- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence. +- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM. + +## Git Safety + +- Use `git status`, `git diff`, and `git log` for read-only investigation. +- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved. +- Source-edit approval does not include commit or push approval. +- Never amend an existing commit unless explicitly requested. +- Before an approved commit, show the intended files, validation results, and proposed commit message. +- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push. + +## Dependencies and External Actions + +- Use the package manager, lockfile, and toolchain already selected by the repository. +- Do not install global packages. +- Do not add, remove, or upgrade a dependency unless it was included in the approved plan. +- Pause for approval if an unplanned dependency becomes necessary. +- Keep lockfiles synchronized with approved dependency changes. +- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested. +- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service. +- Remove secrets and unnecessary internal identifiers from external search queries. + +## Database Safety + +- Treat writing or reviewing SQL as source code separately from executing SQL against a database. +- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope. +- Do not connect to a shared, staging, or production database without explicit authorization for that environment. +- Read-only queries against a non-local database also require authorization because results may contain sensitive data. +- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation. +- Source-change approval does not authorize migration execution. +- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature. +- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output. + +## Secrets and Sensitive Data + +- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control. +- Read sensitive files only when the approved task requires it and no safer source exists. +- Prefer inspecting configuration keys and schemas without displaying secret values. +- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots. +- Redact sensitive values when reporting errors or command output. +- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action. +- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized. + +## Validation + +- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands. +- Include intended validation in the discussion-phase plan. +- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate. +- Limit formatting to files within the approved scope. +- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized. +- Do not claim that a check passed unless it was executed successfully. +- If a check cannot be run, state the exact reason. +- Distinguish a current-change failure from a pre-existing failure or an undetermined failure. +- Do not fix unrelated failures without expanding the approved scope. +- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes. + +## Artifacts and Session Records + +- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested. +- Store durable information in the repository's existing documentation structure. +- Do not place generated reports or temporary analysis files in the repository root. +- Remove task-specific temporary files created by the current task after validation when removal is safe. + +## Completion Report + +When implementation is complete, report in Korean: + +- what changed and why; +- the main affected files or components; +- validation commands actually executed and their results; +- checks not executed and the reason; +- remaining risks, assumptions, or follow-up work; +- database, deployment, dependency, encoding, and compatibility impact when applicable. + +- Do not report completion while required validation is failing or known encoding corruption is unresolved. +- Keep the report concise and do not include a full session transcript. + +## Requested Project Rules + +- Treat the approved requirements, acceptance criteria, and recorded decisions as the primary scope boundary. +- Do not infer a requirement solely from a file name, folder date, or apparently newer document. +- When requirements conflict, report the exact sources and request a decision. +- Preserve original customer, partner, and planning documents as read-only evidence unless document editing is explicitly approved. +- Summarize durable implementation requirements inside the repository rather than relying only on files outside the repository. +- Do not expand the deliverable with speculative features, infrastructure, or architectural changes. +- Record material assumptions and unresolved decisions in the project-specific rules or existing project documentation. +- Define observable acceptance criteria before implementation. +- Treat separately managed Frontend and Backend repositories as independent deliverables with a coordinated contract. +- Protect customer, partner, survey, and field data as sensitive information. +- Keep handoff, operation, configuration, and validation instructions usable by the requesting team. +- Report deviations from the requested scope and obtain approval before proceeding. + +## Java and Spring Boot + +- Treat the configured JDK, Spring Boot, Gradle, plugin, dependency, and package versions as authoritative. +- Use the repository's Gradle Wrapper. Do not substitute a machine-global Gradle installation. +- Preserve the established package layout and controller, application/service, domain, and persistence boundaries. +- Keep controllers thin, place business rules in the established service/domain layer, and prefer constructor injection. +- Apply request and configuration validation at boundaries and preserve the project's exception and response conventions. +- Make transaction boundaries explicit and narrow; do not add broad transactions to hide lifecycle or query problems. +- Preserve authentication, authorization, auditing, logging, and secret-management conventions. +- Do not edit generated QueryDSL or other generated sources. Change their source definitions and regenerate only when the repository workflow requires it. +- Use the approved KriCommon contract when the project profile includes it; do not duplicate shared backend behavior locally. +- Run the narrowest relevant Gradle compile, test, static-analysis, and build tasks. + +## MySQL + +- Use MySQL syntax and behavior only for data sources whose declared engine is `mysql`. +- Preserve the configured version, schema, character set, collation, time zone, naming, migration, and access conventions. +- Parameterize values. Do not build SQL by concatenating untrusted input. +- Consider indexes and execution plans for changed filters, joins, ordering, grouping, and pagination without guessing from small data sets. +- Preserve transaction, locking, null, date/time, decimal, and generated-key semantics. +- Do not introduce MSSQL or other dialect syntax into MySQL paths. +- A source-code change approval authorizes SQL analysis and migration drafting only. Execute DDL, DML, procedures, or migrations only with separate explicit approval and the declared data-source access level. + +## KriCommon Consumer Contract + +### Dependency and API Boundary + +- Consume KriCommon as `com.kri.common:starter:` using the consumer repository's established Gradle dependency and version-management conventions. +- 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. + +## 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. + +## 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 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 + +- 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. +- 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)`. +- 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. +- 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 + +- 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. +- 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. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..eecb3ac --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# epolicy-dash-back + +epolicy-dash-back Spring Boot application + +## 기술 구성 + +- Java 17 +- Spring Boot 3.5.7 +- `com.kri.common:starter:beta.1.6.4` +- JPA + QueryDSL + JdbcTemplate +- EmbeddedId 예제 +- MyBatis는 생성 옵션에 따라 포함 + +## Gitea Maven 인증 + +Windows 사용자 Gradle 설정: + +```text +%USERPROFILE%\.gradle\gradle.properties +``` + +```properties +giteaUser=사용자명 +giteaToken=Gitea토큰 +``` + +또는 다음 환경변수를 사용할 수 있습니다. + +```text +GITEA_MAVEN_USER +GITEA_MAVEN_TOKEN +``` + +## 실행 + +Windows: + +```powershell +.\gradlew.bat bootRun +``` + +Linux/macOS: + +```bash +./gradlew bootRun +``` + +프로필 지정: + +```powershell +.\gradlew.bat bootRun --args="--spring.profiles.active=local" +``` + +## 빌드 + +```powershell +.\gradlew.bat clean build +``` + +## 인증 설정 + +공용 Starter 설정으로 제어합니다. + +```yaml +kri: + security: + enabled: true + auth: + apikey: + enabled: false +``` + +프로젝트 내부에 JWT/API Key 필터를 중복 구현하지 않습니다. + +## Agent Harness + +- 프로젝트 ID: `epolicy-dash-back` +- 프로젝트 유형: `requested-project` +- 권위 원본: `.agent/profile.yml`, `.agent/project.md` + +`AGENTS.md`와 `CLAUDE.md`는 중앙 Agent Harness가 합성합니다. 두 파일을 직접 수정하지 않습니다. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..fe76475 --- /dev/null +++ b/build.gradle @@ -0,0 +1,104 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.5.7' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.kri.epolicy.dash.back' +version = '0.0.1-SNAPSHOT' +description = 'epolicy-dash-back Spring Boot application' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +def giteaUser = findProperty('giteaUser') + ?: System.getenv('GITEA_MAVEN_USER') + ?: '' +def giteaToken = findProperty('giteaToken') + ?: System.getenv('GITEA_MAVEN_TOKEN') + ?: '' + +repositories { + mavenCentral() + + maven { + name = 'gitea' + url = uri('https://gitea.kric.com/api/packages/KRi/maven') + credentials { + username = giteaUser + password = giteaToken + } + } +} + +configurations.configureEach { + resolutionStrategy.cacheDynamicVersionsFor 0, 'seconds' +} + +dependencies { + implementation 'com.kri.common:starter:beta.1.6.4' + implementation 'org.apache.poi:poi-ooxml:5.5.1' + + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.11' + + implementation 'io.github.openfeign.querydsl:querydsl-jpa:7.1' + annotationProcessor 'com.querydsl:querydsl-apt:5.0.0:jakarta' + annotationProcessor 'jakarta.annotation:jakarta.annotation-api' + annotationProcessor 'jakarta.persistence:jakarta.persistence-api' + + runtimeOnly 'com.mysql:mysql-connector-j' + + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + developmentOnly 'org.springframework.boot:spring-boot-devtools' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +def querydslDir = layout.buildDirectory.dir('generated/querydsl').get().asFile + +sourceSets { + main.java.srcDirs += [querydslDir] +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.generatedSourceOutputDirectory.set(file(querydslDir)) +} + +tasks.withType(Test).configureEach { + jvmArgs '-Dfile.encoding=UTF-8' +} + +tasks.withType(JavaExec).configureEach { + jvmArgs '-Dfile.encoding=UTF-8' +} + +tasks.named('test') { + useJUnitPlatform() +} + +tasks.named('clean') { + doLast { + delete querydslDir + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..0e829de --- /dev/null +++ b/gradle.properties @@ -0,0 +1,5 @@ +# Keep the Gradle daemon on the platform charset so Windows JDK 17 can read +# worker classpath files containing non-ASCII project paths. +org.gradle.jvmargs=-Xmx2g +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..a38d6cb --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'epolicy-dash-back' diff --git a/src/main/java/com/kri/epolicy/dash/back/EpolicyDashBackApplication.java b/src/main/java/com/kri/epolicy/dash/back/EpolicyDashBackApplication.java new file mode 100644 index 0000000..666a5f3 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/EpolicyDashBackApplication.java @@ -0,0 +1,14 @@ +package com.kri.epolicy.dash.back; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class EpolicyDashBackApplication { + + public static void main(String[] args) { + SpringApplication.run(EpolicyDashBackApplication.class, args); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/common/enums/ChartType.java b/src/main/java/com/kri/epolicy/dash/back/common/enums/ChartType.java new file mode 100644 index 0000000..c0f9a66 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/common/enums/ChartType.java @@ -0,0 +1,39 @@ +package com.kri.epolicy.dash.back.common.enums; + +import com.kri.common.feature.enums.CodeEnum; +import java.util.Arrays; + +public enum ChartType implements CodeEnum { + BAR("BAR", "bar"); + + private final String code; + private final String label; + + ChartType(String code, String label) { + this.code = code; + this.label = label; + } + + @Override + public String getCode() { + return code; + } + + public String getLabel() { + return label; + } + + public static ChartType fromLabel(String label) { + return Arrays.stream(values()) + .filter(type -> type.label.equalsIgnoreCase(label)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("지원하지 않는 차트 유형입니다: " + label)); + } + + public static ChartType fromCode(String code) { + return Arrays.stream(values()) + .filter(type -> type.code.equalsIgnoreCase(code)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("지원하지 않는 차트 코드입니다: " + code)); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/common/enums/SystemEventType.java b/src/main/java/com/kri/epolicy/dash/back/common/enums/SystemEventType.java new file mode 100644 index 0000000..16b1b2e --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/common/enums/SystemEventType.java @@ -0,0 +1,21 @@ +package com.kri.epolicy.dash.back.common.enums; + +import com.kri.common.feature.enums.CodeEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +@Schema(description = "시스템 이벤트 타입") +public enum SystemEventType implements CodeEnum { + //1의 자리 1 insert, 2 update, 3 delete, 4 upload + //100의 자리 대분류, 10의 자리 소분류 + + LOGIN((short) 111), // 로그인 + LOGOUT((short) 121), // 로그 아웃 + + DUMMY((short) 9999); + + private final Short code; +} diff --git a/src/main/java/com/kri/epolicy/dash/back/common/util/StringNormalizer.java b/src/main/java/com/kri/epolicy/dash/back/common/util/StringNormalizer.java new file mode 100644 index 0000000..27c77f5 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/common/util/StringNormalizer.java @@ -0,0 +1,13 @@ +package com.kri.epolicy.dash.back.common.util; + +public final class StringNormalizer { + + private StringNormalizer() { + } + + public static String trimToNull(String value) { + if (value == null) return null; + String normalized = value.trim(); + return normalized.isEmpty() ? null : normalized; + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/common/validation/package-info.java b/src/main/java/com/kri/epolicy/dash/back/common/validation/package-info.java new file mode 100644 index 0000000..241bbcb --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/common/validation/package-info.java @@ -0,0 +1,4 @@ +/** + * 프로젝트 전용 Bean Validation annotation과 validator를 배치합니다. + */ +package com.kri.epolicy.dash.back.common.validation; diff --git a/src/main/java/com/kri/epolicy/dash/back/config/FileStorageProperties.java b/src/main/java/com/kri/epolicy/dash/back/config/FileStorageProperties.java new file mode 100644 index 0000000..c1e88b7 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/config/FileStorageProperties.java @@ -0,0 +1,14 @@ +package com.kri.epolicy.dash.back.config; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.file") +public class FileStorageProperties { + + private String baseDir = "./upload-file"; + private String resourcePattern = "/files/**"; +} diff --git a/src/main/java/com/kri/epolicy/dash/back/config/JdbcConfig.java b/src/main/java/com/kri/epolicy/dash/back/config/JdbcConfig.java new file mode 100644 index 0000000..4d75fc5 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/config/JdbcConfig.java @@ -0,0 +1,15 @@ +package com.kri.epolicy.dash.back.config; + +import javax.sql.DataSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +@Configuration +public class JdbcConfig { + + @Bean + public JdbcTemplate jdbcTemplate(DataSource dataSource) { + return new JdbcTemplate(dataSource); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/config/QueryDSLConfig.java b/src/main/java/com/kri/epolicy/dash/back/config/QueryDSLConfig.java new file mode 100644 index 0000000..a4e07d7 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/config/QueryDSLConfig.java @@ -0,0 +1,19 @@ +package com.kri.epolicy.dash.back.config; + +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@RequiredArgsConstructor +public class QueryDSLConfig { + + private final EntityManager entityManager; + + @Bean + public JPAQueryFactory jpaQueryFactory() { + return new JPAQueryFactory(entityManager); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/config/WebResourceConfig.java b/src/main/java/com/kri/epolicy/dash/back/config/WebResourceConfig.java new file mode 100644 index 0000000..b2c1268 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/config/WebResourceConfig.java @@ -0,0 +1,26 @@ +package com.kri.epolicy.dash.back.config; + +import java.nio.file.Path; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@RequiredArgsConstructor +public class WebResourceConfig implements WebMvcConfigurer { + + private final FileStorageProperties fileStorageProperties; + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + String location = Path.of(fileStorageProperties.getBaseDir()) + .toAbsolutePath() + .normalize() + .toUri() + .toString(); + + registry.addResourceHandler(fileStorageProperties.getResourcePattern()) + .addResourceLocations(location.endsWith("/") ? location : location + "/"); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/controller/AuthController.java b/src/main/java/com/kri/epolicy/dash/back/controller/AuthController.java new file mode 100644 index 0000000..6ac1332 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/controller/AuthController.java @@ -0,0 +1,52 @@ +package com.kri.epolicy.dash.back.controller; + +import com.kri.common.feature.datetime.DateTimeUtil; +import com.kri.common.feature.web.RequestUserContext; +import com.kri.epolicy.dash.back.dto.auth.LoginRequestDto; +import com.kri.epolicy.dash.back.dto.auth.LoginResponseDto; +import com.kri.epolicy.dash.back.service.AuthService; +import com.kri.epolicy.dash.back.service.common.SystemEventLogService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import java.time.LocalDateTime; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/auth") +@RequiredArgsConstructor +@Tag(name = "Auth", description = "인증 API") +public class AuthController { + + private final AuthService authService; + private final SystemEventLogService systemEventLogService; + + @Operation(summary = "로그인 요청") + @PostMapping("/login") + public LoginResponseDto tryLogin( + @Valid @RequestBody LoginRequestDto request, + RequestUserContext ctx + ) { + final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime(); + + LoginResponseDto response = authService.tryLogin(request); + systemEventLogService.writeLoginLog(response.getUser().getUserId(), now, ctx.getClientIp()); + + return response; + } + + @Operation(summary = "로그아웃 요청") + @PostMapping("/logout/{userId}") + public boolean logout(@PathVariable String userId, RequestUserContext ctx) { + final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime(); + + systemEventLogService.writeLogoutLog(userId, now, ctx.getClientIp()); + + return true; + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/controller/ExcelController.java b/src/main/java/com/kri/epolicy/dash/back/controller/ExcelController.java new file mode 100644 index 0000000..6ead28a --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/controller/ExcelController.java @@ -0,0 +1,42 @@ +package com.kri.epolicy.dash.back.controller; + +import com.kri.epolicy.dash.back.dto.response.ExcelImportResponse; +import com.kri.epolicy.dash.back.service.ExcelImportService; +import com.kri.epolicy.dash.back.service.ExcelTemplateService; +import java.nio.charset.StandardCharsets; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v1/excel") +public class ExcelController { + + private final ExcelImportService excelImportService; + private final ExcelTemplateService excelTemplateService; + + @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ExcelImportResponse importExcel(@RequestPart("file") MultipartFile file) { + return excelImportService.importWorkbook(file); + } + + @GetMapping(value = "/template", produces = ExcelTemplateService.EXCEL_CONTENT_TYPE) + public ResponseEntity exportTemplate() { + ContentDisposition disposition = ContentDisposition.attachment() + .filename(ExcelTemplateService.TEMPLATE_FILENAME, StandardCharsets.UTF_8) + .build(); + return ResponseEntity.ok() + .header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString()) + .contentType(MediaType.parseMediaType(ExcelTemplateService.EXCEL_CONTENT_TYPE)) + .body(excelTemplateService.createTemplate()); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/controller/ReferenceFileController.java b/src/main/java/com/kri/epolicy/dash/back/controller/ReferenceFileController.java new file mode 100644 index 0000000..f5fa5c0 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/controller/ReferenceFileController.java @@ -0,0 +1,36 @@ +package com.kri.epolicy.dash.back.controller; + +import com.kri.epolicy.dash.back.dto.response.ReferenceFileUploadResponse; +import com.kri.epolicy.dash.back.service.ReferenceFileStorageService; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.Size; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@Validated +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v1/references") +public class ReferenceFileController { + + private final ReferenceFileStorageService referenceFileStorageService; + + @PostMapping(value = "/{waveCd}/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ReferenceFileUploadResponse upload( + @PathVariable @Positive Short waveCd, + @RequestParam("fileTitle") @NotBlank @Size(max = 128) String fileTitle, + @RequestParam("fileOrder") @Positive Short fileOrder, + @RequestPart("file") MultipartFile file + ) { + return referenceFileStorageService.store(waveCd, fileTitle, fileOrder, file); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/controller/WaveController.java b/src/main/java/com/kri/epolicy/dash/back/controller/WaveController.java new file mode 100644 index 0000000..d697f0f --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/controller/WaveController.java @@ -0,0 +1,43 @@ +package com.kri.epolicy.dash.back.controller; + +import com.kri.common.feature.web.RequestUserContext; +import com.kri.epolicy.dash.back.dto.response.PartDetailResponse; +import com.kri.epolicy.dash.back.dto.response.WaveDetailResponse; +import com.kri.epolicy.dash.back.dto.response.WaveSummaryResponse; +import com.kri.epolicy.dash.back.service.WaveQueryService; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v1/waves") +public class WaveController { + + private final WaveQueryService waveQueryService; + + @GetMapping + public List findWaves(RequestUserContext userContext) { + return waveQueryService.findWaves(userContext); + } + + @GetMapping("/{waveCd}") + public WaveDetailResponse findWave( + @PathVariable Short waveCd, + RequestUserContext userContext + ) { + return waveQueryService.findWave(waveCd, userContext); + } + + @GetMapping("/{waveCd}/parts/{partCd}") + public PartDetailResponse findPart( + @PathVariable Short waveCd, + @PathVariable Short partCd, + RequestUserContext userContext + ) { + return waveQueryService.findPart(waveCd, partCd, userContext); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/auth/LoginRequestDto.java b/src/main/java/com/kri/epolicy/dash/back/dto/auth/LoginRequestDto.java new file mode 100644 index 0000000..b201229 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/auth/LoginRequestDto.java @@ -0,0 +1,17 @@ +package com.kri.epolicy.dash.back.dto.auth; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Schema(description = "사용자 로그인 요청") +public class LoginRequestDto { + + @Schema(description = "사용자 ID") + private String userId; + + @Schema(description = "사용자 PW") + private String userPw; +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/auth/LoginResponseDto.java b/src/main/java/com/kri/epolicy/dash/back/dto/auth/LoginResponseDto.java new file mode 100644 index 0000000..ce305d1 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/auth/LoginResponseDto.java @@ -0,0 +1,24 @@ +package com.kri.epolicy.dash.back.dto.auth; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +@Schema(description = "로그인 응답") +public class LoginResponseDto { + + @Schema(description = "jwt access 토큰") + private String accessToken; + + @Schema(description = "사용자 정보") + private UserDto user; + + public static LoginResponseDto from(String accessToken, UserDto user) { + return LoginResponseDto.builder() + .accessToken(accessToken) + .user(user) + .build(); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/auth/UserDto.java b/src/main/java/com/kri/epolicy/dash/back/dto/auth/UserDto.java new file mode 100644 index 0000000..29e3dec --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/auth/UserDto.java @@ -0,0 +1,47 @@ +package com.kri.epolicy.dash.back.dto.auth; + +import com.kri.epolicy.dash.back.persistence.entity.TUserEntity; +import io.swagger.v3.oas.annotations.media.Schema; +import java.util.Map; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class UserDto { + + @Schema(description = "사용자 ID") + private String userId; + + @Schema(description = "사용자 소속 회사") + private String userCmpn; + + @Schema(description = "팀 코드") + private String userTeam; + + @Schema(description = "사용자 이름") + private String userName; + + @Schema(description = "권한 코드") + private Integer userRole; + + public static UserDto from(TUserEntity entity) { + if (entity == null) { + return null; + } + + return UserDto.builder() + .userId(entity.getUserId()) + .userName(entity.getUserName()) + .userCmpn(entity.getUserCmpn()) + .userTeam(entity.getUserTeam()) + .userRole(entity.getUserRole()) + .build(); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/excel/ExcelTemplateRows.java b/src/main/java/com/kri/epolicy/dash/back/dto/excel/ExcelTemplateRows.java new file mode 100644 index 0000000..f7d2c33 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/excel/ExcelTemplateRows.java @@ -0,0 +1,108 @@ +package com.kri.epolicy.dash.back.dto.excel; + +import com.kri.common.feature.excel.ExcelColumn; +import lombok.Getter; + +public final class ExcelTemplateRows { + + public static final String WAVE_SHEET = "t_wave"; + public static final String WAVE_INFO_SHEET = "t_wave_info"; + public static final String SURVEY_SHEET = "t_survey"; + public static final String SURVEY_ITEM_SHEET = "t_survey_item"; + public static final String PART_SHEET = "t_part"; + 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_BASE_SHEET = "t_part_item_base"; + public static final String PART_ITEM_DATA_SHEET = "t_part_item_data"; + + private ExcelTemplateRows() { + } + + @Getter + public static final class Wave { + @ExcelColumn(header = "wave_cd", order = 0) private String waveCd; + @ExcelColumn(header = "year", order = 1) private String year; + @ExcelColumn(header = "wave", order = 2) private String wave; + @ExcelColumn(header = "label", order = 3) private String label; + @ExcelColumn(header = "is_open (1, 0)", order = 4) private String isOpen; + } + + @Getter + public static final class WaveInfo { + @ExcelColumn(header = "wave_cd", order = 0) private String waveCd; + @ExcelColumn(header = "wave_info_order", order = 1) private String waveInfoOrder; + @ExcelColumn(header = "wave_info_title", order = 2) private String waveInfoTitle; + @ExcelColumn(header = "wave_info_content", order = 3) private String waveInfoContent; + } + + @Getter + public static final class Survey { + @ExcelColumn(header = "wave_cd", order = 0) private String waveCd; + @ExcelColumn(header = "survey_cd", order = 1) private String surveyCd; + @ExcelColumn(header = "survey_order", order = 2) private String surveyOrder; + @ExcelColumn(header = "survey_title", order = 3) private String surveyTitle; + @ExcelColumn(header = "survey_alias", order = 4) private String surveyAlias; + } + + @Getter + public static final class SurveyItem { + @ExcelColumn(header = "wave_cd", order = 0) private String waveCd; + @ExcelColumn(header = "survey_cd", order = 1) private String surveyCd; + @ExcelColumn(header = "survey_item_order", order = 2) private String surveyItemOrder; + @ExcelColumn(header = "survey_item_title", order = 3) private String surveyItemTitle; + @ExcelColumn(header = "survey_item_content", order = 4) private String surveyItemContent; + } + + @Getter + public static final class Part { + @ExcelColumn(header = "wave_cd", order = 0) private String waveCd; + @ExcelColumn(header = "part_cd", order = 1) private String partCd; + @ExcelColumn(header = "part_order", order = 2) private String partOrder; + @ExcelColumn(header = "part_title", order = 3) private String partTitle; + } + + @Getter + public static final class PartItem { + @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_order", order = 3) private String partItemOrder; + @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 = 6) private String partItemComment; + } + + @Getter + public static final class PartItemSub { + @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 = "part_item_sub_title", order = 4) private String partItemSubTitle; + } + + @Getter + public static final class PartItemBase { + @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 = "survey_cd", order = 3) private String surveyCd; + @ExcelColumn(header = "part_item_sub_cd", order = 4) private String partItemSubCd; + @ExcelColumn(header = "base_count", order = 5) private String baseCount; + @ExcelColumn(header = "base_pre_text", order = 6) private String basePreText; + @ExcelColumn(header = "base_post_text", order = 7) private String basePostText; + } + + @Getter + public static final class PartItemData { + @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 = "survey_cd", order = 3) private String surveyCd; + @ExcelColumn(header = "part_item_sub_cd", order = 4) private String partItemSubCd; + @ExcelColumn(header = "part_item_data_order", order = 5) private String partItemDataOrder; + @ExcelColumn(header = "part_item_data_label", order = 6) private String partItemDataLabel; + @ExcelColumn(header = "part_item_data_value", order = 7) private String partItemDataValue; + @ExcelColumn(header = "is_chart_visible (1, 0)", order = 8) private String isChartVisible; + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/request/ExcelData.java b/src/main/java/com/kri/epolicy/dash/back/dto/request/ExcelData.java new file mode 100644 index 0000000..32cc70f --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/request/ExcelData.java @@ -0,0 +1,106 @@ +package com.kri.epolicy.dash.back.dto.request; + +import com.kri.epolicy.dash.back.common.enums.ChartType; +import java.math.BigDecimal; +import java.util.List; + +public record ExcelData( + List waves, + List waveInfos, + List surveys, + List surveyItems, + List parts, + List partItems, + List partItemSubs, + List partItemBases, + List partItemData +) { + + public record WaveRow( + Short waveCd, + Short year, + Short wave, + String label, + Boolean isOpen + ) { + } + + public record WaveInfoRow( + Short waveCd, + Short waveInfoOrder, + String waveInfoTitle, + String waveInfoContent + ) { + } + + public record SurveyRow( + Short waveCd, + Short surveyCd, + Short surveyOrder, + String surveyTitle, + String surveyAlias + ) { + } + + public record SurveyItemRow( + Short waveCd, + Short surveyCd, + Short surveyItemOrder, + String surveyItemTitle, + String surveyItemContent + ) { + } + + public record PartRow( + Short waveCd, + Short partCd, + Short partOrder, + String partTitle + ) { + } + + public record PartItemRow( + Short waveCd, + Short partCd, + Short partItemCd, + Short partItemOrder, + String partItemTitle, + ChartType chartType, + String partItemComment + ) { + } + + public record PartItemSubRow( + Short waveCd, + Short partCd, + Short partItemCd, + Short partItemSubCd, + String partItemSubTitle + ) { + } + + public record PartItemBaseRow( + Short waveCd, + Short partCd, + Short partItemCd, + Short surveyCd, + Short partItemSubCd, + Integer baseCount, + String basePreText, + String basePostText + ) { + } + + public record PartItemDataRow( + Short waveCd, + Short partCd, + Short partItemCd, + Short surveyCd, + Short partItemSubCd, + Short partItemDataOrder, + String partItemDataLabel, + BigDecimal partItemDataValue, + Boolean isChartVisible + ) { + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/response/ExcelImportResponse.java b/src/main/java/com/kri/epolicy/dash/back/dto/response/ExcelImportResponse.java new file mode 100644 index 0000000..c56e7c1 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/response/ExcelImportResponse.java @@ -0,0 +1,14 @@ +package com.kri.epolicy.dash.back.dto.response; + +public record ExcelImportResponse( + int waveCount, + int waveInfoCount, + int surveyCount, + int surveyItemCount, + int partCount, + int partItemCount, + int partItemSubCount, + int partItemBaseCount, + int partItemDataCount +) { +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/response/PartDetailResponse.java b/src/main/java/com/kri/epolicy/dash/back/dto/response/PartDetailResponse.java new file mode 100644 index 0000000..ae95f42 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/response/PartDetailResponse.java @@ -0,0 +1,52 @@ +package com.kri.epolicy.dash.back.dto.response; + +import java.math.BigDecimal; +import java.util.List; + +public record PartDetailResponse( + Short waveCd, + Short partCd, + String title, + List items +) { + + public record Item( + Short partItemCd, + Short order, + String title, + String chartType, + String comment, + Audience audience, + List resultGroups + ) { + } + + public record Audience(String type, String label) { + } + + public record ResultGroup( + SubItem subItem, + List categories, + List series + ) { + } + + public record Category( + Short order, + String label, + Boolean chartVisible + ) { + } + + public record SubItem(Short partItemSubCd, String title) { + } + + public record Series( + Short surveyCd, + String label, + Integer baseCount, + String baseText, + List values + ) { + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/response/ReferenceFileUploadResponse.java b/src/main/java/com/kri/epolicy/dash/back/dto/response/ReferenceFileUploadResponse.java new file mode 100644 index 0000000..50d92b7 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/response/ReferenceFileUploadResponse.java @@ -0,0 +1,13 @@ +package com.kri.epolicy.dash.back.dto.response; + +public record ReferenceFileUploadResponse( + Integer fileIdx, + Short waveCd, + Short fileOrder, + String fileTitle, + String fileType, + String originalFilename, + long size, + String relativePath +) { +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/response/WaveDetailResponse.java b/src/main/java/com/kri/epolicy/dash/back/dto/response/WaveDetailResponse.java new file mode 100644 index 0000000..54ceab8 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/response/WaveDetailResponse.java @@ -0,0 +1,46 @@ +package com.kri.epolicy.dash.back.dto.response; + +import java.util.List; + +public record WaveDetailResponse( + WaveSummaryResponse wave, + List overview, + List surveys, + List parts, + List files +) { + + public record OverviewItem(String title, String content) { + } + + public record Survey( + Short surveyCd, + String title, + String alias, + List items + ) { + } + + public record SurveyItem(String title, String content) { + } + + public record PartMenu( + Short partCd, + String title, + int itemCount, + List items + ) { + } + + public record PartItemMenu(Short partItemCd, String title) { + } + + public record FileDownload( + Integer fileIdx, + String title, + String type, + String fileName, + String downloadUrl + ) { + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/dto/response/WaveSummaryResponse.java b/src/main/java/com/kri/epolicy/dash/back/dto/response/WaveSummaryResponse.java new file mode 100644 index 0000000..c954441 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/dto/response/WaveSummaryResponse.java @@ -0,0 +1,11 @@ +package com.kri.epolicy.dash.back.dto.response; + +public record WaveSummaryResponse( + Short waveCd, + Short year, + Short wave, + String label, + Boolean isOpen, + boolean accessible +) { +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/converter/ChartTypeConverter.java b/src/main/java/com/kri/epolicy/dash/back/persistence/converter/ChartTypeConverter.java new file mode 100644 index 0000000..c5b5c27 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/converter/ChartTypeConverter.java @@ -0,0 +1,13 @@ +package com.kri.epolicy.dash.back.persistence.converter; + +import com.kri.common.feature.jpa.AbstractCodeEnumConverter; +import com.kri.epolicy.dash.back.common.enums.ChartType; +import jakarta.persistence.Converter; + +@Converter +public class ChartTypeConverter extends AbstractCodeEnumConverter { + + public ChartTypeConverter() { + super(ChartType.class); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TFileEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TFileEntity.java new file mode 100644 index 0000000..fed9b84 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TFileEntity.java @@ -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_file") +public class TFileEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "file_idx", nullable = false, updatable = false) + private Integer id; + + @NotNull + @Column(name = "wave_cd", nullable = false) + private Short waveCd; + + @NotNull + @Column(name = "file_order", nullable = false) + private Short fileOrder; + + @Size(max = 128) + @NotNull + @Column(name = "file_title", nullable = false, length = 128) + private String fileTitle; + + @Size(max = 16) + @NotNull + @Column(name = "file_type", nullable = false, length = 16) + private String fileType; + + @Size(max = 64) + @NotNull + @Column(name = "file_name", nullable = false, length = 64) + private String fileName; + + +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartEntity.java new file mode 100644 index 0000000..44e7db6 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartEntity.java @@ -0,0 +1,32 @@ +package com.kri.epolicy.dash.back.persistence.entity; + +import com.kri.epolicy.dash.back.persistence.entity.id.TPartEntityId; +import jakarta.persistence.Column; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +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") +public class TPartEntity { + + @EmbeddedId + private TPartEntityId id; + + @NotNull + @Column(name = "part_order", nullable = false) + private Short partOrder; + + @Size(max = 128) + @NotNull + @Column(name = "part_title", nullable = false, length = 128) + private String partTitle; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemBaseEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemBaseEntity.java new file mode 100644 index 0000000..826229a --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemBaseEntity.java @@ -0,0 +1,57 @@ +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_base") +public class TPartItemBaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "part_item_base_idx", nullable = false, updatable = 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; + + @NotNull + @Column(name = "survey_cd", nullable = false) + private Short surveyCd; + + @Column(name = "part_item_sub_cd") + private Short partItemSubCd; + + @NotNull + @Column(name = "base_count", nullable = false) + private Integer baseCount; + + @Size(max = 128) + @Column(name = "base_pre_text", length = 128) + private String basePreText; + + @Size(max = 128) + @Column(name = "base_post_text", length = 128) + private String basePostText; + + +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemDataEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemDataEntity.java new file mode 100644 index 0000000..376f680 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemDataEntity.java @@ -0,0 +1,62 @@ +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 java.math.BigDecimal; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Entity +@Table(name = "t_part_item_data") +public class TPartItemDataEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "t_part_item_data_idx", nullable = false, updatable = 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; + + @NotNull + @Column(name = "survey_cd", nullable = false) + private Short surveyCd; + + @Column(name = "part_item_sub_cd") + private Short partItemSubCd; + + @NotNull + @Column(name = "part_item_data_order", nullable = false) + private Short partItemDataOrder; + + @Size(max = 128) + @NotNull + @Column(name = "part_item_data_label", nullable = false, length = 128) + private String partItemDataLabel; + + @NotNull + @Column(name = "part_item_data_value", nullable = false, precision = 14, scale = 10) + private BigDecimal partItemDataValue; + + @NotNull + @Column(name = "is_chart_visible", nullable = false) + private Boolean isChartVisible; + +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemEntity.java new file mode 100644 index 0000000..84e82b9 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemEntity.java @@ -0,0 +1,46 @@ +package com.kri.epolicy.dash.back.persistence.entity; + +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.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.Convert; +import jakarta.persistence.Lob; +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") +public class TPartItemEntity { + + @EmbeddedId + private TPartItemEntityId id; + + @NotNull + @Column(name = "part_item_order", nullable = false) + private Short partItemOrder; + + @Size(max = 128) + @NotNull + @Column(name = "part_item_title", nullable = false, length = 128) + private String partItemTitle; + + @NotNull + @Convert(converter = ChartTypeConverter.class) + @Column(name = "chart_type", nullable = false, length = 32) + private ChartType chartType; + + @NotNull + @Lob + @Column(name = "part_item_comment", nullable = false) + private String partItemComment; + + +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemSubEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemSubEntity.java new file mode 100644 index 0000000..c5a87dc --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TPartItemSubEntity.java @@ -0,0 +1,28 @@ +package com.kri.epolicy.dash.back.persistence.entity; + +import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemSubEntityId; +import jakarta.persistence.Column; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +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_sub") +public class TPartItemSubEntity { + + @EmbeddedId + private TPartItemSubEntityId id; + + @Size(max = 128) + @NotNull + @Column(name = "part_item_sub_title", nullable = false, length = 128) + private String partItemSubTitle; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSurveyEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSurveyEntity.java new file mode 100644 index 0000000..0bbc80f --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSurveyEntity.java @@ -0,0 +1,37 @@ +package com.kri.epolicy.dash.back.persistence.entity; + +import com.kri.epolicy.dash.back.persistence.entity.id.TSurveyEntityId; +import jakarta.persistence.Column; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +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_survey") +public class TSurveyEntity { + + @EmbeddedId + private TSurveyEntityId id; + + @NotNull + @Column(name = "survey_order", nullable = false) + private Short surveyOrder; + + @Size(max = 128) + @NotNull + @Column(name = "survey_title", nullable = false, length = 128) + private String surveyTitle; + + @Size(max = 32) + @NotNull + @Column(name = "survey_alias", nullable = false, length = 32) + private String surveyAlias; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSurveyItemEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSurveyItemEntity.java new file mode 100644 index 0000000..cf87089 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSurveyItemEntity.java @@ -0,0 +1,47 @@ +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.Lob; +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_survey_item") +public class TSurveyItemEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "survey_item_idx", nullable = false, updatable = false) + private Integer id; + + @NotNull + @Column(name = "wave_cd", nullable = false) + private Short waveCd; + + @NotNull + @Column(name = "survey_cd", nullable = false) + private Short surveyCd; + + @NotNull + @Column(name = "survey_item_order", nullable = false) + private Short surveyItemOrder; + + @Size(max = 128) + @NotNull + @Column(name = "survey_item_title", nullable = false, length = 128) + private String surveyItemTitle; + + @NotNull + @Lob + @Column(name = "survey_item_content", nullable = false) + private String surveyItemContent; +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSysEventLogEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSysEventLogEntity.java new file mode 100644 index 0000000..3457484 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TSysEventLogEntity.java @@ -0,0 +1,82 @@ +package com.kri.epolicy.dash.back.persistence.entity; + +import com.kri.epolicy.dash.back.common.enums.SystemEventType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.time.LocalDateTime; +import java.util.Map; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +@Getter @Setter @Builder +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "t_sys_event_log") +public class TSysEventLogEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "sys_event_log_idx", nullable = false, updatable = false) + private Long id; + + @NotNull + @Column(name = "event_ty", nullable = false) + private Short eventTy; + + @Size(max = 128) + @NotNull + @Column(name = "log_title", nullable = false, length = 128) + private String logTitle; + + @NotNull + @JdbcTypeCode(SqlTypes.JSON) + @Column(name = "log_content", nullable = false) + private Map logContent; + + @Size(max = 16) + @NotNull + @Column(name = "ip", nullable = false, length = 16) + private String ip; + + @Size(max = 32) + @NotNull + @Column(name = "reg_user", nullable = false, length = 32, updatable = false) + private String regUser; + + @NotNull + @ColumnDefault("CURRENT_TIMESTAMP") + @Column(name = "reg_dt", nullable = false, updatable = false) + private LocalDateTime regDt; + + public static TSysEventLogEntity of( + SystemEventType eventType, + String title, + Map logContent, + String clientIp, + String regId, + LocalDateTime regDt + ) { + return TSysEventLogEntity.builder() + .eventTy(eventType.getCode()) + .logTitle(title) + .logContent(logContent) + .ip(clientIp) + .regUser(regId) + .regDt(regDt) + .build(); + } +} + diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TUserEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TUserEntity.java new file mode 100644 index 0000000..3dc8290 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TUserEntity.java @@ -0,0 +1,73 @@ +package com.kri.epolicy.dash.back.persistence.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.time.Instant; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_user") +public class TUserEntity { + + @Id + @Size(max = 32) + @Column(name = "user_id", nullable = false, length = 32) + private String userId; + + @Size(max = 64) + @NotNull + @Column(name = "user_pw", nullable = false, length = 64) + private String userPw; + + @Size(max = 32) + @NotNull + @Column(name = "user_name", nullable = false, length = 32) + private String userName; + + @Size(max = 32) + @NotNull + @Column(name = "user_cmpn", nullable = false, length = 32) + private String userCmpn; + + @Size(max = 32) + @NotNull + @Column(name = "user_team", nullable = false, length = 32) + private String userTeam; + + @NotNull + @Column(name = "user_role", nullable = false) + private Integer userRole; + + @NotNull + @Lob + @Column(name = "memo", nullable = false) + private String memo; + + @Size(max = 32) + @NotNull + @Column(name = "reg_user", nullable = false, length = 32) + private String regUser; + + @NotNull + @ColumnDefault("CURRENT_TIMESTAMP") + @Column(name = "reg_dt", nullable = false) + private Instant regDt; + + @Size(max = 32) + @Column(name = "mod_user", length = 32) + private String modUser; + + @Column(name = "mod_dt") + private Instant modDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TWaveEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TWaveEntity.java new file mode 100644 index 0000000..19b7d93 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TWaveEntity.java @@ -0,0 +1,40 @@ +package com.kri.epolicy.dash.back.persistence.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Entity +@Table(name = "t_wave") +public class TWaveEntity { + + @Id + @Column(name = "wave_cd", nullable = false) + private Short id; + + @NotNull + @Column(name = "year", nullable = false) + private Short year; + + @NotNull + @Column(name = "wave", nullable = false) + private Short wave; + + @Size(max = 32) + @NotNull + @Column(name = "label", nullable = false, length = 32) + private String label; + + @NotNull + @Column(name = "is_open", nullable = false) + private Boolean isOpen; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TWaveInfoEntity.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TWaveInfoEntity.java new file mode 100644 index 0000000..fd99e3d --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/TWaveInfoEntity.java @@ -0,0 +1,45 @@ +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.Lob; +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_wave_info") +public class TWaveInfoEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "wave_info_idx", nullable = false, updatable = false) + private Integer id; + + @NotNull + @Column(name = "wave_cd", nullable = false) + private Short waveCd; + + @NotNull + @Column(name = "wave_info_order", nullable = false) + private Short waveInfoOrder; + + @Size(max = 128) + @NotNull + @Column(name = "wave_info_title", nullable = false, length = 128) + private String waveInfoTitle; + + @NotNull + @Lob + @Column(name = "wave_info_content", nullable = false) + private String waveInfoContent; + + +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartEntityId.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartEntityId.java new file mode 100644 index 0000000..e0051a8 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartEntityId.java @@ -0,0 +1,29 @@ +package com.kri.epolicy.dash.back.persistence.entity.id; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.validation.constraints.NotNull; +import java.io.Serial; +import java.io.Serializable; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@Embeddable +public class TPartEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = -7363909224374172180L; + @NotNull + @Column(name = "wave_cd", nullable = false) + private Short waveCd; + + @NotNull + @Column(name = "part_cd", nullable = false) + private Short partCd; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartItemEntityId.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartItemEntityId.java new file mode 100644 index 0000000..f2194ff --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartItemEntityId.java @@ -0,0 +1,33 @@ +package com.kri.epolicy.dash.back.persistence.entity.id; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.validation.constraints.NotNull; +import java.io.Serial; +import java.io.Serializable; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@Embeddable +public class TPartItemEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = 6976667477724981830L; + @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; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartItemSubEntityId.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartItemSubEntityId.java new file mode 100644 index 0000000..83e1c7a --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TPartItemSubEntityId.java @@ -0,0 +1,37 @@ +package com.kri.epolicy.dash.back.persistence.entity.id; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.validation.constraints.NotNull; +import java.io.Serial; +import java.io.Serializable; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@Embeddable +public class TPartItemSubEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = -4801875494665947942L; + @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; + + @NotNull + @Column(name = "part_item_sub_cd", nullable = false) + private Short partItemSubCd; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TSurveyEntityId.java b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TSurveyEntityId.java new file mode 100644 index 0000000..5c300bc --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/entity/id/TSurveyEntityId.java @@ -0,0 +1,29 @@ +package com.kri.epolicy.dash.back.persistence.entity.id; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.validation.constraints.NotNull; +import java.io.Serial; +import java.io.Serializable; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@EqualsAndHashCode +@Embeddable +public class TSurveyEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = -5862749272106811476L; + @NotNull + @Column(name = "wave_cd", nullable = false) + private Short waveCd; + + @NotNull + @Column(name = "survey_cd", nullable = false) + private Short surveyCd; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/FileRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/FileRepository.java new file mode 100644 index 0000000..af33e36 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/FileRepository.java @@ -0,0 +1,13 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TFileEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; +import java.util.Optional; + +public interface FileRepository extends JpaRepository { + + List findByWaveCdOrderByFileOrderAsc(Short waveCd); + + Optional findFirstByWaveCdAndFileName(Short waveCd, String fileName); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemBaseRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemBaseRepository.java new file mode 100644 index 0000000..59ec459 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemBaseRepository.java @@ -0,0 +1,13 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TPartItemBaseEntity; +import java.util.Collection; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PartItemBaseRepository extends JpaRepository { + + List findByWaveCdAndPartCd(Short waveCd, Short partCd); + + List findByWaveCdIn(Collection waveCodes); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemDataRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemDataRepository.java new file mode 100644 index 0000000..7f77fcc --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemDataRepository.java @@ -0,0 +1,16 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TPartItemDataEntity; +import java.util.Collection; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PartItemDataRepository extends JpaRepository { + + List findByWaveCdAndPartCdOrderByPartItemDataOrderAsc( + Short waveCd, + Short partCd + ); + + List findByWaveCdIn(Collection waveCodes); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemRepository.java new file mode 100644 index 0000000..16a3817 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemRepository.java @@ -0,0 +1,17 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TPartItemEntity; +import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemEntityId; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + +public interface PartItemRepository + extends JpaRepository { + + List findByIdWaveCdOrderByPartItemOrderAsc(Short waveCd); + + List findByIdWaveCdAndIdPartCdOrderByPartItemOrderAsc( + Short waveCd, + Short partCd + ); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemSubRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemSubRepository.java new file mode 100644 index 0000000..ef9213e --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartItemSubRepository.java @@ -0,0 +1,15 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TPartItemSubEntity; +import com.kri.epolicy.dash.back.persistence.entity.id.TPartItemSubEntityId; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + +public interface PartItemSubRepository + extends JpaRepository { + + List findByIdWaveCdAndIdPartCdOrderByIdPartItemCdAscIdPartItemSubCdAsc( + Short waveCd, + Short partCd + ); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartRepository.java new file mode 100644 index 0000000..7282fda --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/PartRepository.java @@ -0,0 +1,11 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TPartEntity; +import com.kri.epolicy.dash.back.persistence.entity.id.TPartEntityId; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + +public interface PartRepository extends JpaRepository { + + List findByIdWaveCdOrderByPartOrderAsc(Short waveCd); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SurveyItemRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SurveyItemRepository.java new file mode 100644 index 0000000..6187618 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SurveyItemRepository.java @@ -0,0 +1,14 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TSurveyItemEntity; +import java.util.Collection; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SurveyItemRepository + extends JpaRepository { + + List findByWaveCdOrderBySurveyItemOrderAsc(Short waveCd); + + List findByWaveCdIn(Collection waveCodes); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SurveyRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SurveyRepository.java new file mode 100644 index 0000000..1ee3a54 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SurveyRepository.java @@ -0,0 +1,11 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TSurveyEntity; +import com.kri.epolicy.dash.back.persistence.entity.id.TSurveyEntityId; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + +public interface SurveyRepository extends JpaRepository { + + List findByIdWaveCdOrderBySurveyOrderAsc(Short waveCd); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SysEventLogRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SysEventLogRepository.java new file mode 100644 index 0000000..b1f2b79 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/SysEventLogRepository.java @@ -0,0 +1,7 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TSysEventLogEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SysEventLogRepository extends JpaRepository { +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/UserRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/UserRepository.java new file mode 100644 index 0000000..7b71d61 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/UserRepository.java @@ -0,0 +1,9 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TUserEntity; +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + Optional findByUserIdAndUserPw(String userId, String userPw); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/WaveInfoRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/WaveInfoRepository.java new file mode 100644 index 0000000..4304c15 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/WaveInfoRepository.java @@ -0,0 +1,13 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TWaveInfoEntity; +import java.util.Collection; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface WaveInfoRepository extends JpaRepository { + + List findByWaveCdOrderByWaveInfoOrderAsc(Short waveCd); + + List findByWaveCdIn(Collection waveCodes); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/persistence/repository/WaveRepository.java b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/WaveRepository.java new file mode 100644 index 0000000..193ad34 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/persistence/repository/WaveRepository.java @@ -0,0 +1,10 @@ +package com.kri.epolicy.dash.back.persistence.repository; + +import com.kri.epolicy.dash.back.persistence.entity.TWaveEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + +public interface WaveRepository extends JpaRepository { + + List findAllByOrderByYearDescWaveDesc(); +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/AuthService.java b/src/main/java/com/kri/epolicy/dash/back/service/AuthService.java new file mode 100644 index 0000000..c9534ee --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/AuthService.java @@ -0,0 +1,35 @@ +package com.kri.epolicy.dash.back.service; + +import com.kri.common.feature.auth.dto.JwtUserClaimsDto; +import com.kri.common.feature.auth.jwt.JwtService; + +import com.kri.epolicy.dash.back.dto.auth.LoginRequestDto; +import com.kri.epolicy.dash.back.dto.auth.LoginResponseDto; +import com.kri.epolicy.dash.back.dto.auth.UserDto; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class AuthService { + + private final JwtService jwtService; + private final UserService userService; + + public LoginResponseDto tryLogin(LoginRequestDto req) { + UserDto user = userService.getUserWithLoginRequest(req); + + JwtUserClaimsDto claims = JwtUserClaimsDto.builder() + .userId(user.getUserId()) + .userCmpn(user.getUserCmpn()) + .userName(user.getUserName()) + .userTeam(user.getUserTeam()) + .userRole(user.getUserRole()) + .build(); + + String accessToken = jwtService.generateAccessToken(claims); + + return LoginResponseDto.from(accessToken, user); + } + +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/ExcelImportService.java b/src/main/java/com/kri/epolicy/dash/back/service/ExcelImportService.java new file mode 100644 index 0000000..0a82f3f --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/ExcelImportService.java @@ -0,0 +1,259 @@ +package com.kri.epolicy.dash.back.service; + +import com.kri.epolicy.dash.back.dto.request.ExcelData; +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.TPartItemBaseEntity; +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.TPartItemSubEntity; +import com.kri.epolicy.dash.back.persistence.entity.TSurveyEntity; +import com.kri.epolicy.dash.back.persistence.entity.TSurveyItemEntity; +import com.kri.epolicy.dash.back.persistence.entity.TWaveEntity; +import com.kri.epolicy.dash.back.persistence.entity.TWaveInfoEntity; +import com.kri.epolicy.dash.back.persistence.entity.id.TPartEntityId; +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.TSurveyEntityId; +import com.kri.epolicy.dash.back.persistence.repository.PartItemBaseRepository; +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.Map; +import java.util.Set; +import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +@Service +@RequiredArgsConstructor +public class ExcelImportService { + + private final ExcelImportValidator excelImportValidator; + 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 PartItemDataRepository partItemDataRepository; + + @Transactional + public ExcelImportResponse importWorkbook(MultipartFile file) { + ExcelData data = excelImportValidator.validateAndConvert(file); + Set waveCodes = data.waves().stream() + .map(ExcelData.WaveRow::waveCd) + .collect(Collectors.toSet()); + Map waveInfoIds = waveInfoRepository.findByWaveCdIn(waveCodes) + .stream().collect(Collectors.toMap( + entity -> new WaveInfoKey(entity.getWaveCd(), entity.getWaveInfoOrder()), + TWaveInfoEntity::getId, + firstValue())); + Map surveyItemIds = surveyItemRepository + .findByWaveCdIn(waveCodes).stream().collect(Collectors.toMap( + entity -> new SurveyItemKey( + entity.getWaveCd(), entity.getSurveyCd(), entity.getSurveyItemOrder()), + TSurveyItemEntity::getId, + firstValue())); + Map 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 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 -> { + TWaveEntity entity = new TWaveEntity(); + entity.setId(row.waveCd()); + entity.setYear(row.year()); + entity.setWave(row.wave()); + entity.setLabel(row.label()); + entity.setIsOpen(row.isOpen()); + return entity; + }).toList()); + + waveInfoRepository.saveAll(data.waveInfos().stream().map(row -> { + TWaveInfoEntity entity = new TWaveInfoEntity(); + entity.setId(waveInfoIds.get(new WaveInfoKey(row.waveCd(), row.waveInfoOrder()))); + entity.setWaveCd(row.waveCd()); + entity.setWaveInfoOrder(row.waveInfoOrder()); + entity.setWaveInfoTitle(row.waveInfoTitle()); + entity.setWaveInfoContent(row.waveInfoContent()); + return entity; + }).toList()); + + surveyRepository.saveAll(data.surveys().stream().map(row -> { + TSurveyEntity entity = new TSurveyEntity(); + entity.setId(surveyId(row.waveCd(), row.surveyCd())); + entity.setSurveyOrder(row.surveyOrder()); + entity.setSurveyTitle(row.surveyTitle()); + entity.setSurveyAlias(row.surveyAlias()); + return entity; + }).toList()); + + surveyItemRepository.saveAll(data.surveyItems().stream().map(row -> { + TSurveyItemEntity entity = new TSurveyItemEntity(); + entity.setId(surveyItemIds.get( + new SurveyItemKey(row.waveCd(), row.surveyCd(), row.surveyItemOrder()))); + entity.setWaveCd(row.waveCd()); + entity.setSurveyCd(row.surveyCd()); + entity.setSurveyItemOrder(row.surveyItemOrder()); + entity.setSurveyItemTitle(row.surveyItemTitle()); + entity.setSurveyItemContent(row.surveyItemContent()); + return entity; + }).toList()); + + partRepository.saveAll(data.parts().stream().map(row -> { + TPartEntity entity = new TPartEntity(); + entity.setId(partId(row.waveCd(), row.partCd())); + entity.setPartOrder(row.partOrder()); + entity.setPartTitle(row.partTitle()); + return entity; + }).toList()); + + partItemRepository.saveAll(data.partItems().stream().map(row -> { + TPartItemEntity entity = new TPartItemEntity(); + entity.setId(partItemId(row.waveCd(), row.partCd(), row.partItemCd())); + entity.setPartItemOrder(row.partItemOrder()); + entity.setPartItemTitle(row.partItemTitle()); + entity.setChartType(row.chartType()); + entity.setPartItemComment(row.partItemComment()); + return entity; + }).toList()); + + partItemSubRepository.saveAll(data.partItemSubs().stream().map(row -> { + TPartItemSubEntity entity = new TPartItemSubEntity(); + entity.setId(partItemSubId( + row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd())); + entity.setPartItemSubTitle(row.partItemSubTitle()); + return entity; + }).toList()); + + partItemBaseRepository.saveAll(data.partItemBases().stream().map(row -> { + 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.setPartCd(row.partCd()); + entity.setPartItemCd(row.partItemCd()); + entity.setSurveyCd(row.surveyCd()); + entity.setPartItemSubCd(row.partItemSubCd()); + entity.setBaseCount(row.baseCount()); + entity.setBasePreText(row.basePreText()); + entity.setBasePostText(row.basePostText()); + return entity; + }).toList()); + + partItemDataRepository.saveAll(data.partItemData().stream().map(row -> { + 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.setPartCd(row.partCd()); + entity.setPartItemCd(row.partItemCd()); + entity.setSurveyCd(row.surveyCd()); + entity.setPartItemSubCd(row.partItemSubCd()); + entity.setPartItemDataOrder(row.partItemDataOrder()); + entity.setPartItemDataLabel(row.partItemDataLabel()); + entity.setPartItemDataValue(row.partItemDataValue()); + entity.setIsChartVisible(row.isChartVisible()); + return entity; + }).toList()); + + return new ExcelImportResponse( + data.waves().size(), + data.waveInfos().size(), + data.surveys().size(), + data.surveyItems().size(), + data.parts().size(), + data.partItems().size(), + data.partItemSubs().size(), + data.partItemBases().size(), + data.partItemData().size() + ); + } + + private TSurveyEntityId surveyId(Short waveCd, Short surveyCd) { + TSurveyEntityId id = new TSurveyEntityId(); + id.setWaveCd(waveCd); + id.setSurveyCd(surveyCd); + return id; + } + + private TPartEntityId partId(Short waveCd, Short partCd) { + TPartEntityId id = new TPartEntityId(); + id.setWaveCd(waveCd); + id.setPartCd(partCd); + return id; + } + + private TPartItemEntityId partItemId(Short waveCd, Short partCd, Short partItemCd) { + TPartItemEntityId id = new TPartItemEntityId(); + id.setWaveCd(waveCd); + id.setPartCd(partCd); + id.setPartItemCd(partItemCd); + return id; + } + + private TPartItemSubEntityId partItemSubId( + Short waveCd, + Short partCd, + Short partItemCd, + Short partItemSubCd + ) { + TPartItemSubEntityId id = new TPartItemSubEntityId(); + id.setWaveCd(waveCd); + id.setPartCd(partCd); + id.setPartItemCd(partItemCd); + id.setPartItemSubCd(partItemSubCd); + return id; + } + + private java.util.function.BinaryOperator 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 + ) { + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/ExcelImportValidator.java b/src/main/java/com/kri/epolicy/dash/back/service/ExcelImportValidator.java new file mode 100644 index 0000000..d42b14d --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/ExcelImportValidator.java @@ -0,0 +1,653 @@ +package com.kri.epolicy.dash.back.service; + +import com.kri.common.feature.excel.ExcelColumn; +import com.kri.common.feature.excel.ExcelMapper; +import com.kri.common.feature.web.BusinessException; +import com.kri.epolicy.dash.back.common.enums.ChartType; +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.PartItemBaseRow; +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.PartItemSubRow; +import com.kri.epolicy.dash.back.dto.request.ExcelData.PartRow; +import com.kri.epolicy.dash.back.dto.request.ExcelData.SurveyItemRow; +import com.kri.epolicy.dash.back.dto.request.ExcelData.SurveyRow; +import com.kri.epolicy.dash.back.dto.request.ExcelData.WaveInfoRow; +import com.kri.epolicy.dash.back.dto.request.ExcelData.WaveRow; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import org.apache.poi.ss.usermodel.DataFormatter; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +@Component +public class ExcelImportValidator { + + private static final int HEADER_ROW_NUMBER = 1; + + public ExcelData validateAndConvert(MultipartFile file) { + validateFile(file); + try (InputStream inputStream = file.getInputStream(); + Workbook workbook = WorkbookFactory.create(inputStream)) { + ExcelData data = new ExcelData( + readRows(workbook, ExcelTemplateRows.WAVE_SHEET, ExcelTemplateRows.Wave.class, + row -> allBlank(row.getWaveCd(), row.getYear(), row.getWave(), row.getLabel(), + row.getIsOpen()), this::toWaveRow), + readRows(workbook, ExcelTemplateRows.WAVE_INFO_SHEET, ExcelTemplateRows.WaveInfo.class, + row -> allBlank(row.getWaveCd(), row.getWaveInfoOrder(), row.getWaveInfoTitle(), + row.getWaveInfoContent()), this::toWaveInfoRow), + readRows(workbook, ExcelTemplateRows.SURVEY_SHEET, ExcelTemplateRows.Survey.class, + row -> allBlank(row.getWaveCd(), row.getSurveyCd(), row.getSurveyOrder(), + row.getSurveyTitle(), row.getSurveyAlias()), this::toSurveyRow), + readRows(workbook, ExcelTemplateRows.SURVEY_ITEM_SHEET, + ExcelTemplateRows.SurveyItem.class, + row -> allBlank(row.getWaveCd(), row.getSurveyCd(), row.getSurveyItemOrder(), + row.getSurveyItemTitle(), row.getSurveyItemContent()), this::toSurveyItemRow), + readRows(workbook, ExcelTemplateRows.PART_SHEET, ExcelTemplateRows.Part.class, + row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartOrder(), + row.getPartTitle()), this::toPartRow), + readRows(workbook, ExcelTemplateRows.PART_ITEM_SHEET, ExcelTemplateRows.PartItem.class, + row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(), + row.getPartItemOrder(), row.getPartItemTitle(), row.getChartType(), + row.getPartItemComment()), this::toPartItemRow), + readRows(workbook, ExcelTemplateRows.PART_ITEM_SUB_SHEET, + ExcelTemplateRows.PartItemSub.class, + row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(), + row.getPartItemSubCd(), row.getPartItemSubTitle()), this::toPartItemSubRow), + readRows(workbook, ExcelTemplateRows.PART_ITEM_BASE_SHEET, + ExcelTemplateRows.PartItemBase.class, + row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(), + row.getSurveyCd(), row.getPartItemSubCd(), row.getBaseCount(), + row.getBasePreText(), row.getBasePostText()), this::toPartItemBaseRow), + readRows(workbook, ExcelTemplateRows.PART_ITEM_DATA_SHEET, + ExcelTemplateRows.PartItemData.class, + row -> allBlank(row.getWaveCd(), row.getPartCd(), row.getPartItemCd(), + row.getSurveyCd(), row.getPartItemSubCd(), row.getPartItemDataOrder(), + row.getPartItemDataLabel(), row.getPartItemDataValue(), + row.getIsChartVisible()), this::toPartItemDataRow) + ); + if (data.waves().isEmpty()) { + throw sheetError(ExcelTemplateRows.WAVE_SHEET, + "한 개 이상의 Wave 데이터가 필요합니다."); + } + validateRelationships(data); + return data; + } catch (BusinessException exception) { + throw exception; + } catch (IOException | RuntimeException exception) { + BusinessException businessException = findBusinessException(exception); + if (businessException != null) { + throw businessException; + } + throw BusinessException.validationError( + "EXCEL_IMPORT_FAILED", "Excel 파일을 읽을 수 없습니다."); + } + } + + private List readRows( + Workbook workbook, + String sheetName, + Class rowType, + Predicate emptyRow, + BiFunction converter + ) { + validateHeaders(workbook, sheetName, rowType); + List sourceRows = ExcelMapper.readFromWorkbook( + workbook, rowType, sheetName, HEADER_ROW_NUMBER); + List result = new ArrayList<>(); + for (int index = 0; index < sourceRows.size(); index++) { + T row = sourceRows.get(index); + if (!emptyRow.test(row)) { + result.add(converter.apply(row, new RowContext(sheetName, index + 2))); + } + } + return List.copyOf(result); + } + + private void validateHeaders(Workbook workbook, String sheetName, Class rowType) { + Sheet sheet = workbook.getSheet(sheetName); + if (sheet == null) { + throw sheetError(sheetName, "필수 시트가 없습니다."); + } + Row headerRow = sheet.getRow(HEADER_ROW_NUMBER - 1); + if (headerRow == null) { + throw sheetError(sheetName, "헤더 행이 없습니다."); + } + DataFormatter formatter = new DataFormatter(); + List actualHeaders = new ArrayList<>(); + for (int column = 0; column < headerRow.getLastCellNum(); column++) { + actualHeaders.add(formatter.formatCellValue(headerRow.getCell(column))); + } + Set uniqueHeaders = new HashSet<>(); + for (String actualHeader : actualHeaders) { + String header = actualHeader == null ? "" : actualHeader.trim(); + if (!uniqueHeaders.add(header)) { + throw sheetError(sheetName, "중복된 헤더가 있습니다: " + header); + } + } + List expectedHeaders = expectedHeaders(rowType); + if (!actualHeaders.equals(expectedHeaders)) { + throw sheetError(sheetName, + "헤더가 올바르지 않습니다. 예상 헤더: " + String.join(", ", expectedHeaders)); + } + } + + private List expectedHeaders(Class rowType) { + return Arrays.stream(rowType.getDeclaredFields()) + .map(field -> new AnnotatedField(field, field.getAnnotation(ExcelColumn.class))) + .filter(field -> field.column() != null) + .sorted(Comparator.comparingInt(field -> field.column().order())) + .map(field -> field.column().header()) + .toList(); + } + + private WaveRow toWaveRow(ExcelTemplateRows.Wave row, RowContext context) { + return new WaveRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getYear(), "year", context), + requiredShort(row.getWave(), "wave", context), + requiredString(row.getLabel(), "label", 32, context), + requiredBoolean(row.getIsOpen(), "is_open", context) + ); + } + + private WaveInfoRow toWaveInfoRow(ExcelTemplateRows.WaveInfo row, RowContext context) { + return new WaveInfoRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getWaveInfoOrder(), "wave_info_order", context), + requiredString(row.getWaveInfoTitle(), "wave_info_title", 128, context), + requiredString(row.getWaveInfoContent(), "wave_info_content", null, context) + ); + } + + private SurveyRow toSurveyRow(ExcelTemplateRows.Survey row, RowContext context) { + return new SurveyRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getSurveyCd(), "survey_cd", context), + requiredShort(row.getSurveyOrder(), "survey_order", context), + requiredString(row.getSurveyTitle(), "survey_title", 128, context), + requiredString(row.getSurveyAlias(), "survey_alias", 32, context) + ); + } + + private SurveyItemRow toSurveyItemRow( + ExcelTemplateRows.SurveyItem row, + RowContext context + ) { + return new SurveyItemRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getSurveyCd(), "survey_cd", context), + requiredShort(row.getSurveyItemOrder(), "survey_item_order", context), + requiredString(row.getSurveyItemTitle(), "survey_item_title", 128, context), + requiredString(row.getSurveyItemContent(), "survey_item_content", null, context) + ); + } + + private PartRow toPartRow(ExcelTemplateRows.Part row, RowContext context) { + return new PartRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getPartCd(), "part_cd", context), + requiredShort(row.getPartOrder(), "part_order", context), + requiredString(row.getPartTitle(), "part_title", 128, context) + ); + } + + private PartItemRow toPartItemRow(ExcelTemplateRows.PartItem row, RowContext context) { + return new PartItemRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getPartCd(), "part_cd", context), + requiredShort(row.getPartItemCd(), "part_item_cd", context), + requiredShort(row.getPartItemOrder(), "part_item_order", context), + requiredString(row.getPartItemTitle(), "part_item_title", 128, context), + requiredChartType(row.getChartType(), "chart_type", context), + Objects.requireNonNullElse( + optionalString(row.getPartItemComment(), "part_item_comment", null, context), "") + ); + } + + private PartItemSubRow toPartItemSubRow( + ExcelTemplateRows.PartItemSub row, + RowContext context + ) { + return new PartItemSubRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getPartCd(), "part_cd", context), + requiredShort(row.getPartItemCd(), "part_item_cd", context), + requiredShort(row.getPartItemSubCd(), "part_item_sub_cd", context), + requiredString(row.getPartItemSubTitle(), "part_item_sub_title", 128, context) + ); + } + + private PartItemBaseRow toPartItemBaseRow( + ExcelTemplateRows.PartItemBase row, + RowContext context + ) { + return new PartItemBaseRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getPartCd(), "part_cd", context), + requiredShort(row.getPartItemCd(), "part_item_cd", context), + requiredShort(row.getSurveyCd(), "survey_cd", context), + optionalShort(row.getPartItemSubCd(), "part_item_sub_cd", context), + requiredInteger(row.getBaseCount(), "base_count", context), + optionalString(row.getBasePreText(), "base_pre_text", 128, context), + optionalString(row.getBasePostText(), "base_post_text", 128, context) + ); + } + + private PartItemDataRow toPartItemDataRow( + ExcelTemplateRows.PartItemData row, + RowContext context + ) { + return new PartItemDataRow( + requiredShort(row.getWaveCd(), "wave_cd", context), + requiredShort(row.getPartCd(), "part_cd", context), + requiredShort(row.getPartItemCd(), "part_item_cd", context), + requiredShort(row.getSurveyCd(), "survey_cd", context), + optionalShort(row.getPartItemSubCd(), "part_item_sub_cd", context), + requiredShort(row.getPartItemDataOrder(), "part_item_data_order", context), + requiredString(row.getPartItemDataLabel(), "part_item_data_label", 128, context), + requiredDecimal(row.getPartItemDataValue(), "part_item_data_value", context), + requiredBoolean(row.getIsChartVisible(), "is_chart_visible", context) + ); + } + + private void validateRelationships(ExcelData data) { + Set waveKeys = uniqueKeys( + data.waves(), WaveRow::waveCd, ExcelTemplateRows.WAVE_SHEET); + uniqueKeys(data.waveInfos(), + row -> new WaveInfoKey(row.waveCd(), row.waveInfoOrder()), + ExcelTemplateRows.WAVE_INFO_SHEET); + Set surveyKeys = uniqueKeys(data.surveys(), + row -> new SurveyKey(row.waveCd(), row.surveyCd()), ExcelTemplateRows.SURVEY_SHEET); + uniqueKeys(data.surveyItems(), + row -> new SurveyItemKey(row.waveCd(), row.surveyCd(), row.surveyItemOrder()), + ExcelTemplateRows.SURVEY_ITEM_SHEET); + Set partKeys = uniqueKeys(data.parts(), + row -> new PartKey(row.waveCd(), row.partCd()), ExcelTemplateRows.PART_SHEET); + Set itemKeys = uniqueKeys(data.partItems(), + row -> new ItemKey(row.waveCd(), row.partCd(), row.partItemCd()), + ExcelTemplateRows.PART_ITEM_SHEET); + Set subKeys = uniqueKeys(data.partItemSubs(), + row -> new SubKey(row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd()), + ExcelTemplateRows.PART_ITEM_SUB_SHEET); + + requireParents(data.waveInfos(), WaveInfoRow::waveCd, waveKeys, + ExcelTemplateRows.WAVE_INFO_SHEET, "wave_cd"); + requireParents(data.surveys(), SurveyRow::waveCd, waveKeys, + ExcelTemplateRows.SURVEY_SHEET, "wave_cd"); + requireParents(data.surveyItems(), + row -> new SurveyKey(row.waveCd(), row.surveyCd()), surveyKeys, + ExcelTemplateRows.SURVEY_ITEM_SHEET, "wave_cd, survey_cd"); + requireParents(data.parts(), PartRow::waveCd, waveKeys, + ExcelTemplateRows.PART_SHEET, "wave_cd"); + requireParents(data.partItems(), + row -> new PartKey(row.waveCd(), row.partCd()), partKeys, + ExcelTemplateRows.PART_ITEM_SHEET, "wave_cd, part_cd"); + requireParents(data.partItemSubs(), + row -> new ItemKey(row.waveCd(), row.partCd(), row.partItemCd()), itemKeys, + ExcelTemplateRows.PART_ITEM_SUB_SHEET, "wave_cd, part_cd, part_item_cd"); + + Set itemsWithSubs = data.partItemSubs().stream() + .map(row -> new ItemKey(row.waveCd(), row.partCd(), row.partItemCd())) + .collect(Collectors.toSet()); + for (PartItemBaseRow row : data.partItemBases()) { + validateResultRelationship(row.waveCd(), row.partCd(), row.partItemCd(), row.surveyCd(), + row.partItemSubCd(), itemKeys, surveyKeys, subKeys, itemsWithSubs, + ExcelTemplateRows.PART_ITEM_BASE_SHEET); + } + for (PartItemDataRow row : data.partItemData()) { + validateResultRelationship(row.waveCd(), row.partCd(), row.partItemCd(), row.surveyCd(), + row.partItemSubCd(), itemKeys, surveyKeys, subKeys, itemsWithSubs, + ExcelTemplateRows.PART_ITEM_DATA_SHEET); + } + validateResultBases(data.partItemBases(), data.partItemData()); + validateCategoryConsistency(data.partItemData()); + } + + private void validateResultBases(List bases, List data) { + Set baseKeys = uniqueKeys(bases, + row -> new ResultSeriesKey( + row.waveCd(), row.partCd(), row.partItemCd(), row.surveyCd(), row.partItemSubCd()), + ExcelTemplateRows.PART_ITEM_BASE_SHEET); + for (PartItemDataRow row : data) { + ResultSeriesKey key = new ResultSeriesKey( + row.waveCd(), row.partCd(), row.partItemCd(), row.surveyCd(), row.partItemSubCd()); + if (!baseKeys.contains(key)) { + throw relationshipError(ExcelTemplateRows.PART_ITEM_DATA_SHEET, + "결과 데이터에 대응하는 Base가 없습니다: " + key); + } + } + } + + private void validateCategoryConsistency(List rows) { + uniqueKeys(rows, + row -> new ResultCategoryKey( + row.waveCd(), row.partCd(), row.partItemCd(), row.surveyCd(), + row.partItemSubCd(), row.partItemDataOrder()), + ExcelTemplateRows.PART_ITEM_DATA_SHEET); + Map>> grouped = rows.stream() + .collect(Collectors.groupingBy( + row -> new ResultGroupKey( + row.waveCd(), row.partCd(), row.partItemCd(), row.partItemSubCd()), + Collectors.groupingBy( + PartItemDataRow::surveyCd, + Collectors.mapping( + row -> new CategoryKey( + row.partItemDataOrder(), row.partItemDataLabel(), row.isChartVisible()), + Collectors.toList())))); + + for (Map.Entry>> group : grouped.entrySet()) { + List expected = null; + for (List categories : group.getValue().values()) { + categories.sort(Comparator.comparing(CategoryKey::order)); + if (expected == null) { + expected = List.copyOf(categories); + } else if (!Objects.equals(expected, categories)) { + throw relationshipError(ExcelTemplateRows.PART_ITEM_DATA_SHEET, + "조사대상별 항목명, 표시 순서 및 차트 노출 여부가 일치하지 않습니다: " + + group.getKey()); + } + } + } + } + + private void validateResultRelationship( + Short waveCd, + Short partCd, + Short partItemCd, + Short surveyCd, + Short partItemSubCd, + Set itemKeys, + Set surveyKeys, + Set subKeys, + Set itemsWithSubs, + String sheetName + ) { + ItemKey itemKey = new ItemKey(waveCd, partCd, partItemCd); + if (!itemKeys.contains(itemKey)) { + throw relationshipError(sheetName, "존재하지 않는 문항을 참조합니다: " + itemKey); + } + if (!surveyKeys.contains(new SurveyKey(waveCd, surveyCd))) { + throw relationshipError(sheetName, + "동일 Wave에 존재하지 않는 조사대상을 참조합니다: " + surveyCd); + } + if (itemsWithSubs.contains(itemKey)) { + if (partItemSubCd == null) { + throw relationshipError(sheetName, + "Sub가 있는 문항의 part_item_sub_cd는 필수입니다: " + itemKey); + } + if (!subKeys.contains(new SubKey(waveCd, partCd, partItemCd, partItemSubCd))) { + throw relationshipError(sheetName, "존재하지 않는 Sub를 참조합니다: " + partItemSubCd); + } + } else if (partItemSubCd != null) { + throw relationshipError(sheetName, + "일반 문항의 part_item_sub_cd는 NULL이어야 합니다: " + itemKey); + } + } + + private Set uniqueKeys( + List rows, + Function keyExtractor, + String sheetName + ) { + Set keys = new LinkedHashSet<>(); + for (T row : rows) { + K key = keyExtractor.apply(row); + if (!keys.add(key)) { + throw relationshipError(sheetName, "중복된 논리 식별자가 있습니다: " + key); + } + } + return keys; + } + + private void requireParents( + List rows, + Function parentKeyExtractor, + Set parentKeys, + String sheetName, + String columns + ) { + for (T row : rows) { + K key = parentKeyExtractor.apply(row); + if (!parentKeys.contains(key)) { + throw relationshipError(sheetName, + "Excel 안에 부모 데이터가 없습니다 (" + columns + "): " + key); + } + } + } + + private void validateFile(MultipartFile file) { + if (file == null || file.isEmpty()) { + throw invalidFile("업로드할 XLSX 파일이 비어 있습니다."); + } + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null + || !originalFilename.toLowerCase(Locale.ROOT).endsWith(".xlsx")) { + throw invalidFile("XLSX 파일만 업로드할 수 있습니다."); + } + } + + private boolean allBlank(String... values) { + return Arrays.stream(values).allMatch(value -> value == null || value.isBlank()); + } + + private String requiredString( + String rawValue, + String column, + Integer maxLength, + RowContext context + ) { + String value = requiredRaw(rawValue, column, context); + validateLength(value, column, maxLength, context); + return value; + } + + private String optionalString( + String rawValue, + String column, + Integer maxLength, + RowContext context + ) { + String value = normalized(rawValue); + if (value != null) { + validateLength(value, column, maxLength, context); + } + return value; + } + + private void validateLength( + String value, + String column, + Integer maxLength, + RowContext context + ) { + if (maxLength != null && value.length() > maxLength) { + throw cellError(context, column, "최대 길이는 " + maxLength + "자입니다."); + } + } + + private Short requiredShort(String rawValue, String column, RowContext context) { + String value = requiredRaw(rawValue, column, context); + try { + return Short.valueOf(value); + } catch (NumberFormatException exception) { + throw cellError(context, column, "SMALLINT 범위의 정수여야 합니다."); + } + } + + private Short optionalShort(String rawValue, String column, RowContext context) { + String value = normalized(rawValue); + if (value == null) { + return null; + } + try { + return Short.valueOf(value); + } catch (NumberFormatException exception) { + throw cellError(context, column, "SMALLINT 범위의 정수여야 합니다."); + } + } + + private Integer requiredInteger(String rawValue, String column, RowContext context) { + String value = requiredRaw(rawValue, column, context); + try { + return Integer.valueOf(value); + } catch (NumberFormatException exception) { + throw cellError(context, column, "정수여야 합니다."); + } + } + + private BigDecimal requiredDecimal(String rawValue, String column, RowContext context) { + String value = requiredRaw(rawValue, column, context); + try { + BigDecimal rounded = new BigDecimal(value).setScale(10, RoundingMode.HALF_UP); + if (rounded.precision() > 14) { + throw cellError(context, column, + "소수점 10자리 반올림 후 DECIMAL(14,10) 범위를 벗어났습니다."); + } + return rounded; + } catch (NumberFormatException exception) { + throw cellError(context, column, "숫자여야 합니다."); + } + } + + private Boolean requiredBoolean(String rawValue, String column, RowContext context) { + String value = requiredRaw(rawValue, column, context).toLowerCase(Locale.ROOT); + return switch (value) { + case "1" -> true; + case "0" -> false; + default -> throw cellError(context, column, "1 또는 0이어야 합니다."); + }; + } + + private ChartType requiredChartType(String rawValue, String column, RowContext context) { + String label = requiredRaw(rawValue, column, context); + try { + return ChartType.fromLabel(label); + } catch (IllegalArgumentException exception) { + throw cellError(context, column, "지원하는 label은 bar입니다."); + } + } + + private String requiredRaw(String rawValue, String column, RowContext context) { + String value = normalized(rawValue); + if (value == null) { + throw cellError(context, column, "필수 값입니다."); + } + return value; + } + + private String normalized(String value) { + if (value == null || value.isBlank()) { + return null; + } + return value.trim(); + } + + private BusinessException findBusinessException(Throwable throwable) { + Throwable current = throwable; + while (current != null) { + if (current instanceof BusinessException businessException) { + return businessException; + } + current = current.getCause(); + } + return null; + } + + private BusinessException invalidFile(String message) { + return BusinessException.validationError("INVALID_EXCEL_FILE", message); + } + + private BusinessException sheetError(String sheetName, String message) { + return BusinessException.validationError("INVALID_EXCEL_SHEET", message) + .with("sheet", sheetName); + } + + private BusinessException relationshipError(String sheetName, String message) { + return BusinessException.validationError("INVALID_EXCEL_RELATIONSHIP", message) + .with("sheet", sheetName); + } + + private BusinessException cellError(RowContext context, String column, String message) { + return BusinessException.validationError("INVALID_EXCEL_CELL", message) + .with("sheet", context.sheetName()) + .with("row", context.rowNumber()) + .with("column", column); + } + + private record AnnotatedField(Field field, ExcelColumn column) { + } + + private record RowContext(String sheetName, int rowNumber) { + } + + private record WaveInfoKey(Short waveCd, Short order) { + } + + private record SurveyKey(Short waveCd, Short surveyCd) { + } + + private record SurveyItemKey(Short waveCd, Short surveyCd, Short order) { + } + + private record PartKey(Short waveCd, Short partCd) { + } + + private record ItemKey(Short waveCd, Short partCd, Short partItemCd) { + } + + private record SubKey(Short waveCd, Short partCd, Short partItemCd, Short partItemSubCd) { + } + + private record ResultGroupKey( + Short waveCd, + Short partCd, + Short partItemCd, + Short partItemSubCd + ) { + } + + 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 + ) { + } + + private record CategoryKey(Short order, String label, Boolean chartVisible) { + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/ExcelTemplateService.java b/src/main/java/com/kri/epolicy/dash/back/service/ExcelTemplateService.java new file mode 100644 index 0000000..b87d49d --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/ExcelTemplateService.java @@ -0,0 +1,51 @@ +package com.kri.epolicy.dash.back.service; + +import com.kri.common.feature.excel.ExcelMapper; +import com.kri.common.feature.web.BusinessException; +import com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows; +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_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_SUB_SHEET; +import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.PART_SHEET; +import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.SURVEY_ITEM_SHEET; +import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.SURVEY_SHEET; +import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.WAVE_INFO_SHEET; +import static com.kri.epolicy.dash.back.dto.excel.ExcelTemplateRows.WAVE_SHEET; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; +import org.apache.poi.ss.usermodel.Workbook; +import org.springframework.stereotype.Service; + +@Service +public class ExcelTemplateService { + + public static final String EXCEL_CONTENT_TYPE = + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + public static final String TEMPLATE_FILENAME = "epolicy-data-template.xlsx"; + + public byte[] createTemplate() { + try (Workbook workbook = ExcelMapper.writeToWorkbook( + List.of(), ExcelTemplateRows.Wave.class, WAVE_SHEET); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + append(workbook, WAVE_INFO_SHEET, ExcelTemplateRows.WaveInfo.class); + append(workbook, SURVEY_SHEET, ExcelTemplateRows.Survey.class); + append(workbook, SURVEY_ITEM_SHEET, ExcelTemplateRows.SurveyItem.class); + append(workbook, PART_SHEET, ExcelTemplateRows.Part.class); + append(workbook, PART_ITEM_SHEET, ExcelTemplateRows.PartItem.class); + append(workbook, PART_ITEM_SUB_SHEET, ExcelTemplateRows.PartItemSub.class); + append(workbook, PART_ITEM_BASE_SHEET, ExcelTemplateRows.PartItemBase.class); + append(workbook, PART_ITEM_DATA_SHEET, ExcelTemplateRows.PartItemData.class); + workbook.write(outputStream); + return outputStream.toByteArray(); + } catch (IOException | RuntimeException exception) { + throw BusinessException.internalError( + "EXCEL_TEMPLATE_EXPORT_FAILED", "Excel 양식 파일을 생성할 수 없습니다."); + } + } + + private void append(Workbook workbook, String sheetName, Class rowType) { + ExcelMapper.appendSheetToWorkbook(workbook, List.of(), rowType, sheetName, 1); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/ReferenceFileStorageService.java b/src/main/java/com/kri/epolicy/dash/back/service/ReferenceFileStorageService.java new file mode 100644 index 0000000..4f5175b --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/ReferenceFileStorageService.java @@ -0,0 +1,261 @@ +package com.kri.epolicy.dash.back.service; + +import com.kri.common.feature.web.BusinessException; +import com.kri.epolicy.dash.back.config.FileStorageProperties; +import com.kri.epolicy.dash.back.dto.response.ReferenceFileUploadResponse; +import com.kri.epolicy.dash.back.persistence.entity.TFileEntity; +import com.kri.epolicy.dash.back.persistence.repository.FileRepository; +import com.kri.epolicy.dash.back.persistence.repository.WaveRepository; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Locale; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.multipart.MultipartFile; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ReferenceFileStorageService { + + private static final String REFERENCES_DIRECTORY = "References"; + private static final int MAX_FILENAME_LENGTH = 64; + private static final int MAX_FILE_TITLE_LENGTH = 128; + private static final int MAX_FILE_TYPE_LENGTH = 16; + + private final FileStorageProperties fileStorageProperties; + private final FileRepository fileRepository; + private final WaveRepository waveRepository; + + @Transactional + public ReferenceFileUploadResponse store( + Short waveCd, + String fileTitle, + Short fileOrder, + MultipartFile file + ) { + validateRequest(waveCd, fileTitle, fileOrder, file); + if (!waveRepository.existsById(waveCd)) { + throw BusinessException.validationError( + "WAVE_NOT_FOUND", "존재하지 않는 waveCd입니다.").with("waveCd", waveCd); + } + + String normalizedTitle = fileTitle.trim(); + String originalFilename = validateFilename(file.getOriginalFilename()); + String fileType = extractFileType(originalFilename); + Path baseDirectory = Path.of(fileStorageProperties.getBaseDir()).toAbsolutePath().normalize(); + Path targetDirectory = baseDirectory + .resolve(REFERENCES_DIRECTORY) + .resolve(waveCd.toString()) + .normalize(); + Path target = targetDirectory.resolve(originalFilename).normalize(); + if (!target.startsWith(targetDirectory) || !targetDirectory.startsWith(baseDirectory)) { + throw invalidFilename("허용되지 않는 파일 경로입니다."); + } + + Path stagedFile = stageFile(targetDirectory, file); + try { + TFileEntity entity = fileRepository.findFirstByWaveCdAndFileName(waveCd, originalFilename) + .orElseGet(TFileEntity::new); + entity.setWaveCd(waveCd); + entity.setFileOrder(fileOrder); + entity.setFileTitle(normalizedTitle); + entity.setFileType(fileType); + entity.setFileName(originalFilename); + TFileEntity saved = fileRepository.saveAndFlush(entity); + + replaceFileWithRollbackProtection(stagedFile, target); + stagedFile = null; + + String relativePath = REFERENCES_DIRECTORY + "/" + waveCd + "/" + originalFilename; + return new ReferenceFileUploadResponse( + saved.getId(), + waveCd, + fileOrder, + normalizedTitle, + fileType, + originalFilename, + file.getSize(), + relativePath + ); + } finally { + deleteQuietly(stagedFile, "임시 업로드 파일을 삭제하지 못했습니다."); + } + } + + private void validateRequest( + Short waveCd, + String fileTitle, + Short fileOrder, + MultipartFile file + ) { + if (waveCd == null || waveCd <= 0) { + throw BusinessException.validationError( + "INVALID_WAVE_CD", "waveCd는 1 이상의 값이어야 합니다."); + } + if (fileTitle == null || fileTitle.isBlank()) { + throw BusinessException.validationError( + "INVALID_FILE_TITLE", "fileTitle은 필수 값입니다."); + } + if (fileTitle.trim().length() > MAX_FILE_TITLE_LENGTH) { + throw BusinessException.validationError( + "INVALID_FILE_TITLE", "fileTitle은 128자 이하여야 합니다."); + } + if (fileOrder == null || fileOrder <= 0) { + throw BusinessException.validationError( + "INVALID_FILE_ORDER", "fileOrder는 1 이상의 값이어야 합니다."); + } + if (file == null || file.isEmpty()) { + throw BusinessException.validationError( + "EMPTY_REFERENCE_FILE", "업로드할 파일이 비어 있습니다."); + } + } + + private String validateFilename(String originalFilename) { + if (originalFilename == null || originalFilename.isBlank()) { + throw invalidFilename("원본 파일명이 필요합니다."); + } + if (originalFilename.length() > MAX_FILENAME_LENGTH) { + throw invalidFilename("원본 파일명은 64자 이하여야 합니다."); + } + if (originalFilename.indexOf('\0') >= 0 + || originalFilename.contains("/") + || originalFilename.contains("\\") + || originalFilename.matches(".*[<>:\"|?*].*") + || originalFilename.endsWith(".") + || originalFilename.endsWith(" ") + || originalFilename.equals(".") + || originalFilename.equals("..") + || !Path.of(originalFilename).getFileName().toString().equals(originalFilename)) { + throw invalidFilename("허용되지 않는 파일명입니다."); + } + return originalFilename; + } + + private String extractFileType(String filename) { + int separator = filename.lastIndexOf('.'); + if (separator <= 0 || separator == filename.length() - 1) { + throw BusinessException.validationError( + "INVALID_REFERENCE_FILE_TYPE", "확장자가 있는 파일만 업로드할 수 있습니다."); + } + String fileType = filename.substring(separator + 1).toLowerCase(Locale.ROOT); + if (fileType.length() > MAX_FILE_TYPE_LENGTH) { + throw BusinessException.validationError( + "INVALID_REFERENCE_FILE_TYPE", "파일 확장자는 16자 이하여야 합니다."); + } + return fileType; + } + + private Path stageFile(Path targetDirectory, MultipartFile file) { + Path stagedFile = null; + try { + Files.createDirectories(targetDirectory); + stagedFile = Files.createTempFile(targetDirectory, ".upload-", ".tmp"); + try (InputStream inputStream = file.getInputStream()) { + Files.copy(inputStream, stagedFile, StandardCopyOption.REPLACE_EXISTING); + } + return stagedFile; + } catch (IOException exception) { + deleteQuietly(stagedFile, "임시 업로드 파일을 삭제하지 못했습니다."); + throw storageError(); + } + } + + private void replaceFileWithRollbackProtection(Path stagedFile, Path target) { + boolean targetExisted = Files.exists(target); + Path backupFile = null; + try { + if (targetExisted) { + Path pendingBackup = Files.createTempFile(target.getParent(), ".backup-", ".tmp"); + try { + Files.copy(target, pendingBackup, + StandardCopyOption.REPLACE_EXISTING, + StandardCopyOption.COPY_ATTRIBUTES); + backupFile = pendingBackup; + } catch (IOException exception) { + deleteQuietly(pendingBackup, "완성되지 않은 파일 백업을 삭제하지 못했습니다."); + throw exception; + } + } + moveReplacing(stagedFile, target); + registerFileSynchronization(target, backupFile, targetExisted); + } catch (IOException | RuntimeException exception) { + restoreFile(target, backupFile, targetExisted); + throw storageError(); + } + } + + private void registerFileSynchronization( + Path target, + Path backupFile, + boolean targetExisted + ) { + if (!TransactionSynchronizationManager.isSynchronizationActive()) { + restoreFile(target, backupFile, targetExisted); + throw BusinessException.internalError( + "REFERENCE_FILE_TRANSACTION_REQUIRED", "파일 저장 트랜잭션을 시작할 수 없습니다."); + } + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + if (status == STATUS_COMMITTED) { + deleteQuietly(backupFile, "파일 백업을 삭제하지 못했습니다."); + return; + } + restoreFile(target, backupFile, targetExisted); + } + }); + } + + private void restoreFile(Path target, Path backupFile, boolean targetExisted) { + try { + if (targetExisted && backupFile != null && Files.exists(backupFile)) { + moveReplacing(backupFile, target); + } else if (!targetExisted) { + Files.deleteIfExists(target); + } + } catch (IOException exception) { + log.error("트랜잭션 롤백 중 기존 파일을 복구하지 못했습니다: {}", target, exception); + } finally { + deleteQuietly(backupFile, "파일 백업을 삭제하지 못했습니다."); + } + } + + private void moveReplacing(Path source, Path target) throws IOException { + try { + Files.move(source, target, + StandardCopyOption.ATOMIC_MOVE, + StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException exception) { + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); + } + } + + private void deleteQuietly(Path path, String failureMessage) { + if (path == null) { + return; + } + try { + Files.deleteIfExists(path); + } catch (IOException exception) { + log.warn("{} path={}", failureMessage, path, exception); + } + } + + private BusinessException invalidFilename(String message) { + return BusinessException.validationError("INVALID_REFERENCE_FILENAME", message); + } + + private BusinessException storageError() { + return BusinessException.internalError( + "REFERENCE_FILE_STORAGE_FAILED", "파일을 저장할 수 없습니다."); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/UserService.java b/src/main/java/com/kri/epolicy/dash/back/service/UserService.java new file mode 100644 index 0000000..10ccc1e --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/UserService.java @@ -0,0 +1,26 @@ +package com.kri.epolicy.dash.back.service; + +import com.kri.common.feature.web.BusinessException; +import com.kri.epolicy.dash.back.dto.auth.LoginRequestDto; +import com.kri.epolicy.dash.back.dto.auth.UserDto; +import com.kri.epolicy.dash.back.persistence.entity.TUserEntity; +import com.kri.epolicy.dash.back.persistence.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class UserService { + + private final UserRepository userRepository; + + public UserDto getUserWithLoginRequest(LoginRequestDto req){ + TUserEntity userEntity = userRepository.findByUserIdAndUserPw(req.getUserId(), req.getUserPw()) + .orElseThrow(() -> + BusinessException + .notFound("USER_NOT_FOUND", "사용자가 없습니다.") + .with("userId", req.getUserId()) + ); + return UserDto.from(userEntity); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/WaveAccessPolicy.java b/src/main/java/com/kri/epolicy/dash/back/service/WaveAccessPolicy.java new file mode 100644 index 0000000..7a2c091 --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/WaveAccessPolicy.java @@ -0,0 +1,25 @@ +package com.kri.epolicy.dash.back.service; + +import com.kri.common.feature.web.BusinessException; +import com.kri.common.feature.web.RequestUserContext; +import com.kri.epolicy.dash.back.persistence.entity.TWaveEntity; +import org.springframework.stereotype.Component; + +@Component +public class WaveAccessPolicy { + + static final int OPEN_WAVE_ONLY_ROLE = 2010; + + public boolean canAccess(TWaveEntity wave, RequestUserContext userContext) { + Integer userRole = userContext == null ? null : userContext.getUserRole(); + return Boolean.TRUE.equals(wave.getIsOpen()) + || (userRole != null && userRole < OPEN_WAVE_ONLY_ROLE); + } + + public void validate(TWaveEntity wave, RequestUserContext userContext) { + if (!canAccess(wave, userContext)) { + throw BusinessException.forbidden( + "WAVE_ACCESS_DENIED", "공개되지 않은 조사 차수에는 접근할 수 없습니다."); + } + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/WaveQueryService.java b/src/main/java/com/kri/epolicy/dash/back/service/WaveQueryService.java new file mode 100644 index 0000000..1bbdb9c --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/WaveQueryService.java @@ -0,0 +1,300 @@ +package com.kri.epolicy.dash.back.service; + +import com.kri.common.feature.web.BusinessException; +import com.kri.common.feature.web.RequestUserContext; +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.Audience; +import com.kri.epolicy.dash.back.dto.response.PartDetailResponse.Category; +import com.kri.epolicy.dash.back.dto.response.PartDetailResponse.Item; +import com.kri.epolicy.dash.back.dto.response.PartDetailResponse.ResultGroup; +import com.kri.epolicy.dash.back.dto.response.PartDetailResponse.Series; +import com.kri.epolicy.dash.back.dto.response.PartDetailResponse.SubItem; +import com.kri.epolicy.dash.back.dto.response.WaveDetailResponse; +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.TPartEntity; +import com.kri.epolicy.dash.back.persistence.entity.TPartItemBaseEntity; +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.TPartItemSubEntity; +import com.kri.epolicy.dash.back.persistence.entity.TSurveyEntity; +import com.kri.epolicy.dash.back.persistence.entity.TSurveyItemEntity; +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.repository.FileRepository; +import com.kri.epolicy.dash.back.persistence.repository.PartItemBaseRepository; +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.text.NumberFormat; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.util.UriUtils; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class WaveQueryService { + + private final WaveRepository waveRepository; + private final WaveInfoRepository waveInfoRepository; + private final SurveyRepository surveyRepository; + private final SurveyItemRepository surveyItemRepository; + private final FileRepository fileRepository; + private final PartRepository partRepository; + private final PartItemRepository partItemRepository; + private final PartItemSubRepository partItemSubRepository; + private final PartItemBaseRepository partItemBaseRepository; + private final PartItemDataRepository partItemDataRepository; + private final WaveAccessPolicy waveAccessPolicy; + private final FileStorageProperties fileStorageProperties; + + public List findWaves(RequestUserContext userContext) { + return waveRepository.findAllByOrderByYearDescWaveDesc().stream() + .map(wave -> toSummary(wave, userContext)) + .toList(); + } + + public WaveDetailResponse findWave(Short waveCd, RequestUserContext userContext) { + TWaveEntity wave = findAccessibleWave(waveCd, userContext); + List surveys = surveyRepository.findByIdWaveCdOrderBySurveyOrderAsc(waveCd); + Map> surveyItems = surveyItemRepository + .findByWaveCdOrderBySurveyItemOrderAsc(waveCd).stream() + .collect(Collectors.groupingBy( + TSurveyItemEntity::getSurveyCd, LinkedHashMap::new, Collectors.toList())); + List parts = partRepository.findByIdWaveCdOrderByPartOrderAsc(waveCd); + Map> partItems = partItemRepository + .findByIdWaveCdOrderByPartItemOrderAsc(waveCd).stream() + .collect(Collectors.groupingBy( + item -> item.getId().getPartCd(), LinkedHashMap::new, Collectors.toList())); + + return new WaveDetailResponse( + toSummary(wave, userContext), + waveInfoRepository.findByWaveCdOrderByWaveInfoOrderAsc(waveCd).stream() + .map(info -> new WaveDetailResponse.OverviewItem( + info.getWaveInfoTitle(), info.getWaveInfoContent())) + .toList(), + surveys.stream().map(survey -> new WaveDetailResponse.Survey( + survey.getId().getSurveyCd(), + survey.getSurveyTitle(), + survey.getSurveyAlias(), + surveyItems.getOrDefault(survey.getId().getSurveyCd(), List.of()).stream() + .map(item -> new WaveDetailResponse.SurveyItem( + item.getSurveyItemTitle(), item.getSurveyItemContent())) + .toList() + )).toList(), + parts.stream().map(part -> { + List items = partItems.getOrDefault(part.getId().getPartCd(), List.of()); + return new WaveDetailResponse.PartMenu( + part.getId().getPartCd(), + part.getPartTitle(), + items.size(), + items.stream().map(item -> new WaveDetailResponse.PartItemMenu( + item.getId().getPartItemCd(), item.getPartItemTitle())).toList() + ); + }).toList(), + fileRepository.findByWaveCdOrderByFileOrderAsc(waveCd).stream() + .map(file -> toFileDownload(waveCd, file)) + .toList() + ); + } + + public PartDetailResponse findPart( + Short waveCd, + Short partCd, + RequestUserContext userContext + ) { + findAccessibleWave(waveCd, userContext); + TPartEntity part = partRepository.findById(partId(waveCd, partCd)).orElseThrow(() -> + BusinessException.notFound( + "PART_NOT_FOUND", "요청한 Part를 찾을 수 없습니다.")); + + List surveys = surveyRepository.findByIdWaveCdOrderBySurveyOrderAsc(waveCd); + Map surveyByCode = surveys.stream().collect(Collectors.toMap( + survey -> survey.getId().getSurveyCd(), Function.identity(), (left, right) -> left, + LinkedHashMap::new)); + List items = partItemRepository + .findByIdWaveCdAndIdPartCdOrderByPartItemOrderAsc(waveCd, partCd); + List subs = partItemSubRepository + .findByIdWaveCdAndIdPartCdOrderByIdPartItemCdAscIdPartItemSubCdAsc(waveCd, partCd); + List bases = partItemBaseRepository.findByWaveCdAndPartCd(waveCd, partCd); + List data = partItemDataRepository + .findByWaveCdAndPartCdOrderByPartItemDataOrderAsc(waveCd, partCd); + + Map> subsByItem = subs.stream().collect(Collectors.groupingBy( + sub -> sub.getId().getPartItemCd(), LinkedHashMap::new, Collectors.toList())); + + return new PartDetailResponse( + waveCd, + partCd, + part.getPartTitle(), + items.stream().map(item -> toItem(item, surveys, surveyByCode, subsByItem, bases, data)) + .toList() + ); + } + + private Item toItem( + TPartItemEntity item, + List surveys, + Map surveyByCode, + Map> subsByItem, + List allBases, + List allData + ) { + Short itemCd = item.getId().getPartItemCd(); + List bases = allBases.stream() + .filter(base -> base.getPartItemCd().equals(itemCd)).toList(); + List data = allData.stream() + .filter(value -> value.getPartItemCd().equals(itemCd)).toList(); + List subs = subsByItem.getOrDefault(itemCd, List.of()); + List groups = new ArrayList<>(); + + if (subs.isEmpty()) { + groups.add(toResultGroup(null, bases, data, surveyByCode)); + } else { + for (TPartItemSubEntity sub : subs) { + Short subCd = sub.getId().getPartItemSubCd(); + groups.add(toResultGroup( + new SubItem(subCd, sub.getPartItemSubTitle()), + bases.stream().filter(base -> subCd.equals(base.getPartItemSubCd())).toList(), + data.stream().filter(value -> subCd.equals(value.getPartItemSubCd())).toList(), + surveyByCode)); + } + } + + Set audienceCodes = bases.stream() + .map(TPartItemBaseEntity::getSurveyCd) + .collect(Collectors.toCollection(LinkedHashSet::new)); + return new Item( + itemCd, + item.getPartItemOrder(), + item.getPartItemTitle(), + item.getChartType().getCode(), + item.getPartItemComment(), + toAudience(audienceCodes, surveys, surveyByCode), + List.copyOf(groups) + ); + } + + private ResultGroup toResultGroup( + SubItem subItem, + List bases, + List data, + Map surveyByCode + ) { + Map baseBySurvey = bases.stream().collect(Collectors.toMap( + TPartItemBaseEntity::getSurveyCd, Function.identity(), (left, right) -> left, + LinkedHashMap::new)); + Map> dataBySurvey = data.stream().collect( + Collectors.groupingBy(TPartItemDataEntity::getSurveyCd, + LinkedHashMap::new, Collectors.toList())); + List surveyCodes = dataBySurvey.keySet().stream() + .sorted(Comparator.comparing(code -> surveyByCode.get(code).getSurveyOrder())) + .toList(); + List categories = surveyCodes.isEmpty() ? List.of() + : dataBySurvey.get(surveyCodes.get(0)).stream() + .sorted(Comparator.comparing(TPartItemDataEntity::getPartItemDataOrder)) + .map(value -> new Category( + value.getPartItemDataOrder(), + value.getPartItemDataLabel(), + value.getIsChartVisible())) + .toList(); + List series = surveyCodes.stream().map(surveyCd -> { + TPartItemBaseEntity base = baseBySurvey.get(surveyCd); + TSurveyEntity survey = surveyByCode.get(surveyCd); + return new Series( + surveyCd, + survey.getSurveyAlias(), + base == null ? null : base.getBaseCount(), + base == null ? null : formatBase(base), + dataBySurvey.get(surveyCd).stream() + .sorted(Comparator.comparing(TPartItemDataEntity::getPartItemDataOrder)) + .map(TPartItemDataEntity::getPartItemDataValue) + .toList() + ); + }).toList(); + return new ResultGroup(subItem, categories, series); + } + + private Audience toAudience( + Set audienceCodes, + List surveys, + Map surveyByCode + ) { + if (!surveys.isEmpty() && audienceCodes.size() == surveys.size() + && audienceCodes.containsAll(surveyByCode.keySet())) { + return new Audience("COMMON", "공통"); + } + String label = audienceCodes.stream() + .map(surveyByCode::get) + .filter(java.util.Objects::nonNull) + .sorted(Comparator.comparing(TSurveyEntity::getSurveyOrder)) + .map(TSurveyEntity::getSurveyAlias) + .collect(Collectors.joining(", ")); + return new Audience("SURVEY", label); + } + + private String formatBase(TPartItemBaseEntity base) { + String prefix = base.getBasePreText() == null ? "" : base.getBasePreText(); + String suffix = base.getBasePostText() == null ? "" : base.getBasePostText(); + String count = NumberFormat.getIntegerInstance(Locale.KOREA).format(base.getBaseCount()); + return prefix + count + suffix; + } + + private WaveDetailResponse.FileDownload toFileDownload(Short waveCd, TFileEntity file) { + String encodedFilename = UriUtils.encodePathSegment(file.getFileName(), java.nio.charset.StandardCharsets.UTF_8); + String resourcePath = fileStorageProperties.getResourcePattern().replace("/**", ""); + if (resourcePath.endsWith("/")) { + resourcePath = resourcePath.substring(0, resourcePath.length() - 1); + } + return new WaveDetailResponse.FileDownload( + file.getId(), + file.getFileTitle(), + file.getFileType(), + file.getFileName(), + resourcePath + "/References/" + waveCd + "/" + encodedFilename + ); + } + + private TWaveEntity findAccessibleWave(Short waveCd, RequestUserContext userContext) { + TWaveEntity wave = waveRepository.findById(waveCd).orElseThrow(() -> + BusinessException.notFound("WAVE_NOT_FOUND", "요청한 조사 차수를 찾을 수 없습니다.")); + waveAccessPolicy.validate(wave, userContext); + return wave; + } + + private TPartEntityId partId(Short waveCd, Short partCd) { + TPartEntityId id = new TPartEntityId(); + id.setWaveCd(waveCd); + id.setPartCd(partCd); + return id; + } + + private WaveSummaryResponse toSummary(TWaveEntity wave, RequestUserContext userContext) { + return new WaveSummaryResponse( + wave.getId(), + wave.getYear(), + wave.getWave(), + wave.getLabel(), + wave.getIsOpen(), + waveAccessPolicy.canAccess(wave, userContext) + ); + } +} diff --git a/src/main/java/com/kri/epolicy/dash/back/service/common/SystemEventLogService.java b/src/main/java/com/kri/epolicy/dash/back/service/common/SystemEventLogService.java new file mode 100644 index 0000000..333208b --- /dev/null +++ b/src/main/java/com/kri/epolicy/dash/back/service/common/SystemEventLogService.java @@ -0,0 +1,89 @@ +package com.kri.epolicy.dash.back.service.common; + +import static com.kri.common.feature.json.JsonUtil.toMap; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.kri.epolicy.dash.back.common.enums.SystemEventType; +import com.kri.epolicy.dash.back.persistence.entity.TSysEventLogEntity; +import com.kri.epolicy.dash.back.persistence.repository.SysEventLogRepository; +import java.time.LocalDateTime; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class SystemEventLogService { + + private final ObjectMapper objectMapper; + private final SysEventLogRepository sysEventLogRepository; + + public void writeLoginLog(String userId, LocalDateTime regDt, String clientIp) { + writeSystemLog( + SystemEventType.LOGIN, + "Login", + userId, + regDt, + clientIp, + "userId", + userId + ); + } + + public void writeLogoutLog(String userId, LocalDateTime regDt, String clientIp) { + writeSystemLog( + SystemEventType.LOGOUT, + "Logout", + userId, + regDt, + clientIp, + "userId", + userId + ); + } + protected void writeSystemLog( + SystemEventType eventType, + String title, + String regId, + LocalDateTime regDt, + String clientIp, + T content + ) { + Map contentMap = toMap(objectMapper, content); + + saveLog(eventType, title, regId, regDt, clientIp, contentMap); + } + + protected void writeSystemLog( + SystemEventType eventType, + String title, + String regId, + LocalDateTime regDt, + String clientIp, + String contentKey, + T content + ) { + Map contentMap = Map.of(contentKey, content); + saveLog(eventType, title, regId, regDt, clientIp, contentMap); + } + + private void saveLog( + SystemEventType eventType, + String title, + String regId, + LocalDateTime regDt, + String clientIp, + Map contentMap + ) { + TSysEventLogEntity log = TSysEventLogEntity.of( + eventType, + title, + contentMap, + clientIp, + regId, + regDt + ); + + sysEventLogRepository.save(log); + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..1a61792 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,6 @@ +spring: + datasource: + url: jdbc:mysql://db-md87m.vpc-cdb.ntruss.com:3306/test_epolicy_dash?characterEncoding=UTF-8&rewriteBatchedStatements=true + username: pjrct_epolicy + password: epolicy#260813 + driver-class-name: com.mysql.cj.jdbc.Driver \ No newline at end of file diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml new file mode 100644 index 0000000..c287805 --- /dev/null +++ b/src/main/resources/application-local.yml @@ -0,0 +1,6 @@ +spring: + datasource: + url: jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/test_epolicy_dash?characterEncoding=UTF-8&rewriteBatchedStatements=true + username: pjrct_epolicy + password: epolicy#260813 + driver-class-name: com.mysql.cj.jdbc.Driver diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000..ec47e68 --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,6 @@ +spring: + datasource: + url: jdbc:mysql://db-md87m.vpc-cdb.ntruss.com:3306/prjct_epolicy_dash?characterEncoding=UTF-8&rewriteBatchedStatements=true + username: pjrct_epolicy + password: epolicy#260813 + driver-class-name: com.mysql.cj.jdbc.Driver \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..2a8a46b --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,63 @@ +server: + port: 6107 + forward-headers-strategy: framework + +spring: + application: + name: epolicy-dash-back + profiles: + default: local + jpa: + open-in-view: false + hibernate: + ddl-auto: none + properties: + hibernate: + jdbc: + batch_size: 1000 + order_inserts: true + order_updates: true + format_sql: true + servlet: + multipart: + max-file-size: 20MB + max-request-size: 20MB + +logging: + file: + path: ./logs + +springdoc: + writer-with-order-by-keys: true + swagger-ui: + tags-sorter: alpha + operations-sorter: method + +kri: + auth: + apikey: + enabled: false + security: + enabled: true + public-paths: + - /v3/api-docs/** + - /swagger-ui.html + - /swagger-ui/** + - /api/v1/auth/login + - /files/** + swagger: + enabled: true + title: "epolicy-dash-back API" + description: "epolicy-dash-back Spring Boot application" + version: "v1.0.0" + base-package: "com.kri.epolicy.dash.back" + allowed-ips: [] + file: + base-dir: ./upload-file + resource-pattern: /files/** + web: + enabled: true + redis: + enabled: false + scheduling: + enabled: false