commit d8504dff3806c5ad7ed558e3943a4cfc56412328 Author: kric_jspark Date: Fri Aug 21 15:16:03 2026 +0900 260821_01_FST: First Commit diff --git a/.agent/profile.yml b/.agent/profile.yml new file mode 100644 index 0000000..51fff6a --- /dev/null +++ b/.agent/profile.yml @@ -0,0 +1,21 @@ +schema_version: 1 + +project: + id: ksif-manage-back + name: "ksif-manage-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..983da3a --- /dev/null +++ b/.agent/project.md @@ -0,0 +1,128 @@ +# KSIF Manage Backend + +## 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 ksif-manage-back` and `.\scripts\agent-harness.ps1 verify --project ksif-manage-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 Rules + +### Data Sources +- Internal DB: JPA +- External survey DB: MyBatis +- No physical FK constraints. + +### Roles +- `1001`, `2001`: Admin with the same capabilities for the current scope. +- `3001`: Center +- Center users are restricted to their own `center_cd`. +- Resolve a Center user's `center_cd` from the internal user record when it is not present in the shared request-user claims. +- `center_cd = 0` is the project-wide code for the real aggregate `t_center` row named `전체`; do not synthesize this row in application code. + +### Reports +Progress: +- Calculated in real time from the external survey DB. +- Never use `t_report_final_data`. +- Backend calculates 7-point and 100-point scores. +- The backend owns the MyBatis Mapper interface, DTO contract, SQL, service call, and response assembly. The approved external survey source is fixed to `PKEY = '2605040_A'`, excludes `SURVEY_TYPE = 'TEST'`, and requires `Status = 10`. +- Use only `ReportHeaderType.CURRENT` headers. A nonblank `kon_qid` maps to `$.{prefix}.{kon_qid}`, where `prefix` is the substring before `_`, or the full value when `_` is absent. +- Header `1001` is a special composite score with no `kon_qid`; calculate it in the external survey SQL and return it through the same metric contract. +- The source variables used by the `1001` formula are assumed to be non-null values in the `1..7` range. Do not add null or range conditions to that special calculation. + +Final: +- Read pre-calculated values from `t_report_final_data`. +- Do not recalculate during normal requests. +- Admin imports final data through an Excel upload. +- Upsert only the Centers represented by uploaded rows and retain all other Centers' existing final data. +- Store `completeCount` in `t_center.center_final_sample`. +- Treat blank cells and `-` as absent values and delete the matching existing `t_report_final_data` value for that uploaded Center. +- Excel columns are `centerCd`, `completeCount`, followed by `report_header_id` values used as column headers. +- Use only `ReportHeaderType.FINAL` headers for Final responses and Excel validation. +- Validate every header ID, Center code, row shape, and value before applying the workbook atomically. + +Header hierarchy: +`report_header_group → variable_group → variable_name → report_header_label` + +- Order by `report_header_order`. +- 7-point/100-point share one logical header. +- Report endpoints are not paginated. +- The initial and currently supported report filter is optional `centerCd`; keep the request boundary extensible for future filters. +- For Progress, Admin requests with absent `centerCd` or `centerCd = 0` return the aggregate row followed by all Centers. A specific Admin `centerCd` returns only that Center. Center users receive only their own Center. +- For Final, Admin requests with absent `centerCd` or `centerCd = 0` return the aggregate row followed by all Centers. A specific Admin `centerCd` returns the aggregate row followed by that Center. Center users receive the aggregate row followed by their own Center. +- Return `headers` and `content`. Each content row contains `centerCd`, `centerName`, `targetCount`, `completeCount`, and ordered `values`. +- For the aggregate `centerCd = 0` row, calculate counts at query time instead of using the stored aggregate-row values. `targetCount` is the sum of `center_quota` across all nonzero Centers. Progress `completeCount` is the external survey query's aggregate count, while Final `completeCount` is the sum of `center_final_sample` across all nonzero Centers. +- Each value contains `headerId`, nullable `value7`, and nullable `value100`. +- Progress returns the available 7-point and 100-point values from MyBatis. Final returns `value7 = null` and the stored final value as `value100`. + +### Notice / Popup +- 0 center mappings = all Centers. +- 1+ mappings = mapped Centers only. +- Use soft delete where provided. +- Store Center-level view history separately in `t_notice_view` and `t_popup_view`; target mapping tables describe visibility only. +- Record a Notice or Popup view for the current Center without changing its target mappings. +- A viewed active Popup remains eligible for subsequent responses; view history is informational and does not suppress it. +- Popup periods are entered and stored with minute precision. Active lookup uses `start_dt <= now` and `end_dt > now - 1 minute`, so the selected start minute begins normally and the selected end minute remains active through its final second. +- Notice and Popup bodies contain Tiptap HTML. Store and return the HTML unchanged and do not add a backend HTML-sanitizer dependency for the current scope. +- Admin roles create, update, and delete Notices and Popups. Center users may read only content visible to their own Center. + +### Q&A +- Question 1 : Answer 0..1. +- On first Center-user answer view, set: + `is_view_answer`, `view_user`, `view_dt`. +- Center users may access only their own Center's questions. +- A Center may not update or delete a Question while it has an active Answer. +- Admin roles may create, update, and delete an Answer only until a Center user has viewed it. +- Once `is_view_answer = 1`, the Answer may no longer be updated or deleted. +- Use soft delete for Questions and Answers where provided. + +### Files +- Max 5 files. +- Max 5 MB each. +- Reject `.exe`. +- Separate storage locations: + `notice`, `qna-question`, `qna-answer`. + +### Pagination +- Use KriCommon `PageResponseDto` for Notice, Q&A Question, and Admin Popup lists. +- Default to `page = 0`, `size = 20`, ordered by registration date descending. +- Apply role, Center, target, and soft-delete filters in the database query before pagination. +- Their `POST .../search` bodies extend the shared page request with optional `searchKeyword` and `targetCenterCds`. Match `searchKeyword` against the row ID, title, or registration user with OR-connected contains searches. Match `targetCenterCds` with IN semantics; always include rows targeting all Centers (`0` for Q&A and no target mappings for Notice/Popup). Null or empty filters apply no additional restriction. +- Q&A Question list sorting additionally accepts virtual fields `answerDt` and `viewDt`. Sort `answerDt` by the active Answer's `reg_dt` and `viewDt` by the active Answer's `view_dt`, using a left join so Questions without an Answer or Answer view remain in the page result. +- Report endpoints do not use pagination. + +### Excel +- Do not implement backend Excel-download endpoints. +- The frontend will export the current screen query/filter result after the backend APIs are complete. +- Final Report Excel upload remains a backend Admin capability as defined in the Reports rules. + +### API Boundaries +- Authentication is already implemented and is outside the current API-development scope. +- Provide screen-oriented endpoints for Progress Report, Final Report, Notice, Q&A Question/Answer, menu exposure, and Popup management. +- Keep controllers thin and enforce role and Center access again in the service layer. +- Store registration, modification, deletion, answer-view, notice-view, and popup-view timestamps as KST `LocalDateTime` values according to the existing project convention. + +### System Event Logs +- Controllers write a system event log after each successful create, update, delete, or upload operation. +- Event codes use the hundreds digit for the major category, tens digit for the minor category, and ones digit for the action. +- Action digits are `1 = insert`, `2 = update`, `3 = delete`, and `4 = upload`. +- Major categories are `2xx = Report`, `3xx = Notice`, `4xx = Q&A`, `5xx = Popup`, and `6xx = Menu`. +- Q&A minor categories are `41x = Question` and `42x = Answer`. +- Log resource identifiers and aggregate counts; do not log HTML bodies or uploaded file contents. + +### Report Code Enums +- Manage `report_header_type` as `ReportHeaderType implements CodeEnum` with `1 = CURRENT`, `2 = FINAL`. +- Persist `ReportHeaderType` through an explicit JPA code converter so the existing `smallint` schema remains unchanged. +- `report_value_type`, `round_point`, and `kon_deny_value` have been removed from `t_report_header`. +- `report_value_type` and `round_point` have also been removed from the report API header response; `kon_deny_value` was not exposed by the API. + +### Do Not Assume +Ask before implementing undefined: +- future differences between Admin `1001` / `2001` +- report filters beyond `centerCd` +- progress-report scoring formulas and external survey SQL +- behavior that is not present in the approved API and screen contracts 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..ce7de00 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +.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/ +*.log + +### OS ### +.DS_Store +Thumbs.db diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..39410c3 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,390 @@ + + +# 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. + +# KSIF Manage Backend + +## 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 ksif-manage-back` and `.\scripts\agent-harness.ps1 verify --project ksif-manage-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 Rules + +### Data Sources +- Internal DB: JPA +- External survey DB: MyBatis +- No physical FK constraints. + +### Roles +- `1001`, `2001`: Admin with the same capabilities for the current scope. +- `3001`: Center +- Center users are restricted to their own `center_cd`. +- Resolve a Center user's `center_cd` from the internal user record when it is not present in the shared request-user claims. +- `center_cd = 0` is the project-wide code for the real aggregate `t_center` row named `전체`; do not synthesize this row in application code. + +### Reports +Progress: +- Calculated in real time from the external survey DB. +- Never use `t_report_final_data`. +- Backend calculates 7-point and 100-point scores. +- The backend owns the MyBatis Mapper interface, DTO contract, SQL, service call, and response assembly. The approved external survey source is fixed to `PKEY = '2605040_A'`, excludes `SURVEY_TYPE = 'TEST'`, and requires `Status = 10`. +- Use only `ReportHeaderType.CURRENT` headers. A nonblank `kon_qid` maps to `$.{prefix}.{kon_qid}`, where `prefix` is the substring before `_`, or the full value when `_` is absent. +- Header `1001` is a special composite score with no `kon_qid`; calculate it in the external survey SQL and return it through the same metric contract. +- The source variables used by the `1001` formula are assumed to be non-null values in the `1..7` range. Do not add null or range conditions to that special calculation. + +Final: +- Read pre-calculated values from `t_report_final_data`. +- Do not recalculate during normal requests. +- Admin imports final data through an Excel upload. +- Upsert only the Centers represented by uploaded rows and retain all other Centers' existing final data. +- Store `completeCount` in `t_center.center_final_sample`. +- Treat blank cells and `-` as absent values and delete the matching existing `t_report_final_data` value for that uploaded Center. +- Excel columns are `centerCd`, `completeCount`, followed by `report_header_id` values used as column headers. +- Use only `ReportHeaderType.FINAL` headers for Final responses and Excel validation. +- Validate every header ID, Center code, row shape, and value before applying the workbook atomically. + +Header hierarchy: +`report_header_group → variable_group → variable_name → report_header_label` + +- Order by `report_header_order`. +- 7-point/100-point share one logical header. +- Report endpoints are not paginated. +- The initial and currently supported report filter is optional `centerCd`; keep the request boundary extensible for future filters. +- For Progress, Admin requests with absent `centerCd` or `centerCd = 0` return the aggregate row followed by all Centers. A specific Admin `centerCd` returns only that Center. Center users receive only their own Center. +- For Final, Admin requests with absent `centerCd` or `centerCd = 0` return the aggregate row followed by all Centers. A specific Admin `centerCd` returns the aggregate row followed by that Center. Center users receive the aggregate row followed by their own Center. +- Return `headers` and `content`. Each content row contains `centerCd`, `centerName`, `targetCount`, `completeCount`, and ordered `values`. +- For the aggregate `centerCd = 0` row, calculate counts at query time instead of using the stored aggregate-row values. `targetCount` is the sum of `center_quota` across all nonzero Centers. Progress `completeCount` is the external survey query's aggregate count, while Final `completeCount` is the sum of `center_final_sample` across all nonzero Centers. +- Each value contains `headerId`, nullable `value7`, and nullable `value100`. +- Progress returns the available 7-point and 100-point values from MyBatis. Final returns `value7 = null` and the stored final value as `value100`. + +### Notice / Popup +- 0 center mappings = all Centers. +- 1+ mappings = mapped Centers only. +- Use soft delete where provided. +- Store Center-level view history separately in `t_notice_view` and `t_popup_view`; target mapping tables describe visibility only. +- Record a Notice or Popup view for the current Center without changing its target mappings. +- A viewed active Popup remains eligible for subsequent responses; view history is informational and does not suppress it. +- Popup periods are entered and stored with minute precision. Active lookup uses `start_dt <= now` and `end_dt > now - 1 minute`, so the selected start minute begins normally and the selected end minute remains active through its final second. +- Notice and Popup bodies contain Tiptap HTML. Store and return the HTML unchanged and do not add a backend HTML-sanitizer dependency for the current scope. +- Admin roles create, update, and delete Notices and Popups. Center users may read only content visible to their own Center. + +### Q&A +- Question 1 : Answer 0..1. +- On first Center-user answer view, set: + `is_view_answer`, `view_user`, `view_dt`. +- Center users may access only their own Center's questions. +- A Center may not update or delete a Question while it has an active Answer. +- Admin roles may create, update, and delete an Answer only until a Center user has viewed it. +- Once `is_view_answer = 1`, the Answer may no longer be updated or deleted. +- Use soft delete for Questions and Answers where provided. + +### Files +- Max 5 files. +- Max 5 MB each. +- Reject `.exe`. +- Separate storage locations: + `notice`, `qna-question`, `qna-answer`. + +### Pagination +- Use KriCommon `PageResponseDto` for Notice, Q&A Question, and Admin Popup lists. +- Default to `page = 0`, `size = 20`, ordered by registration date descending. +- Apply role, Center, target, and soft-delete filters in the database query before pagination. +- Their `POST .../search` bodies extend the shared page request with optional `searchKeyword` and `targetCenterCds`. Match `searchKeyword` against the row ID, title, or registration user with OR-connected contains searches. Match `targetCenterCds` with IN semantics; always include rows targeting all Centers (`0` for Q&A and no target mappings for Notice/Popup). Null or empty filters apply no additional restriction. +- Q&A Question list sorting additionally accepts virtual fields `answerDt` and `viewDt`. Sort `answerDt` by the active Answer's `reg_dt` and `viewDt` by the active Answer's `view_dt`, using a left join so Questions without an Answer or Answer view remain in the page result. +- Report endpoints do not use pagination. + +### Excel +- Do not implement backend Excel-download endpoints. +- The frontend will export the current screen query/filter result after the backend APIs are complete. +- Final Report Excel upload remains a backend Admin capability as defined in the Reports rules. + +### API Boundaries +- Authentication is already implemented and is outside the current API-development scope. +- Provide screen-oriented endpoints for Progress Report, Final Report, Notice, Q&A Question/Answer, menu exposure, and Popup management. +- Keep controllers thin and enforce role and Center access again in the service layer. +- Store registration, modification, deletion, answer-view, notice-view, and popup-view timestamps as KST `LocalDateTime` values according to the existing project convention. + +### System Event Logs +- Controllers write a system event log after each successful create, update, delete, or upload operation. +- Event codes use the hundreds digit for the major category, tens digit for the minor category, and ones digit for the action. +- Action digits are `1 = insert`, `2 = update`, `3 = delete`, and `4 = upload`. +- Major categories are `2xx = Report`, `3xx = Notice`, `4xx = Q&A`, `5xx = Popup`, and `6xx = Menu`. +- Q&A minor categories are `41x = Question` and `42x = Answer`. +- Log resource identifiers and aggregate counts; do not log HTML bodies or uploaded file contents. + +### Report Code Enums +- Manage `report_header_type` as `ReportHeaderType implements CodeEnum` with `1 = CURRENT`, `2 = FINAL`. +- Persist `ReportHeaderType` through an explicit JPA code converter so the existing `smallint` schema remains unchanged. +- `report_value_type`, `round_point`, and `kon_deny_value` have been removed from `t_report_header`. +- `report_value_type` and `round_point` have also been removed from the report API header response; `kon_deny_value` was not exposed by the API. + +### Do Not Assume +Ask before implementing undefined: +- future differences between Admin `1001` / `2001` +- report filters beyond `centerCd` +- progress-report scoring formulas and external survey SQL +- behavior that is not present in the approved API and screen contracts 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..e67a155 --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# ksif-manage-back + +ksif-manage-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: `ksif-manage-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..92e5cf4 --- /dev/null +++ b/build.gradle @@ -0,0 +1,107 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.5.7' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.kri.ksif.manage.back' +version = '0.0.1-SNAPSHOT' +description = 'ksif-manage-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.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' + + implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.5' + implementation 'com.microsoft.sqlserver:mssql-jdbc:13.2.1.jre11' // 버전은 환경 맞춰 조정 + + + 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.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.5' + 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/docs/종합결과 data upload.xlsx b/docs/종합결과 data upload.xlsx new file mode 100644 index 0000000..ef36d7e Binary files /dev/null and b/docs/종합결과 data upload.xlsx differ diff --git a/docs/화면 설계.pptx b/docs/화면 설계.pptx new file mode 100644 index 0000000..4b5d2d9 Binary files /dev/null and b/docs/화면 설계.pptx differ 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..7bb70cd --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'ksif-manage-back' diff --git a/src/main/java/com/kri/ksif/manage/back/KsifManageBackApplication.java b/src/main/java/com/kri/ksif/manage/back/KsifManageBackApplication.java new file mode 100644 index 0000000..c63b559 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/KsifManageBackApplication.java @@ -0,0 +1,35 @@ +package com.kri.ksif.manage.back; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; + +@Slf4j +@SpringBootApplication +@ConfigurationPropertiesScan +public class KsifManageBackApplication { + + public static void main(String[] args) { + SpringApplication.run(KsifManageBackApplication.class, args); + } + + @Bean + ApplicationRunner dsCheck(ApplicationContext ctx) { + return args -> { + String[] names = ctx.getBeanNamesForType(javax.sql.DataSource.class); + log.info("DataSource beans = {}", java.util.Arrays.toString(names)); + for (String n : names) { + Object ds = ctx.getBean(n); + log.info(" - {} = {}", n, ds.getClass().getName()); + if (ds instanceof com.zaxxer.hikari.HikariDataSource hk) { + log.info(" jdbcUrl=" + hk.getJdbcUrl()); + log.info(" driver=" + hk.getDriverClassName()); + } + } + }; + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/common/auth/AccessControlService.java b/src/main/java/com/kri/ksif/manage/back/common/auth/AccessControlService.java new file mode 100644 index 0000000..22b6b16 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/common/auth/AccessControlService.java @@ -0,0 +1,70 @@ +package com.kri.ksif.manage.back.common.auth; + +import com.kri.common.feature.web.BusinessException; +import com.kri.common.feature.web.RequestUserContext; +import com.kri.ksif.manage.back.persistence.entity.TUserEntity; +import com.kri.ksif.manage.back.persistence.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class AccessControlService { + + public static final int ADMIN_ROLE_1001 = 1001; + public static final int ADMIN_ROLE_2001 = 2001; + public static final int CENTER_ROLE = 3001; + public static final int ALL_CENTER_CD = 0; + + private final UserRepository userRepository; + + public TUserEntity requireUser(RequestUserContext context) { + if (context == null || !context.isAuthenticated() || context.getUserId() == null) { + throw BusinessException.unauthorized("AUTHENTICATION_REQUIRED", "Authentication is required."); + } + return userRepository.findByUserId(context.getUserId()) + .orElseThrow(() -> BusinessException.unauthorized( + "AUTHENTICATED_USER_NOT_FOUND", "Authenticated user was not found.")); + } + + public TUserEntity requireAdmin(RequestUserContext context) { + TUserEntity user = requireUser(context); + if (!isAdmin(user.getUserRole())) { + throw BusinessException.forbidden("ADMIN_REQUIRED", "Admin role is required."); + } + return user; + } + + public TUserEntity requireCenter(RequestUserContext context) { + TUserEntity user = requireUser(context); + if (!isCenter(user.getUserRole())) { + throw BusinessException.forbidden("CENTER_REQUIRED", "Center role is required."); + } + return user; + } + + public Integer resolveCenterFilter(TUserEntity user, Integer requestedCenterCd) { + if (isCenter(user.getUserRole())) { + if (requestedCenterCd != null + && !requestedCenterCd.equals(ALL_CENTER_CD) + && !requestedCenterCd.equals(user.getCenterCd())) { + throw BusinessException.forbidden("CENTER_ACCESS_DENIED", "Another Center is not accessible."); + } + return user.getCenterCd(); + } + if (isAdmin(user.getUserRole())) { + return requestedCenterCd == null || requestedCenterCd.equals(ALL_CENTER_CD) + ? null : requestedCenterCd; + } + throw BusinessException.forbidden("ROLE_NOT_SUPPORTED", "The user role is not supported."); + } + + public boolean isAdmin(Integer role) { + return Integer.valueOf(ADMIN_ROLE_1001).equals(role) + || Integer.valueOf(ADMIN_ROLE_2001).equals(role); + } + + public boolean isCenter(Integer role) { + return Integer.valueOf(CENTER_ROLE).equals(role); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/common/enums/ReportHeaderType.java b/src/main/java/com/kri/ksif/manage/back/common/enums/ReportHeaderType.java new file mode 100644 index 0000000..a5901ed --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/common/enums/ReportHeaderType.java @@ -0,0 +1,16 @@ +package com.kri.ksif.manage.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 ReportHeaderType implements CodeEnum { + CURRENT((short) 1), + FINAL((short) 2); + + private final Short code; +} diff --git a/src/main/java/com/kri/ksif/manage/back/common/enums/SystemEventType.java b/src/main/java/com/kri/ksif/manage/back/common/enums/SystemEventType.java new file mode 100644 index 0000000..9b9b440 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/common/enums/SystemEventType.java @@ -0,0 +1,38 @@ +package com.kri.ksif.manage.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), + + FINAL_REPORT_UPLOAD((short) 224), + + NOTICE_INSERT((short) 311), + NOTICE_UPDATE((short) 312), + NOTICE_DELETE((short) 313), + + QNA_QUESTION_INSERT((short) 411), + QNA_QUESTION_UPDATE((short) 412), + QNA_QUESTION_DELETE((short) 413), + QNA_ANSWER_INSERT((short) 421), + QNA_ANSWER_UPDATE((short) 422), + QNA_ANSWER_DELETE((short) 423), + + POPUP_INSERT((short) 511), + POPUP_UPDATE((short) 512), + POPUP_DELETE((short) 513), + + MENU_EXPOSURE_UPDATE((short) 612); + + private final Short code; +} diff --git a/src/main/java/com/kri/ksif/manage/back/common/util/StringNormalizer.java b/src/main/java/com/kri/ksif/manage/back/common/util/StringNormalizer.java new file mode 100644 index 0000000..db3c094 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/common/util/StringNormalizer.java @@ -0,0 +1,13 @@ +package com.kri.ksif.manage.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/ksif/manage/back/common/validation/package-info.java b/src/main/java/com/kri/ksif/manage/back/common/validation/package-info.java new file mode 100644 index 0000000..93c4e0e --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/common/validation/package-info.java @@ -0,0 +1,4 @@ +/** + * 프로젝트 전용 Bean Validation annotation과 validator를 배치합니다. + */ +package com.kri.ksif.manage.back.common.validation; diff --git a/src/main/java/com/kri/ksif/manage/back/common/web/ContentSearchCriteria.java b/src/main/java/com/kri/ksif/manage/back/common/web/ContentSearchCriteria.java new file mode 100644 index 0000000..7b3c47f --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/common/web/ContentSearchCriteria.java @@ -0,0 +1,43 @@ +package com.kri.ksif.manage.back.common.web; + +import com.kri.ksif.manage.back.dto.common.ContentSearchRequestDto; +import java.util.List; +import java.util.Locale; +import java.util.Objects; + +public record ContentSearchCriteria( + String searchPattern, + boolean targetFilterEnabled, + List targetCenterCds +) { + + private static final List DISABLED_TARGET_FILTER_VALUE = List.of(0); + + public static ContentSearchCriteria from(ContentSearchRequestDto request) { + String searchPattern = normalizeSearchPattern(request); + List targetCenterCds = normalizeTargetCenterCds(request); + boolean targetFilterEnabled = !targetCenterCds.isEmpty(); + return new ContentSearchCriteria( + searchPattern, + targetFilterEnabled, + targetFilterEnabled ? targetCenterCds : DISABLED_TARGET_FILTER_VALUE); + } + + private static String normalizeSearchPattern(ContentSearchRequestDto request) { + if (request == null || request.getSearchKeyword() == null + || request.getSearchKeyword().isBlank()) { + return null; + } + return "%" + request.getSearchKeyword().trim().toLowerCase(Locale.ROOT) + "%"; + } + + private static List normalizeTargetCenterCds(ContentSearchRequestDto request) { + if (request == null || request.getTargetCenterCds() == null) { + return List.of(); + } + return request.getTargetCenterCds().stream() + .filter(Objects::nonNull) + .distinct() + .toList(); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/common/web/PageRequestSupport.java b/src/main/java/com/kri/ksif/manage/back/common/web/PageRequestSupport.java new file mode 100644 index 0000000..6879d76 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/common/web/PageRequestSupport.java @@ -0,0 +1,57 @@ +package com.kri.ksif.manage.back.common.web; + +import com.kri.common.feature.web.BusinessException; +import com.kri.common.feature.web.page.PageRequestDto; +import com.kri.common.feature.web.page.Pageables; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; + +public final class PageRequestSupport { + + private static final int DEFAULT_PAGE_SIZE = 20; + private static final int MAX_PAGE_SIZE = 100; + private static final String KRI_COMMON_DEFAULT_SORT = "prjctIdx"; + private static final String DEFAULT_SORT = "regDt"; + + private PageRequestSupport() { + } + + public static Pageable latest(PageRequestDto request, Class entityType) { + PageRequestDto normalized = normalize(request); + try { + return Pageables.of(normalized, entityType); + } catch (IllegalArgumentException exception) { + throw BusinessException.validationError( + "PAGE_SORT_INVALID", "The requested sort field is not supported.") + .with("sortBy", normalized.getSortBy()); + } + } + + public static Pageable unsorted(PageRequestDto request) { + PageRequestDto normalized = normalize(request); + return PageRequest.of(normalized.getPageIndex(), normalized.getPageSize()); + } + + private static PageRequestDto normalize(PageRequestDto request) { + PageRequestDto source = request == null ? new PageRequestDto() : request; + PageRequestDto normalized = new PageRequestDto(); + normalized.setPageIndex(Math.max(source.getPageIndex(), 0)); + + int pageSize = source.getPageSize(); + if (pageSize <= 0 + || (pageSize == 10 && KRI_COMMON_DEFAULT_SORT.equals(source.getSortBy()))) { + pageSize = DEFAULT_PAGE_SIZE; + } + if (pageSize > MAX_PAGE_SIZE) { + throw BusinessException.validationError( + "PAGE_SIZE_EXCEEDED", "pageSize must be 100 or less."); + } + normalized.setPageSize(pageSize); + + String sortBy = source.getSortBy(); + normalized.setSortBy(sortBy == null || sortBy.isBlank() + || KRI_COMMON_DEFAULT_SORT.equals(sortBy) ? DEFAULT_SORT : sortBy); + normalized.setSortDir(source.getSortDir()); + return normalized; + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/config/DataSourceConfig.java b/src/main/java/com/kri/ksif/manage/back/config/DataSourceConfig.java new file mode 100644 index 0000000..9f8d0eb --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/config/DataSourceConfig.java @@ -0,0 +1,64 @@ +package com.kri.ksif.manage.back.config; + +import com.zaxxer.hikari.HikariDataSource; +import javax.sql.DataSource; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +@EnableJpaRepositories( + basePackages = "com.kri.ksif.manage.back.persistence.repository", + entityManagerFactoryRef = "mainEntityManagerFactory", + transactionManagerRef = "mainTransactionManager" +) +public class DataSourceConfig { + + @Bean + @Primary + @ConfigurationProperties(prefix = "spring.datasource") + public DataSourceProperties mainDataSourceProperties() { + return new DataSourceProperties(); + } + + @Bean(name = "mainDataSource") + @Primary + @ConfigurationProperties(prefix = "spring.datasource.hikari") + public HikariDataSource mainDataSource( + @Qualifier("mainDataSourceProperties") DataSourceProperties properties + ) { + return properties.initializeDataSourceBuilder() + .type(HikariDataSource.class) + .build(); + } + + @Bean(name = "mainEntityManagerFactory") + @Primary + public LocalContainerEntityManagerFactoryBean mainEntityManagerFactory( + EntityManagerFactoryBuilder builder, + @Qualifier("mainDataSource") DataSource dataSource + ) { + return builder + .dataSource(dataSource) + .packages("com.kri.ksif.manage.back.persistence.entity") + .persistenceUnit("main") + .build(); + } + + @Bean(name = "mainTransactionManager") + @Primary + public PlatformTransactionManager mainTransactionManager( + @Qualifier("mainEntityManagerFactory") + LocalContainerEntityManagerFactoryBean entityManagerFactory + ) { + return new JpaTransactionManager(entityManagerFactory.getObject()); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/config/FileStorageProperties.java b/src/main/java/com/kri/ksif/manage/back/config/FileStorageProperties.java new file mode 100644 index 0000000..e76b06c --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/config/FileStorageProperties.java @@ -0,0 +1,14 @@ +package com.kri.ksif.manage.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/ksif/manage/back/config/JdbcConfig.java b/src/main/java/com/kri/ksif/manage/back/config/JdbcConfig.java new file mode 100644 index 0000000..daa31ce --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/config/JdbcConfig.java @@ -0,0 +1,15 @@ +package com.kri.ksif.manage.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/ksif/manage/back/config/KonMyBatisConfig.java b/src/main/java/com/kri/ksif/manage/back/config/KonMyBatisConfig.java new file mode 100644 index 0000000..6e677f1 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/config/KonMyBatisConfig.java @@ -0,0 +1,142 @@ +package com.kri.ksif.manage.back.config; + +import com.zaxxer.hikari.HikariDataSource; +import java.util.Properties; +import javax.sql.DataSource; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.mybatis.spring.SqlSessionTemplate; +import org.mybatis.spring.annotation.MapperScan; +import org.mybatis.spring.boot.autoconfigure.MybatisProperties; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +@MapperScan( + basePackages = "com.kri.ksif.manage.back.persistence.mapper.kon", + sqlSessionTemplateRef = "konSqlSessionTemplate" +) +public class KonMyBatisConfig { + + @Bean + @ConfigurationProperties(prefix = "kon.datasource") + public DataSourceProperties konDataSourceProperties() { + return new DataSourceProperties(); + } + + @Bean(name = "konDataSource") + @ConfigurationProperties(prefix = "kon.datasource.hikari") + public HikariDataSource konDataSource( + @Qualifier("konDataSourceProperties") DataSourceProperties properties + ) { + return properties.initializeDataSourceBuilder() + .type(HikariDataSource.class) + .build(); + } + + @Bean + @ConfigurationProperties(prefix = "kon.mybatis") + public KonMybatisProperties konMybatisProperties() { + return new KonMybatisProperties(); + } + + @Bean(name = "konSqlSessionFactory") + public SqlSessionFactory konSqlSessionFactory( + @Qualifier("konDataSource") DataSource dataSource, + @Qualifier("konMybatisProperties") KonMybatisProperties properties + ) throws Exception { + SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); + factoryBean.setDataSource(dataSource); + factoryBean.setMapperLocations(resolveMapperLocations(properties.getMapperLocations())); + factoryBean.setTypeAliasesPackage(properties.getTypeAliasesPackage()); + factoryBean.setConfigurationProperties(properties.getConfigurationProperties()); + if (properties.getConfiguration() != null) { + org.apache.ibatis.session.Configuration configuration = + new org.apache.ibatis.session.Configuration(); + properties.getConfiguration().applyTo(configuration); + factoryBean.setConfiguration(configuration); + } + return factoryBean.getObject(); + } + + private Resource[] resolveMapperLocations(String[] mapperLocations) { + if (mapperLocations == null || mapperLocations.length == 0) { + return new Resource[0]; + } + + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + return java.util.Arrays.stream(mapperLocations) + .flatMap(location -> { + try { + return java.util.Arrays.stream(resolver.getResources(location)); + } catch (Exception e) { + throw new IllegalStateException("Failed to resolve MyBatis mapper location: " + location, e); + } + }) + .toArray(Resource[]::new); + } + + @Bean(name = "konSqlSessionTemplate") + public SqlSessionTemplate konSqlSessionTemplate( + @Qualifier("konSqlSessionFactory") SqlSessionFactory sqlSessionFactory + ) { + return new SqlSessionTemplate(sqlSessionFactory); + } + + @Bean(name = "konTransactionManager") + public PlatformTransactionManager konTransactionManager( + @Qualifier("konDataSource") DataSource dataSource + ) { + return new DataSourceTransactionManager(dataSource); + } + + public static class KonMybatisProperties { + + private String[] mapperLocations; + private String typeAliasesPackage; + private Properties configurationProperties; + + @NestedConfigurationProperty + private MybatisProperties.CoreConfiguration configuration; + + public String[] getMapperLocations() { + return mapperLocations; + } + + public void setMapperLocations(String[] mapperLocations) { + this.mapperLocations = mapperLocations; + } + + public String getTypeAliasesPackage() { + return typeAliasesPackage; + } + + public void setTypeAliasesPackage(String typeAliasesPackage) { + this.typeAliasesPackage = typeAliasesPackage; + } + + public Properties getConfigurationProperties() { + return configurationProperties; + } + + public void setConfigurationProperties(Properties configurationProperties) { + this.configurationProperties = configurationProperties; + } + + public MybatisProperties.CoreConfiguration getConfiguration() { + return configuration; + } + + public void setConfiguration(MybatisProperties.CoreConfiguration configuration) { + this.configuration = configuration; + } + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/config/QueryDSLConfig.java b/src/main/java/com/kri/ksif/manage/back/config/QueryDSLConfig.java new file mode 100644 index 0000000..20eec9d --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/config/QueryDSLConfig.java @@ -0,0 +1,19 @@ +package com.kri.ksif.manage.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/ksif/manage/back/controller/AuthController.java b/src/main/java/com/kri/ksif/manage/back/controller/AuthController.java new file mode 100644 index 0000000..a2b4aa5 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/controller/AuthController.java @@ -0,0 +1,53 @@ +package com.kri.ksif.manage.back.controller; + +import com.kri.common.feature.datetime.DateTimeUtil; +import com.kri.common.feature.web.RequestUserContext; + +import com.kri.ksif.manage.back.dto.auth.LoginRequestDto; +import com.kri.ksif.manage.back.dto.auth.LoginResponseDto; +import com.kri.ksif.manage.back.service.AuthService; +import com.kri.ksif.manage.back.service.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/ksif/manage/back/controller/CenterController.java b/src/main/java/com/kri/ksif/manage/back/controller/CenterController.java new file mode 100644 index 0000000..0119a24 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/controller/CenterController.java @@ -0,0 +1,23 @@ +package com.kri.ksif.manage.back.controller; + +import com.kri.common.feature.web.RequestUserContext; +import com.kri.ksif.manage.back.dto.center.CenterResponseDto; +import com.kri.ksif.manage.back.service.CenterService; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/centers") +@RequiredArgsConstructor +public class CenterController { + + private final CenterService service; + + @GetMapping + public List list(RequestUserContext context) { + return service.list(context); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/controller/MenuController.java b/src/main/java/com/kri/ksif/manage/back/controller/MenuController.java new file mode 100644 index 0000000..df3a953 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/controller/MenuController.java @@ -0,0 +1,45 @@ +package com.kri.ksif.manage.back.controller; + +import static com.kri.ksif.manage.back.common.enums.SystemEventType.MENU_EXPOSURE_UPDATE; + +import com.kri.common.feature.web.RequestUserContext; +import com.kri.ksif.manage.back.dto.menu.MenuExposureRequestDto; +import com.kri.ksif.manage.back.dto.menu.MenuResponseDto; +import com.kri.ksif.manage.back.service.MenuService; +import com.kri.ksif.manage.back.service.SystemEventLogService; +import jakarta.validation.Valid; +import java.util.List; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +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/menus") +@RequiredArgsConstructor +public class MenuController { + + private final MenuService service; + private final SystemEventLogService systemEventLogService; + + @GetMapping + public List list(RequestUserContext context) { + return service.list(context); + } + + @PutMapping("/exposure") + public List update(@Valid @RequestBody MenuExposureRequestDto request, + RequestUserContext context) { + List response = service.update(request, context); + systemEventLogService.writeEventLog( + MENU_EXPOSURE_UPDATE, + "Menu exposure updated", + context, + Map.of("updatedMenuCount", request.menus().size()) + ); + return response; + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/controller/NoticeController.java b/src/main/java/com/kri/ksif/manage/back/controller/NoticeController.java new file mode 100644 index 0000000..9e1e647 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/controller/NoticeController.java @@ -0,0 +1,96 @@ +package com.kri.ksif.manage.back.controller; + +import static com.kri.ksif.manage.back.common.enums.SystemEventType.NOTICE_DELETE; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.NOTICE_INSERT; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.NOTICE_UPDATE; + +import com.kri.common.feature.web.RequestUserContext; +import com.kri.common.feature.web.page.PageResponseDto; +import com.kri.ksif.manage.back.dto.common.ContentSearchRequestDto; +import com.kri.ksif.manage.back.dto.notice.NoticeRequestDto; +import com.kri.ksif.manage.back.dto.notice.NoticeResponseDto; +import com.kri.ksif.manage.back.service.NoticeService; +import com.kri.ksif.manage.back.service.SystemEventLogService; +import jakarta.validation.Valid; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.core.io.Resource; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping("/api/v1/notices") +@RequiredArgsConstructor +@Validated +public class NoticeController { + + private final NoticeService service; + private final SystemEventLogService systemEventLogService; + + @PostMapping(value = "/search", consumes = MediaType.APPLICATION_JSON_VALUE) + public PageResponseDto list( + @RequestBody(required = false) ContentSearchRequestDto request, + RequestUserContext context + ) { + return service.list(request, context); + } + + @GetMapping("/{noticeId}") + public NoticeResponseDto get(@PathVariable Integer noticeId, RequestUserContext context) { + return service.get(noticeId, context); + } + + @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public NoticeResponseDto create(@Valid @RequestPart("request") NoticeRequestDto request, + @RequestPart(value = "files", required = false) List files, + RequestUserContext context) { + NoticeResponseDto response = service.create(request, files, context); + systemEventLogService.writeEventLog( + NOTICE_INSERT, "Notice created", context, Map.of("noticeId", response.noticeId())); + return response; + } + + @PutMapping(value = "/{noticeId}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public NoticeResponseDto update(@PathVariable Integer noticeId, + @Valid @RequestPart("request") NoticeRequestDto request, + @RequestPart(value = "files", required = false) List files, + RequestUserContext context) { + NoticeResponseDto response = service.update(noticeId, request, files, context); + systemEventLogService.writeEventLog( + NOTICE_UPDATE, "Notice updated", context, Map.of("noticeId", noticeId)); + return response; + } + + @DeleteMapping("/{noticeId}") + public void delete(@PathVariable Integer noticeId, RequestUserContext context) { + service.delete(noticeId, context); + systemEventLogService.writeEventLog( + NOTICE_DELETE, "Notice deleted", context, Map.of("noticeId", noticeId)); + } + + @GetMapping("/{noticeId}/files/{fileId}") + public ResponseEntity download(@PathVariable Integer noticeId, + @PathVariable Integer fileId, + RequestUserContext context) { + var file = service.download(noticeId, fileId, context); + return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, + ContentDisposition.attachment().filename(file.fileName(), StandardCharsets.UTF_8).build() + .toString()) + .contentType(MediaType.APPLICATION_OCTET_STREAM).body(file.resource()); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/controller/PingController.java b/src/main/java/com/kri/ksif/manage/back/controller/PingController.java new file mode 100644 index 0000000..402ada2 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/controller/PingController.java @@ -0,0 +1,14 @@ +package com.kri.ksif.manage.back.controller; + +import java.util.Map; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class PingController { + + @GetMapping("/ping") + public Map ping() { + return Map.of("status", "ok"); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/controller/PopupController.java b/src/main/java/com/kri/ksif/manage/back/controller/PopupController.java new file mode 100644 index 0000000..198b8cb --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/controller/PopupController.java @@ -0,0 +1,61 @@ +package com.kri.ksif.manage.back.controller; + +import static com.kri.ksif.manage.back.common.enums.SystemEventType.POPUP_DELETE; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.POPUP_INSERT; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.POPUP_UPDATE; + +import com.kri.common.feature.web.RequestUserContext; +import com.kri.common.feature.web.page.PageResponseDto; +import com.kri.ksif.manage.back.dto.common.ContentSearchRequestDto; +import com.kri.ksif.manage.back.dto.popup.*; +import com.kri.ksif.manage.back.service.PopupService; +import com.kri.ksif.manage.back.service.SystemEventLogService; +import jakarta.validation.Valid; +import java.util.List; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import org.springframework.validation.annotation.Validated; + +@RestController +@RequestMapping("/api/v1/popups") +@RequiredArgsConstructor +@Validated +public class PopupController { + private final PopupService service; + private final SystemEventLogService systemEventLogService; + @PostMapping(value = "/search", consumes = "application/json") + public PageResponseDto list( + @RequestBody(required = false) ContentSearchRequestDto request, + RequestUserContext context + ) { + return service.list(request, context); + } + @GetMapping("/active") public List active(RequestUserContext context){return service.active(context);} + @GetMapping("/{popupId}") public PopupResponseDto get(@PathVariable Integer popupId,RequestUserContext context){return service.get(popupId,context);} + @PostMapping + public PopupResponseDto create(@Valid @RequestBody PopupRequestDto request, + RequestUserContext context) { + PopupResponseDto response = service.create(request, context); + systemEventLogService.writeEventLog( + POPUP_INSERT, "Popup created", context, Map.of("popupId", response.popupId())); + return response; + } + + @PutMapping("/{popupId}") + public PopupResponseDto update(@PathVariable Integer popupId, + @Valid @RequestBody PopupRequestDto request, + RequestUserContext context) { + PopupResponseDto response = service.update(popupId, request, context); + systemEventLogService.writeEventLog( + POPUP_UPDATE, "Popup updated", context, Map.of("popupId", popupId)); + return response; + } + + @DeleteMapping("/{popupId}") + public void delete(@PathVariable Integer popupId, RequestUserContext context) { + service.delete(popupId, context); + systemEventLogService.writeEventLog( + POPUP_DELETE, "Popup deleted", context, Map.of("popupId", popupId)); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/controller/QnaController.java b/src/main/java/com/kri/ksif/manage/back/controller/QnaController.java new file mode 100644 index 0000000..50746a9 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/controller/QnaController.java @@ -0,0 +1,167 @@ +package com.kri.ksif.manage.back.controller; + +import static com.kri.ksif.manage.back.common.enums.SystemEventType.QNA_ANSWER_DELETE; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.QNA_ANSWER_INSERT; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.QNA_ANSWER_UPDATE; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.QNA_QUESTION_DELETE; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.QNA_QUESTION_INSERT; +import static com.kri.ksif.manage.back.common.enums.SystemEventType.QNA_QUESTION_UPDATE; + +import com.kri.common.feature.web.RequestUserContext; +import com.kri.common.feature.web.page.PageResponseDto; +import com.kri.ksif.manage.back.dto.common.ContentSearchRequestDto; +import com.kri.ksif.manage.back.dto.qna.QnaAnswerRequestDto; +import com.kri.ksif.manage.back.dto.qna.QnaAnswerResponseDto; +import com.kri.ksif.manage.back.dto.qna.QnaQuestionRequestDto; +import com.kri.ksif.manage.back.dto.qna.QnaQuestionResponseDto; +import com.kri.ksif.manage.back.service.QnaService; +import com.kri.ksif.manage.back.service.SystemEventLogService; +import jakarta.validation.Valid; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.core.io.Resource; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +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 +@RequestMapping("/api/v1/qna-questions") +@RequiredArgsConstructor +@Validated +public class QnaController { + + private final QnaService service; + private final SystemEventLogService systemEventLogService; + + @PostMapping(value = "/search", consumes = MediaType.APPLICATION_JSON_VALUE) + public PageResponseDto list( + @RequestBody(required = false) ContentSearchRequestDto request, + RequestUserContext context + ) { + return service.list(request, context); + } + + @GetMapping("/{questionId}") + public QnaQuestionResponseDto get( + @PathVariable Integer questionId, + RequestUserContext context + ) { + return service.get(questionId, context); + } + + @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public QnaQuestionResponseDto create( + @Valid @RequestPart("request") QnaQuestionRequestDto request, + @RequestPart(value = "files", required = false) List files, + RequestUserContext context + ) { + QnaQuestionResponseDto response = service.create(request, files, context); + systemEventLogService.writeEventLog( + QNA_QUESTION_INSERT, "Q&A question created", context, + Map.of("questionId", response.questionId())); + return response; + } + + @PutMapping(value = "/{questionId}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public QnaQuestionResponseDto update( + @PathVariable Integer questionId, + @Valid @RequestPart("request") QnaQuestionRequestDto request, + @RequestPart(value = "files", required = false) List files, + RequestUserContext context + ) { + QnaQuestionResponseDto response = service.update(questionId, request, files, context); + systemEventLogService.writeEventLog( + QNA_QUESTION_UPDATE, "Q&A question updated", context, + Map.of("questionId", questionId)); + return response; + } + + @DeleteMapping("/{questionId}") + public void delete(@PathVariable Integer questionId, RequestUserContext context) { + service.deleteQuestion(questionId, context); + systemEventLogService.writeEventLog( + QNA_QUESTION_DELETE, "Q&A question deleted", context, + Map.of("questionId", questionId)); + } + + @PostMapping(value = "/{questionId}/answer", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public QnaAnswerResponseDto createAnswer( + @PathVariable Integer questionId, + @Valid @RequestPart("request") QnaAnswerRequestDto request, + @RequestPart(value = "files", required = false) List files, + RequestUserContext context + ) { + QnaAnswerResponseDto response = service.createAnswer(questionId, request, files, context); + systemEventLogService.writeEventLog( + QNA_ANSWER_INSERT, "Q&A answer created", context, + Map.of("questionId", questionId, "answerId", response.answerId())); + return response; + } + + @PutMapping(value = "/{questionId}/answer", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public QnaAnswerResponseDto updateAnswer( + @PathVariable Integer questionId, + @Valid @RequestPart("request") QnaAnswerRequestDto request, + @RequestPart(value = "files", required = false) List files, + RequestUserContext context + ) { + QnaAnswerResponseDto response = service.updateAnswer(questionId, request, files, context); + systemEventLogService.writeEventLog( + QNA_ANSWER_UPDATE, "Q&A answer updated", context, + Map.of("questionId", questionId, "answerId", response.answerId())); + return response; + } + + @DeleteMapping("/{questionId}/answer") + public void deleteAnswer(@PathVariable Integer questionId, RequestUserContext context) { + service.deleteAnswer(questionId, context); + systemEventLogService.writeEventLog( + QNA_ANSWER_DELETE, "Q&A answer deleted", context, + Map.of("questionId", questionId)); + } + + @GetMapping("/{questionId}/files/{fileId}") + public ResponseEntity questionFile( + @PathVariable Integer questionId, + @PathVariable Integer fileId, + RequestUserContext context + ) { + return response(service.downloadQuestion(questionId, fileId, context)); + } + + @GetMapping("/{questionId}/answer/files/{fileId}") + public ResponseEntity answerFile( + @PathVariable Integer questionId, + @PathVariable Integer fileId, + RequestUserContext context + ) { + return response(service.downloadAnswer(questionId, fileId, context)); + } + + private ResponseEntity response(QnaService.Download file) { + return ResponseEntity.ok() + .header( + HttpHeaders.CONTENT_DISPOSITION, + ContentDisposition.attachment() + .filename(file.fileName(), StandardCharsets.UTF_8) + .build() + .toString() + ) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .body(file.resource()); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/controller/ReportController.java b/src/main/java/com/kri/ksif/manage/back/controller/ReportController.java new file mode 100644 index 0000000..74a168c --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/controller/ReportController.java @@ -0,0 +1,63 @@ +package com.kri.ksif.manage.back.controller; + +import static com.kri.ksif.manage.back.common.enums.SystemEventType.FINAL_REPORT_UPLOAD; + +import com.kri.common.feature.web.RequestUserContext; +import com.kri.ksif.manage.back.dto.report.FinalReportImportResponseDto; +import com.kri.ksif.manage.back.dto.report.ReportResponseDto; +import com.kri.ksif.manage.back.service.ReportService; +import com.kri.ksif.manage.back.service.SystemEventLogService; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +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.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping("/api/v1/reports") +@RequiredArgsConstructor +public class ReportController { + + private final ReportService reportService; + private final SystemEventLogService systemEventLogService; + + @GetMapping("/progress") + public ReportResponseDto getProgress( + @RequestParam(required = false) Integer centerCd, + RequestUserContext context + ) { + return reportService.getProgress(centerCd, context); + } + + @GetMapping("/final") + public ReportResponseDto getFinal( + @RequestParam(required = false) Integer centerCd, + RequestUserContext context + ) { + return reportService.getFinal(centerCd, context); + } + + @PostMapping(value = "/final/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public FinalReportImportResponseDto importFinal( + @RequestPart("file") MultipartFile file, + RequestUserContext context + ) { + FinalReportImportResponseDto response = reportService.importFinal(file, context); + systemEventLogService.writeEventLog( + FINAL_REPORT_UPLOAD, + "Final report uploaded", + context, + Map.of( + "importedCenterCount", response.importedCenterCount(), + "savedValueCount", response.savedValueCount(), + "deletedValueCount", response.deletedValueCount() + ) + ); + return response; + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/auth/LoginRequestDto.java b/src/main/java/com/kri/ksif/manage/back/dto/auth/LoginRequestDto.java new file mode 100644 index 0000000..63d5408 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/auth/LoginRequestDto.java @@ -0,0 +1,17 @@ +package com.kri.ksif.manage.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/ksif/manage/back/dto/auth/LoginResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/auth/LoginResponseDto.java new file mode 100644 index 0000000..9eb34da --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/auth/LoginResponseDto.java @@ -0,0 +1,26 @@ +package com.kri.ksif.manage.back.dto.auth; + + +import com.kri.ksif.manage.back.dto.user.UserDto; +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/ksif/manage/back/dto/center/CenterResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/center/CenterResponseDto.java new file mode 100644 index 0000000..abbf410 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/center/CenterResponseDto.java @@ -0,0 +1,10 @@ +package com.kri.ksif.manage.back.dto.center; + +import com.kri.ksif.manage.back.persistence.entity.TCenterEntity; + +public record CenterResponseDto(Integer centerCd, String centerName) { + + public static CenterResponseDto from(TCenterEntity entity) { + return new CenterResponseDto(entity.getId(), entity.getCenterName()); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/common/ContentSearchRequestDto.java b/src/main/java/com/kri/ksif/manage/back/dto/common/ContentSearchRequestDto.java new file mode 100644 index 0000000..50ebb5e --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/common/ContentSearchRequestDto.java @@ -0,0 +1,14 @@ +package com.kri.ksif.manage.back.dto.common; + +import com.kri.common.feature.web.page.PageRequestDto; +import java.util.List; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class ContentSearchRequestDto extends PageRequestDto { + + private String searchKeyword; + private List targetCenterCds; +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/common/FileResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/common/FileResponseDto.java new file mode 100644 index 0000000..97b610c --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/common/FileResponseDto.java @@ -0,0 +1,4 @@ +package com.kri.ksif.manage.back.dto.common; + +public record FileResponseDto(Integer fileId, Short order, String fileName, String fileType) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/menu/MenuExposureRequestDto.java b/src/main/java/com/kri/ksif/manage/back/dto/menu/MenuExposureRequestDto.java new file mode 100644 index 0000000..bca9c20 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/menu/MenuExposureRequestDto.java @@ -0,0 +1,11 @@ +package com.kri.ksif.manage.back.dto.menu; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import java.util.List; + +public record MenuExposureRequestDto(@NotEmpty List<@Valid Item> menus) { + public record Item(@NotNull Integer menuId, @NotNull Boolean userOpen) { + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/menu/MenuResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/menu/MenuResponseDto.java new file mode 100644 index 0000000..9088bb0 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/menu/MenuResponseDto.java @@ -0,0 +1,4 @@ +package com.kri.ksif.manage.back.dto.menu; + +public record MenuResponseDto(Integer menuId, Short order, String title, String path, boolean userOpen) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/notice/NoticeRequestDto.java b/src/main/java/com/kri/ksif/manage/back/dto/notice/NoticeRequestDto.java new file mode 100644 index 0000000..d298479 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/notice/NoticeRequestDto.java @@ -0,0 +1,13 @@ +package com.kri.ksif.manage.back.dto.notice; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import java.util.List; + +public record NoticeRequestDto( + @NotBlank @Size(max = 128) String title, + @NotBlank String contentHtml, + List centerCds, + List keepFileIds +) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/notice/NoticeResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/notice/NoticeResponseDto.java new file mode 100644 index 0000000..88c32e0 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/notice/NoticeResponseDto.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.dto.notice; + +import com.kri.ksif.manage.back.dto.common.FileResponseDto; +import java.time.LocalDateTime; +import java.util.List; + +public record NoticeResponseDto( + Integer noticeId, String title, String contentHtml, List centerCds, + List files, String regUser, LocalDateTime regDt, + String modUser, LocalDateTime modDt, boolean viewed +) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/popup/PopupRequestDto.java b/src/main/java/com/kri/ksif/manage/back/dto/popup/PopupRequestDto.java new file mode 100644 index 0000000..121bfd7 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/popup/PopupRequestDto.java @@ -0,0 +1,16 @@ +package com.kri.ksif.manage.back.dto.popup; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.time.LocalDateTime; +import java.util.List; + +public record PopupRequestDto( + @NotBlank @Size(max = 128) String title, + @NotBlank String contentHtml, + @NotNull LocalDateTime startDt, + @NotNull LocalDateTime endDt, + List centerCds +) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/popup/PopupResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/popup/PopupResponseDto.java new file mode 100644 index 0000000..07bb413 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/popup/PopupResponseDto.java @@ -0,0 +1,11 @@ +package com.kri.ksif.manage.back.dto.popup; + +import java.time.LocalDateTime; +import java.util.List; + +public record PopupResponseDto( + Integer popupId, String title, String contentHtml, LocalDateTime startDt, + LocalDateTime endDt, List centerCds, String regUser, + LocalDateTime regDt, String modUser, LocalDateTime modDt, boolean viewed +) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaAnswerRequestDto.java b/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaAnswerRequestDto.java new file mode 100644 index 0000000..8b35bac --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaAnswerRequestDto.java @@ -0,0 +1,7 @@ +package com.kri.ksif.manage.back.dto.qna; + +import jakarta.validation.constraints.NotBlank; +import java.util.List; + +public record QnaAnswerRequestDto(@NotBlank String contentHtml, List keepFileIds) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaAnswerResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaAnswerResponseDto.java new file mode 100644 index 0000000..e6c833e --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaAnswerResponseDto.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.dto.qna; + +import com.kri.ksif.manage.back.dto.common.FileResponseDto; +import java.time.LocalDateTime; +import java.util.List; + +public record QnaAnswerResponseDto( + Integer answerId, String contentHtml, List files, + boolean viewed, String viewUser, LocalDateTime viewDt, + String regUser, LocalDateTime regDt, String modUser, LocalDateTime modDt +) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaQuestionRequestDto.java b/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaQuestionRequestDto.java new file mode 100644 index 0000000..ae5ffc6 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaQuestionRequestDto.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.dto.qna; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import java.util.List; + +public record QnaQuestionRequestDto( + @NotBlank @Size(max = 128) String title, + @NotBlank String contentHtml, + List keepFileIds +) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaQuestionResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaQuestionResponseDto.java new file mode 100644 index 0000000..7af361f --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/qna/QnaQuestionResponseDto.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.dto.qna; + +import com.kri.ksif.manage.back.dto.common.FileResponseDto; +import java.time.LocalDateTime; +import java.util.List; + +public record QnaQuestionResponseDto( + Integer questionId, Integer centerCd, String centerName, String title, + String contentHtml, List files, QnaAnswerResponseDto answer, + String regUser, LocalDateTime regDt, String modUser, LocalDateTime modDt +) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/report/FinalReportImportResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/report/FinalReportImportResponseDto.java new file mode 100644 index 0000000..9af97f3 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/report/FinalReportImportResponseDto.java @@ -0,0 +1,8 @@ +package com.kri.ksif.manage.back.dto.report; + +public record FinalReportImportResponseDto( + int importedCenterCount, + int savedValueCount, + long deletedValueCount +) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/report/ProgressReportHeaderParamDto.java b/src/main/java/com/kri/ksif/manage/back/dto/report/ProgressReportHeaderParamDto.java new file mode 100644 index 0000000..33167a2 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/report/ProgressReportHeaderParamDto.java @@ -0,0 +1,4 @@ +package com.kri.ksif.manage.back.dto.report; + +public record ProgressReportHeaderParamDto(Integer headerId, String jsonPath) { +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/report/ProgressReportMetricDto.java b/src/main/java/com/kri/ksif/manage/back/dto/report/ProgressReportMetricDto.java new file mode 100644 index 0000000..af12376 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/report/ProgressReportMetricDto.java @@ -0,0 +1,15 @@ +package com.kri.ksif.manage.back.dto.report; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class ProgressReportMetricDto { + + private Integer centerCd; + private Integer completeCount; + private Integer headerId; + private String value7; + private String value100; +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/report/ReportResponseDto.java b/src/main/java/com/kri/ksif/manage/back/dto/report/ReportResponseDto.java new file mode 100644 index 0000000..3cf847c --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/report/ReportResponseDto.java @@ -0,0 +1,35 @@ +package com.kri.ksif.manage.back.dto.report; + +import java.util.List; + +public record ReportResponseDto( + List
headers, + List content +) { + + public record Header( + Integer headerId, + Integer order, + String group, + String variableGroup, + String variableName, + String label + ) { + } + + public record Content( + Integer centerCd, + String centerName, + Integer targetCount, + Integer completeCount, + List values + ) { + } + + public record Value( + Integer headerId, + String value7, + String value100 + ) { + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/dto/user/UserDto.java b/src/main/java/com/kri/ksif/manage/back/dto/user/UserDto.java new file mode 100644 index 0000000..d0e6ea0 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/dto/user/UserDto.java @@ -0,0 +1,45 @@ +package com.kri.ksif.manage.back.dto.user; + +import com.kri.ksif.manage.back.persistence.entity.TUserEntity; +import io.swagger.v3.oas.annotations.media.Schema; +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; + + @Schema(description = "소속 학당") + private Integer centerCd; + + public static UserDto from(TUserEntity entity) { + return UserDto.builder() + .userId(entity.getUserId()) + .userCmpn(entity.getUserCmpn()) + .userTeam(entity.getUserTeam()) + .userName(entity.getUserName()) + .userRole(entity.getUserRole()) + .centerCd(entity.getCenterCd()) + .build(); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/converter/ReportHeaderTypeConverter.java b/src/main/java/com/kri/ksif/manage/back/persistence/converter/ReportHeaderTypeConverter.java new file mode 100644 index 0000000..3f89dbc --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/converter/ReportHeaderTypeConverter.java @@ -0,0 +1,14 @@ +package com.kri.ksif.manage.back.persistence.converter; + +import com.kri.common.feature.jpa.AbstractCodeEnumConverter; +import com.kri.ksif.manage.back.common.enums.ReportHeaderType; +import jakarta.persistence.Converter; + +@Converter +public class ReportHeaderTypeConverter + extends AbstractCodeEnumConverter { + + public ReportHeaderTypeConverter() { + super(ReportHeaderType.class); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TCenterEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TCenterEntity.java new file mode 100644 index 0000000..f98138b --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TCenterEntity.java @@ -0,0 +1,50 @@ +package com.kri.ksif.manage.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; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_center") +public class TCenterEntity { + + @Id + @Column(name = "center_cd", nullable = false) + private Integer id; + + @Size(max = 128) + @NotNull + @Column(name = "center_name", nullable = false, length = 128) + private String centerName; + + @NotNull + @Column(name = "center_area", nullable = false) + private Integer centerArea; + + @NotNull + @Column(name = "center_country", nullable = false) + private Integer centerCountry; + + @NotNull + @Column(name = "center_quota", nullable = false) + private Integer centerQuota; + + @NotNull + @Column(name = "center_final_sample", nullable = false) + private Integer centerFinalSample; + + @NotNull + @ColumnDefault("0") + @Column(name = "is_total_dummy", nullable = false) + private Boolean isTotalDummy; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TMenuEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TMenuEntity.java new file mode 100644 index 0000000..a90589e --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TMenuEntity.java @@ -0,0 +1,46 @@ +package com.kri.ksif.manage.back.persistence.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_menu") +public class TMenuEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "menu_idx", nullable = false) + private Integer id; + + @NotNull + @Column(name = "menu_order", nullable = false) + private Short menuOrder; + + @Size(max = 32) + @NotNull + @Column(name = "menu_title", nullable = false, length = 32) + private String menuTitle; + + @Size(max = 32) + @NotNull + @Column(name = "menu_path", nullable = false, length = 32) + private String menuPath; + + @NotNull + @ColumnDefault("0") + @Column(name = "is_user_open", nullable = false) + private Boolean isUserOpen; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeCenterMapEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeCenterMapEntity.java new file mode 100644 index 0000000..bcd607b --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeCenterMapEntity.java @@ -0,0 +1,19 @@ +package com.kri.ksif.manage.back.persistence.entity; + +import com.kri.ksif.manage.back.persistence.entity.id.TNoticeCenterMapEntityId; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Entity +@Table(name = "t_notice_center_map") +public class TNoticeCenterMapEntity { + + @EmbeddedId + private TNoticeCenterMapEntityId id; + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeEntity.java new file mode 100644 index 0000000..014ec95 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeEntity.java @@ -0,0 +1,68 @@ +package com.kri.ksif.manage.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 java.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_notice") +public class TNoticeEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "notice_idx", nullable = false) + private Integer id; + + @Size(max = 128) + @NotNull + @Column(name = "notice_title", nullable = false, length = 128) + private String noticeTitle; + + @NotNull + @Lob + @Column(name = "notice_content", nullable = false) + private String noticeContent; + + @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 LocalDateTime regDt; + + @Size(max = 32) + @Column(name = "mod_user", length = 32) + private String modUser; + + @Column(name = "mod_dt") + private LocalDateTime modDt; + + @NotNull + @ColumnDefault("0") + @Column(name = "is_del", nullable = false) + private Boolean isDel; + + @Size(max = 32) + @Column(name = "del_user", length = 32) + private String delUser; + + @Column(name = "del_dt") + private LocalDateTime delDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeFileEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeFileEntity.java new file mode 100644 index 0000000..d4af0d0 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeFileEntity.java @@ -0,0 +1,56 @@ +package com.kri.ksif.manage.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.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_notice_file") +public class TNoticeFileEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "notice_file_idx", nullable = false) + private Integer id; + + @NotNull + @Column(name = "notice_idx", nullable = false) + private Integer noticeIdx; + + @NotNull + @Column(name = "file_order", nullable = false) + private Short fileOrder; + + @Size(max = 16) + @NotNull + @Column(name = "file_type", nullable = false, length = 16) + private String fileType; + + @Size(max = 128) + @NotNull + @Column(name = "file_name", nullable = false, length = 128) + private String fileName; + + @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 LocalDateTime regDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeViewEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeViewEntity.java new file mode 100644 index 0000000..c3ef685 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TNoticeViewEntity.java @@ -0,0 +1,35 @@ +package com.kri.ksif.manage.back.persistence.entity; + +import com.kri.ksif.manage.back.persistence.entity.id.TNoticeViewEntityId; +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 java.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_notice_view") +public class TNoticeViewEntity { + + @EmbeddedId + private TNoticeViewEntityId id; + + @Size(max = 32) + @NotNull + @Column(name = "view_user", nullable = false, length = 32) + private String viewUser; + + @NotNull + @ColumnDefault("CURRENT_TIMESTAMP") + @Column(name = "view_dt", nullable = false) + private LocalDateTime viewDt; + + +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupCenterMapEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupCenterMapEntity.java new file mode 100644 index 0000000..244192d --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupCenterMapEntity.java @@ -0,0 +1,19 @@ +package com.kri.ksif.manage.back.persistence.entity; + +import com.kri.ksif.manage.back.persistence.entity.id.TPopupCenterMapEntityId; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Entity +@Table(name = "t_popup_center_map") +public class TPopupCenterMapEntity { + + @EmbeddedId + private TPopupCenterMapEntityId id; + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupEntity.java new file mode 100644 index 0000000..c687168 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupEntity.java @@ -0,0 +1,76 @@ +package com.kri.ksif.manage.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 java.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_popup") +public class TPopupEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "popup_idx", nullable = false) + private Integer id; + + @Size(max = 128) + @NotNull + @Column(name = "popup_title", nullable = false, length = 128) + private String popupTitle; + + @NotNull + @Lob + @Column(name = "popup_content", nullable = false) + private String popupContent; + + @NotNull + @Column(name = "start_dt", nullable = false) + private LocalDateTime startDt; + + @NotNull + @Column(name = "end_dt", nullable = false) + private LocalDateTime endDt; + + @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 LocalDateTime regDt; + + @Size(max = 32) + @Column(name = "mod_user", length = 32) + private String modUser; + + @Column(name = "mod_dt") + private LocalDateTime modDt; + + @NotNull + @ColumnDefault("0") + @Column(name = "is_del", nullable = false) + private Boolean isDel; + + @Size(max = 32) + @Column(name = "del_user", length = 32) + private String delUser; + + @Column(name = "del_dt") + private LocalDateTime delDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupViewEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupViewEntity.java new file mode 100644 index 0000000..b31c102 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TPopupViewEntity.java @@ -0,0 +1,35 @@ +package com.kri.ksif.manage.back.persistence.entity; + +import com.kri.ksif.manage.back.persistence.entity.id.TPopupViewEntityId; +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 java.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_popup_view") +public class TPopupViewEntity { + + @EmbeddedId + private TPopupViewEntityId id; + + @Size(max = 32) + @NotNull + @Column(name = "view_user", nullable = false, length = 32) + private String viewUser; + + @NotNull + @ColumnDefault("CURRENT_TIMESTAMP") + @Column(name = "view_dt", nullable = false) + private LocalDateTime viewDt; + + +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaAnswerEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaAnswerEntity.java new file mode 100644 index 0000000..3a48f88 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaAnswerEntity.java @@ -0,0 +1,79 @@ +package com.kri.ksif.manage.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 java.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_qna_answer") +public class TQnaAnswerEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "qna_answer_idx", nullable = false) + private Integer id; + + @NotNull + @Column(name = "qna_question_idx", nullable = false) + private Integer qnaQuestionIdx; + + @NotNull + @Lob + @Column(name = "answer_content", nullable = false) + private String answerContent; + + @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 LocalDateTime regDt; + + @Size(max = 32) + @Column(name = "mod_user", length = 32) + private String modUser; + + @Column(name = "mod_dt") + private LocalDateTime modDt; + + @NotNull + @ColumnDefault("0") + @Column(name = "is_del", nullable = false) + private Boolean isDel; + + @Size(max = 32) + @Column(name = "del_user", length = 32) + private String delUser; + + @Column(name = "del_dt") + private LocalDateTime delDt; + + @NotNull + @ColumnDefault("0") + @Column(name = "is_view_answer", nullable = false) + private Boolean isViewAnswer; + + @Size(max = 32) + @Column(name = "view_user", length = 32) + private String viewUser; + + @Column(name = "view_dt") + private LocalDateTime viewDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaAnswerFileEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaAnswerFileEntity.java new file mode 100644 index 0000000..6901bca --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaAnswerFileEntity.java @@ -0,0 +1,56 @@ +package com.kri.ksif.manage.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.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_qna_answer_file") +public class TQnaAnswerFileEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "qna_file_idx", nullable = false) + private Integer id; + + @NotNull + @Column(name = "qna_answer_idx", nullable = false) + private Integer qnaAnswerIdx; + + @NotNull + @Column(name = "file_order", nullable = false) + private Short fileOrder; + + @Size(max = 16) + @NotNull + @Column(name = "file_type", nullable = false, length = 16) + private String fileType; + + @Size(max = 128) + @NotNull + @Column(name = "file_name", nullable = false, length = 128) + private String fileName; + + @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 LocalDateTime regDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaQuestionEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaQuestionEntity.java new file mode 100644 index 0000000..301f174 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaQuestionEntity.java @@ -0,0 +1,72 @@ +package com.kri.ksif.manage.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 java.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_qna_question") +public class TQnaQuestionEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "qna_question_idx", nullable = false) + private Integer id; + + @NotNull + @Column(name = "center_cd", nullable = false) + private Integer centerCd; + + @Size(max = 128) + @NotNull + @Column(name = "question_title", nullable = false, length = 128) + private String questionTitle; + + @NotNull + @Lob + @Column(name = "question_content", nullable = false) + private String questionContent; + + @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 LocalDateTime regDt; + + @Size(max = 32) + @Column(name = "mod_user", length = 32) + private String modUser; + + @Column(name = "mod_dt") + private LocalDateTime modDt; + + @NotNull + @ColumnDefault("0") + @Column(name = "is_del", nullable = false) + private Boolean isDel; + + @Size(max = 32) + @Column(name = "del_user", length = 32) + private String delUser; + + @Column(name = "del_dt") + private LocalDateTime delDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaQuestionFileEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaQuestionFileEntity.java new file mode 100644 index 0000000..960c94c --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TQnaQuestionFileEntity.java @@ -0,0 +1,56 @@ +package com.kri.ksif.manage.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.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.ColumnDefault; + +@Getter +@Setter +@Entity +@Table(name = "t_qna_question_file") +public class TQnaQuestionFileEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "qna_file_idx", nullable = false) + private Integer id; + + @NotNull + @Column(name = "qna_question_idx", nullable = false) + private Integer qnaQuestionIdx; + + @NotNull + @Column(name = "file_order", nullable = false) + private Short fileOrder; + + @Size(max = 16) + @NotNull + @Column(name = "file_type", nullable = false, length = 16) + private String fileType; + + @Size(max = 128) + @NotNull + @Column(name = "file_name", nullable = false, length = 128) + private String fileName; + + @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 LocalDateTime regDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TReportFinalDataEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TReportFinalDataEntity.java new file mode 100644 index 0000000..348784f --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TReportFinalDataEntity.java @@ -0,0 +1,28 @@ +package com.kri.ksif.manage.back.persistence.entity; + +import com.kri.ksif.manage.back.persistence.entity.id.TReportFinalDataEntityId; +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_report_final_data") +public class TReportFinalDataEntity { + + @EmbeddedId + private TReportFinalDataEntityId id; + + @Size(max = 32) + @NotNull + @Column(name = "report_final_data_value", nullable = false, length = 32) + private String reportFinalDataValue; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TReportHeaderEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TReportHeaderEntity.java new file mode 100644 index 0000000..62e8884 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TReportHeaderEntity.java @@ -0,0 +1,55 @@ +package com.kri.ksif.manage.back.persistence.entity; + +import com.kri.ksif.manage.back.common.enums.ReportHeaderType; +import com.kri.ksif.manage.back.persistence.converter.ReportHeaderTypeConverter; +import jakarta.persistence.Column; +import jakarta.persistence.Convert; +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_report_header") +public class TReportHeaderEntity { + + @Id + @Column(name = "report_header_id", nullable = false) + private Integer id; + + @NotNull + @Column(name = "report_header_order", nullable = false) + private Integer reportHeaderOrder; + + @Size(max = 32) + @NotNull + @Column(name = "report_header_label", nullable = false, length = 32) + private String reportHeaderLabel; + + @NotNull + @Convert(converter = ReportHeaderTypeConverter.class) + @Column(name = "report_header_type", nullable = false) + private ReportHeaderType reportHeaderType; + + @Size(max = 32) + @Column(name = "report_header_group", length = 32) + private String reportHeaderGroup; + + @Size(max = 32) + @Column(name = "variable_group", length = 32) + private String variableGroup; + + @Size(max = 32) + @Column(name = "variable_name", length = 32) + private String variableName; + + @Size(max = 32) + @Column(name = "kon_qid", length = 32) + private String konQid; + +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TSysEventLogEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TSysEventLogEntity.java new file mode 100644 index 0000000..4be31ae --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TSysEventLogEntity.java @@ -0,0 +1,81 @@ +package com.kri.ksif.manage.back.persistence.entity; + +import com.kri.ksif.manage.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) + 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) + private String regUser; + + @NotNull + @ColumnDefault("CURRENT_TIMESTAMP") + @Column(name = "reg_dt", nullable = 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(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/TUserEntity.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TUserEntity.java new file mode 100644 index 0000000..568864b --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/TUserEntity.java @@ -0,0 +1,77 @@ +package com.kri.ksif.manage.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.LocalDateTime; +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 = 128) + @NotNull + @Column(name = "user_name", nullable = false, length = 128) + 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 + @Column(name = "center_cd", nullable = false) + private Integer centerCd; + + @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 LocalDateTime regDt; + + @Size(max = 32) + @Column(name = "mod_user", length = 32) + private String modUser; + + @Column(name = "mod_dt") + private LocalDateTime modDt; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TNoticeCenterMapEntityId.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TNoticeCenterMapEntityId.java new file mode 100644 index 0000000..e813b02 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TNoticeCenterMapEntityId.java @@ -0,0 +1,29 @@ +package com.kri.ksif.manage.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 TNoticeCenterMapEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = -6775950354640485670L; + @NotNull + @Column(name = "notice_idx", nullable = false) + private Integer noticeIdx; + + @NotNull + @Column(name = "center_cd", nullable = false) + private Integer centerCd; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TNoticeViewEntityId.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TNoticeViewEntityId.java new file mode 100644 index 0000000..de08726 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TNoticeViewEntityId.java @@ -0,0 +1,29 @@ +package com.kri.ksif.manage.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 TNoticeViewEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = -232654271490024933L; + @NotNull + @Column(name = "notice_idx", nullable = false) + private Integer noticeIdx; + + @NotNull + @Column(name = "center_cd", nullable = false) + private Integer centerCd; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TPopupCenterMapEntityId.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TPopupCenterMapEntityId.java new file mode 100644 index 0000000..3b03320 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TPopupCenterMapEntityId.java @@ -0,0 +1,29 @@ +package com.kri.ksif.manage.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 TPopupCenterMapEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = -4706893082527936486L; + @NotNull + @Column(name = "popup_idx", nullable = false) + private Integer popupIdx; + + @NotNull + @Column(name = "center_cd", nullable = false) + private Integer centerCd; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TPopupViewEntityId.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TPopupViewEntityId.java new file mode 100644 index 0000000..87d10cf --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TPopupViewEntityId.java @@ -0,0 +1,29 @@ +package com.kri.ksif.manage.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 TPopupViewEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = 3373253738627126134L; + @NotNull + @Column(name = "popup_idx", nullable = false) + private Integer popupIdx; + + @NotNull + @Column(name = "center_cd", nullable = false) + private Integer centerCd; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TReportFinalDataEntityId.java b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TReportFinalDataEntityId.java new file mode 100644 index 0000000..0fbe229 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/entity/id/TReportFinalDataEntityId.java @@ -0,0 +1,29 @@ +package com.kri.ksif.manage.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 TReportFinalDataEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = 8213501096273858156L; + @NotNull + @Column(name = "center_cd", nullable = false) + private Integer centerCd; + + @NotNull + @Column(name = "report_header_id", nullable = false) + private Integer reportHeaderId; + + +} \ No newline at end of file diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/mapper/kon/KonMapper.java b/src/main/java/com/kri/ksif/manage/back/persistence/mapper/kon/KonMapper.java new file mode 100644 index 0000000..e8a4e32 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/mapper/kon/KonMapper.java @@ -0,0 +1,17 @@ +package com.kri.ksif.manage.back.persistence.mapper.kon; + +import com.kri.ksif.manage.back.dto.report.ProgressReportMetricDto; +import com.kri.ksif.manage.back.dto.report.ProgressReportHeaderParamDto; +import java.util.List; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +@Mapper +public interface KonMapper { + + List selectProgressReport( + @Param("centerCds") List centerCds, + @Param("headerIds") List headerIds, + @Param("scoreHeaders") List scoreHeaders + ); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/CenterRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/CenterRepository.java new file mode 100644 index 0000000..5c8d5b0 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/CenterRepository.java @@ -0,0 +1,32 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TCenterEntity; +import java.util.Collection; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface CenterRepository extends JpaRepository { + + List findAllByOrderByIdAsc(); + + long countAllByIdIn(Collection ids); + + @Query(""" + select + coalesce(sum(center.centerQuota), 0) as targetCount, + coalesce(sum(center.centerFinalSample), 0) as completeCount + from TCenterEntity center + where center.id <> :aggregateCenterCd + """) + CenterCountAggregate findCountAggregate( + @Param("aggregateCenterCd") Integer aggregateCenterCd); + + interface CenterCountAggregate { + + Long getTargetCount(); + + Long getCompleteCount(); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/MenuRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/MenuRepository.java new file mode 100644 index 0000000..ead0bb9 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/MenuRepository.java @@ -0,0 +1,10 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TMenuEntity; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MenuRepository extends JpaRepository { + List findAllByOrderByMenuOrderAsc(); + List findByIsUserOpenTrueOrderByMenuOrderAsc(); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeCenterMapRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeCenterMapRepository.java new file mode 100644 index 0000000..2feaeaf --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeCenterMapRepository.java @@ -0,0 +1,13 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TNoticeCenterMapEntity; +import com.kri.ksif.manage.back.persistence.entity.id.TNoticeCenterMapEntityId; +import java.util.List; +import java.util.Collection; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface NoticeCenterMapRepository extends JpaRepository { + List findByIdNoticeIdx(Integer noticeIdx); + List findByIdNoticeIdxIn(Collection noticeIds); + long deleteByIdNoticeIdx(Integer noticeIdx); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeFileRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeFileRepository.java new file mode 100644 index 0000000..72e4599 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeFileRepository.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TNoticeFileEntity; +import java.util.List; +import java.util.Collection; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface NoticeFileRepository extends JpaRepository { + List findByNoticeIdxOrderByFileOrderAsc(Integer noticeIdx); + List findByNoticeIdxInOrderByNoticeIdxAscFileOrderAsc( + Collection noticeIds); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeRepository.java new file mode 100644 index 0000000..a37a044 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeRepository.java @@ -0,0 +1,47 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TNoticeEntity; +import java.util.Collection; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface NoticeRepository extends JpaRepository { + + @Query(""" + select n from TNoticeEntity n + where n.isDel = false + and (:searchPattern is null + or str(n.id) like :searchPattern + or lower(n.noticeTitle) like :searchPattern + or lower(n.regUser) like :searchPattern) + and case + when :centerRestricted = false then 1 + when not exists (select visible.id from TNoticeCenterMapEntity visible + where visible.id.noticeIdx = n.id) then 1 + when exists (select visible.id from TNoticeCenterMapEntity visible + where visible.id.noticeIdx = n.id + and visible.id.centerCd = :visibleCenterCd) then 1 + else 0 + end = 1 + and case + when :targetFilterEnabled = false then 1 + when not exists (select target.id from TNoticeCenterMapEntity target + where target.id.noticeIdx = n.id) then 1 + when exists (select target.id from TNoticeCenterMapEntity target + where target.id.noticeIdx = n.id + and target.id.centerCd in :targetCenterCds) then 1 + else 0 + end = 1 + """) + Page search( + @Param("searchPattern") String searchPattern, + @Param("centerRestricted") boolean centerRestricted, + @Param("visibleCenterCd") Integer visibleCenterCd, + @Param("targetFilterEnabled") boolean targetFilterEnabled, + @Param("targetCenterCds") Collection targetCenterCds, + Pageable pageable); + +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeViewRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeViewRepository.java new file mode 100644 index 0000000..dacd880 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/NoticeViewRepository.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TNoticeViewEntity; +import com.kri.ksif.manage.back.persistence.entity.id.TNoticeViewEntityId; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.Collection; +import java.util.List; + +public interface NoticeViewRepository extends JpaRepository { + List findByIdNoticeIdxInAndIdCenterCd( + Collection noticeIds, Integer centerCd); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupCenterMapRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupCenterMapRepository.java new file mode 100644 index 0000000..8f9e87b --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupCenterMapRepository.java @@ -0,0 +1,13 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TPopupCenterMapEntity; +import com.kri.ksif.manage.back.persistence.entity.id.TPopupCenterMapEntityId; +import java.util.List; +import java.util.Collection; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PopupCenterMapRepository extends JpaRepository { + List findByIdPopupIdx(Integer popupIdx); + List findByIdPopupIdxIn(Collection popupIds); + long deleteByIdPopupIdx(Integer popupIdx); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupRepository.java new file mode 100644 index 0000000..2d44e1d --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupRepository.java @@ -0,0 +1,56 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TPopupEntity; +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.List; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface PopupRepository extends JpaRepository { + + @Query(""" + select p from TPopupEntity p + where p.isDel = false + and (:searchPattern is null + or str(p.id) like :searchPattern + or lower(p.popupTitle) like :searchPattern + or lower(p.regUser) like :searchPattern) + and case + when :targetFilterEnabled = false then 1 + when not exists (select target.id from TPopupCenterMapEntity target + where target.id.popupIdx = p.id) then 1 + when exists (select target.id from TPopupCenterMapEntity target + where target.id.popupIdx = p.id + and target.id.centerCd in :targetCenterCds) then 1 + else 0 + end = 1 + """) + Page search( + @Param("searchPattern") String searchPattern, + @Param("targetFilterEnabled") boolean targetFilterEnabled, + @Param("targetCenterCds") Collection targetCenterCds, + Pageable pageable); + + @Query(""" + select p from TPopupEntity p + where p.isDel = false + and p.startDt <= :now + and p.endDt > :endThreshold + and case + when not exists (select m.id from TPopupCenterMapEntity m + where m.id.popupIdx = p.id) then 1 + when exists (select m.id from TPopupCenterMapEntity m + where m.id.popupIdx = p.id + and m.id.centerCd = :centerCd) then 1 + else 0 + end = 1 + order by p.regDt desc + """) + List findActiveVisible(@Param("centerCd") Integer centerCd, + @Param("now") LocalDateTime now, + @Param("endThreshold") LocalDateTime endThreshold); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupViewRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupViewRepository.java new file mode 100644 index 0000000..fde16e2 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/PopupViewRepository.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TPopupViewEntity; +import com.kri.ksif.manage.back.persistence.entity.id.TPopupViewEntityId; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.Collection; +import java.util.List; + +public interface PopupViewRepository extends JpaRepository { + List findByIdPopupIdxInAndIdCenterCd( + Collection popupIds, Integer centerCd); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaAnswerFileRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaAnswerFileRepository.java new file mode 100644 index 0000000..9707e92 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaAnswerFileRepository.java @@ -0,0 +1,9 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TQnaAnswerFileEntity; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface QnaAnswerFileRepository extends JpaRepository { + List findByQnaAnswerIdxOrderByFileOrderAsc(Integer answerId); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaAnswerRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaAnswerRepository.java new file mode 100644 index 0000000..392b1c6 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaAnswerRepository.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TQnaAnswerEntity; +import java.util.Optional; +import java.util.Collection; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface QnaAnswerRepository extends JpaRepository { + Optional findByQnaQuestionIdxAndIsDelFalse(Integer questionId); + List findByQnaQuestionIdxInAndIsDelFalse(Collection questionIds); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaQuestionFileRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaQuestionFileRepository.java new file mode 100644 index 0000000..1fba219 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaQuestionFileRepository.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TQnaQuestionFileEntity; +import java.util.List; +import java.util.Collection; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface QnaQuestionFileRepository extends JpaRepository { + List findByQnaQuestionIdxOrderByFileOrderAsc(Integer questionId); + List findByQnaQuestionIdxInOrderByQnaQuestionIdxAscFileOrderAsc( + Collection questionIds); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaQuestionRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaQuestionRepository.java new file mode 100644 index 0000000..71a7f07 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/QnaQuestionRepository.java @@ -0,0 +1,73 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TQnaQuestionEntity; +import java.util.Collection; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface QnaQuestionRepository extends JpaRepository { + + @Query(""" + select q from TQnaQuestionEntity q + where q.isDel = false + and (:searchPattern is null + or str(q.id) like :searchPattern + or lower(q.questionTitle) like :searchPattern + or lower(q.regUser) like :searchPattern) + and (:centerRestricted = false or q.centerCd = :visibleCenterCd) + and (:targetFilterEnabled = false + or q.centerCd = 0 + or q.centerCd in :targetCenterCds) + """) + Page search( + @Param("searchPattern") String searchPattern, + @Param("centerRestricted") boolean centerRestricted, + @Param("visibleCenterCd") Integer visibleCenterCd, + @Param("targetFilterEnabled") boolean targetFilterEnabled, + @Param("targetCenterCds") Collection targetCenterCds, + Pageable pageable); + + @Query(value = """ + select q from TQnaQuestionEntity q + left join TQnaAnswerEntity a + on a.qnaQuestionIdx = q.id and a.isDel = false + where q.isDel = false + and (:searchPattern is null + or str(q.id) like :searchPattern + or lower(q.questionTitle) like :searchPattern + or lower(q.regUser) like :searchPattern) + and (:centerRestricted = false or q.centerCd = :visibleCenterCd) + and (:targetFilterEnabled = false + or q.centerCd = 0 + or q.centerCd in :targetCenterCds) + order by + case when :sortBy = 'answerDt' and :ascending = true then a.regDt end asc, + case when :sortBy = 'answerDt' and :ascending = false then a.regDt end desc, + case when :sortBy = 'viewDt' and :ascending = true then a.viewDt end asc, + case when :sortBy = 'viewDt' and :ascending = false then a.viewDt end desc, + q.id desc + """, countQuery = """ + select count(q) from TQnaQuestionEntity q + where q.isDel = false + and (:searchPattern is null + or str(q.id) like :searchPattern + or lower(q.questionTitle) like :searchPattern + or lower(q.regUser) like :searchPattern) + and (:centerRestricted = false or q.centerCd = :visibleCenterCd) + and (:targetFilterEnabled = false + or q.centerCd = 0 + or q.centerCd in :targetCenterCds) + """) + Page searchByAnswerDate( + @Param("searchPattern") String searchPattern, + @Param("centerRestricted") boolean centerRestricted, + @Param("visibleCenterCd") Integer visibleCenterCd, + @Param("targetFilterEnabled") boolean targetFilterEnabled, + @Param("targetCenterCds") Collection targetCenterCds, + @Param("sortBy") String sortBy, + @Param("ascending") boolean ascending, + Pageable pageable); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportFinalDataJdbcRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportFinalDataJdbcRepository.java new file mode 100644 index 0000000..b073a32 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportFinalDataJdbcRepository.java @@ -0,0 +1,53 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +@Repository +@RequiredArgsConstructor +public class ReportFinalDataJdbcRepository { + + private static final int BATCH_SIZE = 1_000; + private static final String INSERT_SQL = """ + INSERT INTO t_report_final_data ( + center_cd, + report_header_id, + report_final_data_value + ) VALUES (?, ?, ?) + """; + + private final JdbcTemplate jdbcTemplate; + + public long deleteByCenterCds(Collection centerCds) { + if (centerCds.isEmpty()) { + return 0; + } + String placeholders = String.join(",", Collections.nCopies(centerCds.size(), "?")); + String sql = "DELETE FROM t_report_final_data WHERE center_cd IN (" + placeholders + ")"; + return jdbcTemplate.update(sql, centerCds.toArray()); + } + + public void insertAll(List values) { + jdbcTemplate.batchUpdate( + INSERT_SQL, + values, + BATCH_SIZE, + (statement, value) -> { + statement.setInt(1, value.centerCd()); + statement.setInt(2, value.reportHeaderId()); + statement.setString(3, value.reportFinalDataValue()); + } + ); + } + + public record Value( + Integer centerCd, + Integer reportHeaderId, + String reportFinalDataValue + ) { + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportFinalDataRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportFinalDataRepository.java new file mode 100644 index 0000000..0436a5c --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportFinalDataRepository.java @@ -0,0 +1,13 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TReportFinalDataEntity; +import com.kri.ksif.manage.back.persistence.entity.id.TReportFinalDataEntityId; +import java.util.Collection; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ReportFinalDataRepository + extends JpaRepository { + + List findByIdCenterCdIn(Collection centerCds); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportHeaderRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportHeaderRepository.java new file mode 100644 index 0000000..4ebeeb5 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/ReportHeaderRepository.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TReportHeaderEntity; +import com.kri.ksif.manage.back.common.enums.ReportHeaderType; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ReportHeaderRepository extends JpaRepository { + + List findByReportHeaderTypeOrderByReportHeaderOrderAsc( + ReportHeaderType reportHeaderType); +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/SysEventLogRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/SysEventLogRepository.java new file mode 100644 index 0000000..bb2205b --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/SysEventLogRepository.java @@ -0,0 +1,7 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.back.persistence.entity.TSysEventLogEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SysEventLogRepository extends JpaRepository { +} diff --git a/src/main/java/com/kri/ksif/manage/back/persistence/repository/UserRepository.java b/src/main/java/com/kri/ksif/manage/back/persistence/repository/UserRepository.java new file mode 100644 index 0000000..300b592 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/persistence/repository/UserRepository.java @@ -0,0 +1,12 @@ +package com.kri.ksif.manage.back.persistence.repository; + +import com.kri.ksif.manage.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); + + Optional findByUserId(String userId); +} diff --git a/src/main/java/com/kri/ksif/manage/back/service/AuthService.java b/src/main/java/com/kri/ksif/manage/back/service/AuthService.java new file mode 100644 index 0000000..89795ad --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/AuthService.java @@ -0,0 +1,32 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.auth.dto.JwtUserClaimsDto; +import com.kri.common.feature.auth.jwt.JwtService; +import com.kri.ksif.manage.back.dto.auth.LoginRequestDto; +import com.kri.ksif.manage.back.dto.auth.LoginResponseDto; +import com.kri.ksif.manage.back.dto.user.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/ksif/manage/back/service/CenterService.java b/src/main/java/com/kri/ksif/manage/back/service/CenterService.java new file mode 100644 index 0000000..41117c0 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/CenterService.java @@ -0,0 +1,18 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.web.RequestUserContext; +import com.kri.ksif.manage.back.common.auth.AccessControlService; +import com.kri.ksif.manage.back.dto.center.CenterResponseDto; +import com.kri.ksif.manage.back.persistence.entity.TUserEntity; +import com.kri.ksif.manage.back.persistence.repository.CenterRepository; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service @RequiredArgsConstructor +public class CenterService { + private final AccessControlService accessControlService; private final CenterRepository repository; + @Transactional(readOnly=true) public List list(RequestUserContext context){TUserEntity user=accessControlService.requireUser(context); if(accessControlService.isAdmin(user.getUserRole()))return repository.findAllByOrderByIdAsc().stream().map(this::dto).toList(); TUserEntity center=accessControlService.requireCenter(context); return repository.findById(center.getCenterCd()).map(v->List.of(dto(v))).orElse(List.of());} + private CenterResponseDto dto(com.kri.ksif.manage.back.persistence.entity.TCenterEntity v){return new CenterResponseDto(v.getId(),v.getCenterName());} +} diff --git a/src/main/java/com/kri/ksif/manage/back/service/FileStorageService.java b/src/main/java/com/kri/ksif/manage/back/service/FileStorageService.java new file mode 100644 index 0000000..768e744 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/FileStorageService.java @@ -0,0 +1,156 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.web.BusinessException; +import com.kri.ksif.manage.back.config.FileStorageProperties; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.Locale; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.multipart.MultipartFile; + +@Service +@RequiredArgsConstructor +@Slf4j +public class FileStorageService { + + public static final int MAX_FILES = 5; + public static final long MAX_FILE_SIZE = 5L * 1024 * 1024; + private final FileStorageProperties properties; + + public List validate(List files, int retainedCount) { + List values = files == null ? List.of() : files.stream() + .filter(file -> file != null && !file.isEmpty()).toList(); + if (retainedCount + values.size() > MAX_FILES) { + throw BusinessException.validationError("FILE_COUNT_EXCEEDED", "Up to 5 files are allowed."); + } + for (MultipartFile file : values) { + String name = safeName(file.getOriginalFilename()); + if (file.getSize() > MAX_FILE_SIZE) { + throw BusinessException.validationError("FILE_SIZE_EXCEEDED", "Each file must be 5 MB or less.") + .with("fileName", name); + } + if ("exe".equals(extension(name))) { + throw BusinessException.validationError("FILE_TYPE_REJECTED", "Executable files are not allowed.") + .with("fileName", name); + } + } + return values; + } + + public String safeName(String originalName) { + if (originalName == null || originalName.isBlank()) { + throw BusinessException.validationError("FILE_NAME_REQUIRED", "A file name is required."); + } + String name = Path.of(originalName).getFileName().toString(); + if (!name.equals(originalName) || name.contains("..") || name.length() > 128) { + throw BusinessException.validationError("FILE_NAME_INVALID", "The file name is invalid."); + } + String ext = extension(name); + if (ext.length() > 16) { + throw BusinessException.validationError("FILE_EXTENSION_INVALID", "The file extension is too long."); + } + return name; + } + + public String extension(String name) { + int index = name.lastIndexOf('.'); + return index < 0 ? "" : name.substring(index + 1).toLowerCase(Locale.ROOT); + } + + public void store(String category, Integer ownerId, Integer fileId, String extension, + MultipartFile file) { + Path target = resolve(category, ownerId, fileId, extension); + try { + Files.createDirectories(target.getParent()); + try (var input = file.getInputStream()) { + Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING); + } + registerRollbackCleanup(target); + } catch (IOException exception) { + throw BusinessException.internalError("FILE_STORE_FAILED", "The file could not be stored."); + } + } + + public Resource load(String category, Integer ownerId, Integer fileId, String extension) { + Path target = resolve(category, ownerId, fileId, extension); + try { + Resource resource = new UrlResource(target.toUri()); + if (!resource.exists() || !resource.isReadable()) { + throw BusinessException.notFound("FILE_NOT_FOUND", "The file was not found."); + } + return resource; + } catch (BusinessException exception) { + throw exception; + } catch (Exception exception) { + throw BusinessException.internalError("FILE_READ_FAILED", "The file could not be read."); + } + } + + public void delete(String category, Integer ownerId, Integer fileId, String extension) { + Path target = resolve(category, ownerId, fileId, extension); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + deleteAfterCommit(target); + } + }); + return; + } + deleteNow(target); + } + + private void registerRollbackCleanup(Path target) { + if (!TransactionSynchronizationManager.isSynchronizationActive()) { + return; + } + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + if (status != TransactionSynchronization.STATUS_COMMITTED) { + deleteQuietly(target, "rollback cleanup"); + } + } + }); + } + + private void deleteAfterCommit(Path target) { + deleteQuietly(target, "post-commit deletion"); + } + + private void deleteQuietly(Path target, String operation) { + try { + Files.deleteIfExists(target); + } catch (IOException exception) { + log.warn("File {} failed: {}", operation, target, exception); + } + } + + private void deleteNow(Path target) { + try { + Files.deleteIfExists(target); + } catch (IOException exception) { + throw BusinessException.internalError("FILE_DELETE_FAILED", "The file could not be deleted."); + } + } + + private Path resolve(String category, Integer ownerId, Integer fileId, String extension) { + Path root = Path.of(properties.getBaseDir()).toAbsolutePath().normalize(); + String fileName = extension == null || extension.isBlank() + ? String.valueOf(fileId) : fileId + "." + extension; + Path target = root.resolve(category).resolve(String.valueOf(ownerId)).resolve(fileName).normalize(); + if (!target.startsWith(root)) { + throw BusinessException.badRequest("FILE_PATH_INVALID", "The file path is invalid."); + } + return target; + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/service/MenuService.java b/src/main/java/com/kri/ksif/manage/back/service/MenuService.java new file mode 100644 index 0000000..5996129 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/MenuService.java @@ -0,0 +1,26 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.web.BusinessException; +import com.kri.common.feature.web.RequestUserContext; +import com.kri.ksif.manage.back.common.auth.AccessControlService; +import com.kri.ksif.manage.back.dto.menu.*; +import com.kri.ksif.manage.back.persistence.entity.TMenuEntity; +import com.kri.ksif.manage.back.persistence.entity.TUserEntity; +import com.kri.ksif.manage.back.persistence.repository.MenuRepository; +import java.util.*; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class MenuService { + private final AccessControlService accessControlService; + private final MenuRepository repository; + @Transactional(readOnly=true) + public List list(RequestUserContext context){TUserEntity user=accessControlService.requireUser(context); List values=accessControlService.isAdmin(user.getUserRole())?repository.findAllByOrderByMenuOrderAsc():accessControlService.isCenter(user.getUserRole())?repository.findByIsUserOpenTrueOrderByMenuOrderAsc():throwUnsupported(); return values.stream().map(this::dto).toList();} + @Transactional + public List update(MenuExposureRequestDto request,RequestUserContext context){accessControlService.requireAdmin(context); Set ids=new HashSet<>(); request.menus().forEach(v->{if(!ids.add(v.menuId()))throw BusinessException.validationError("MENU_DUPLICATED","Menu is duplicated.");}); Map menus=new HashMap<>(); repository.findAllById(ids).forEach(v->menus.put(v.getId(),v)); if(menus.size()!=ids.size())throw BusinessException.validationError("MENU_NOT_FOUND","A Menu was not found."); request.menus().forEach(v->menus.get(v.menuId()).setIsUserOpen(v.userOpen())); return repository.findAllByOrderByMenuOrderAsc().stream().map(this::dto).toList();} + private T throwUnsupported(){throw BusinessException.forbidden("ROLE_NOT_SUPPORTED","The user role is not supported.");} + private MenuResponseDto dto(TMenuEntity v){return new MenuResponseDto(v.getId(),v.getMenuOrder(),v.getMenuTitle(),v.getMenuPath(),v.getIsUserOpen());} +} diff --git a/src/main/java/com/kri/ksif/manage/back/service/NoticeService.java b/src/main/java/com/kri/ksif/manage/back/service/NoticeService.java new file mode 100644 index 0000000..44333bf --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/NoticeService.java @@ -0,0 +1,273 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.datetime.DateTimeUtil; +import com.kri.common.feature.web.BusinessException; +import com.kri.common.feature.web.RequestUserContext; +import com.kri.common.feature.web.page.PageResponseDto; +import com.kri.ksif.manage.back.common.auth.AccessControlService; +import com.kri.ksif.manage.back.common.web.ContentSearchCriteria; +import com.kri.ksif.manage.back.common.web.PageRequestSupport; +import com.kri.ksif.manage.back.dto.common.FileResponseDto; +import com.kri.ksif.manage.back.dto.common.ContentSearchRequestDto; +import com.kri.ksif.manage.back.dto.notice.NoticeRequestDto; +import com.kri.ksif.manage.back.dto.notice.NoticeResponseDto; +import com.kri.ksif.manage.back.persistence.entity.TNoticeCenterMapEntity; +import com.kri.ksif.manage.back.persistence.entity.TNoticeEntity; +import com.kri.ksif.manage.back.persistence.entity.TNoticeFileEntity; +import com.kri.ksif.manage.back.persistence.entity.TNoticeViewEntity; +import com.kri.ksif.manage.back.persistence.entity.TUserEntity; +import com.kri.ksif.manage.back.persistence.entity.id.TNoticeCenterMapEntityId; +import com.kri.ksif.manage.back.persistence.entity.id.TNoticeViewEntityId; +import com.kri.ksif.manage.back.persistence.repository.NoticeCenterMapRepository; +import com.kri.ksif.manage.back.persistence.repository.NoticeFileRepository; +import com.kri.ksif.manage.back.persistence.repository.NoticeRepository; +import com.kri.ksif.manage.back.persistence.repository.NoticeViewRepository; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import org.springframework.core.io.Resource; +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +@Service +@RequiredArgsConstructor +public class NoticeService { + private static final String CATEGORY = "notice"; + private final AccessControlService accessControlService; + private final TargetCenterService targetCenterService; + private final FileStorageService fileStorageService; + private final NoticeRepository noticeRepository; + private final NoticeCenterMapRepository mapRepository; + private final NoticeFileRepository fileRepository; + private final NoticeViewRepository viewRepository; + + @Transactional(readOnly = true) + public PageResponseDto list( + ContentSearchRequestDto request, + RequestUserContext context + ) { + TUserEntity user = accessControlService.requireUser(context); + var pageable = PageRequestSupport.latest(request, TNoticeEntity.class); + ContentSearchCriteria criteria = ContentSearchCriteria.from(request); + boolean centerRestricted = accessControlService.isCenter(user.getUserRole()); + Integer visibleCenterCd = centerRestricted ? requireCenter(user) : 0; + Page result = noticeRepository.search( + criteria.searchPattern(), + centerRestricted, + visibleCenterCd, + criteria.targetFilterEnabled(), + criteria.targetCenterCds(), + pageable); + List noticeIds = result.getContent().stream().map(TNoticeEntity::getId).toList(); + + Map> filesByNotice = fileRepository + .findByNoticeIdxInOrderByNoticeIdxAscFileOrderAsc(noticeIds).stream() + .collect(Collectors.groupingBy( + TNoticeFileEntity::getNoticeIdx, + Collectors.mapping(this::toFileDto, Collectors.toList()) + )); + Map> targetsByNotice = mapRepository + .findByIdNoticeIdxIn(noticeIds).stream() + .collect(Collectors.groupingBy( + value -> value.getId().getNoticeIdx(), + Collectors.mapping(value -> value.getId().getCenterCd(), Collectors.toList()) + )); + Set viewedNoticeIds = accessControlService.isCenter(user.getUserRole()) + ? viewRepository.findByIdNoticeIdxInAndIdCenterCd(noticeIds, user.getCenterCd()).stream() + .map(value -> value.getId().getNoticeIdx()) + .collect(Collectors.toSet()) + : Set.of(); + + return PageResponseDto.from(result.map(entity -> new NoticeResponseDto( + entity.getId(), + entity.getNoticeTitle(), + entity.getNoticeContent(), + targetsByNotice.getOrDefault(entity.getId(), List.of()), + filesByNotice.getOrDefault(entity.getId(), List.of()), + entity.getRegUser(), + entity.getRegDt(), + entity.getModUser(), + entity.getModDt(), + viewedNoticeIds.contains(entity.getId()) + ))); + } + + @Transactional + public NoticeResponseDto get(Integer id, RequestUserContext context) { + TUserEntity user = accessControlService.requireUser(context); + TNoticeEntity notice = findActive(id); + ensureVisible(notice.getId(), user); + if (accessControlService.isCenter(user.getUserRole())) { + recordView(notice.getId(), user); + } + return toDto(notice, user); + } + + @Transactional + public NoticeResponseDto create(NoticeRequestDto request, List files, + RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); + List centerCds = targetCenterService.validate(request.centerCds()); + List validFiles = fileStorageService.validate(files, 0); + var now = DateTimeUtil.nowKstLocalDateTime(); + TNoticeEntity entity = new TNoticeEntity(); + entity.setNoticeTitle(request.title()); + entity.setNoticeContent(request.contentHtml()); + entity.setRegUser(admin.getUserId()); + entity.setRegDt(now); + entity.setIsDel(false); + noticeRepository.save(entity); + replaceTargets(entity.getId(), centerCds); + addFiles(entity.getId(), validFiles, admin.getUserId(), 0); + return toDto(entity, admin); + } + + @Transactional + public NoticeResponseDto update(Integer id, NoticeRequestDto request, List files, + RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); + TNoticeEntity entity = findActive(id); + List centers = targetCenterService.validate(request.centerCds()); + List existing = fileRepository.findByNoticeIdxOrderByFileOrderAsc(id); + List kept = resolveKept(existing, request.keepFileIds()); + List validFiles = fileStorageService.validate(files, kept.size()); + entity.setNoticeTitle(request.title()); + entity.setNoticeContent(request.contentHtml()); + entity.setModUser(admin.getUserId()); + entity.setModDt(DateTimeUtil.nowKstLocalDateTime()); + replaceTargets(id, centers); + removeFiles(existing, kept); + reorder(kept); + addFiles(id, validFiles, admin.getUserId(), kept.size()); + return toDto(entity, admin); + } + + @Transactional + public void delete(Integer id, RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); + TNoticeEntity entity = findActive(id); + entity.setIsDel(true); + entity.setDelUser(admin.getUserId()); + entity.setDelDt(DateTimeUtil.nowKstLocalDateTime()); + } + + @Transactional(readOnly = true) + public Download download(Integer noticeId, Integer fileId, RequestUserContext context) { + TUserEntity user = accessControlService.requireUser(context); + TNoticeEntity notice = findActive(noticeId); + ensureVisible(notice.getId(), user); + TNoticeFileEntity file = fileRepository.findById(fileId) + .filter(value -> value.getNoticeIdx().equals(noticeId)) + .orElseThrow(() -> BusinessException.notFound("NOTICE_FILE_NOT_FOUND", "Notice file was not found.")); + return new Download(file.getFileName(), fileStorageService.load( + CATEGORY, noticeId, fileId, file.getFileType())); + } + + private TNoticeEntity findActive(Integer id) { + return noticeRepository.findById(id).filter(entity -> !entity.getIsDel()) + .orElseThrow(() -> BusinessException.notFound("NOTICE_NOT_FOUND", "Notice was not found.")); + } + + private int requireCenter(TUserEntity user) { + if (!accessControlService.isCenter(user.getUserRole())) { + throw BusinessException.forbidden("ROLE_NOT_SUPPORTED", "The user role is not supported."); + } + return user.getCenterCd(); + } + + private void ensureVisible(Integer noticeId, TUserEntity user) { + if (accessControlService.isAdmin(user.getUserRole())) return; + int centerCd = requireCenter(user); + List targets = targets(noticeId); + if (!targets.isEmpty() && !targets.contains(centerCd)) { + throw BusinessException.forbidden("NOTICE_ACCESS_DENIED", "Notice is not visible to this Center."); + } + } + + private void recordView(Integer noticeId, TUserEntity user) { + TNoticeViewEntityId id = new TNoticeViewEntityId(); + id.setNoticeIdx(noticeId); + id.setCenterCd(user.getCenterCd()); + if (!viewRepository.existsById(id)) { + TNoticeViewEntity view = new TNoticeViewEntity(); + view.setId(id); + view.setViewUser(user.getUserId()); + view.setViewDt(DateTimeUtil.nowKstLocalDateTime()); + viewRepository.save(view); + } + } + + private void replaceTargets(Integer noticeId, List centerCds) { + mapRepository.deleteByIdNoticeIdx(noticeId); + mapRepository.saveAll(centerCds.stream().map(centerCd -> { + TNoticeCenterMapEntityId id = new TNoticeCenterMapEntityId(); + id.setNoticeIdx(noticeId); id.setCenterCd(centerCd); + TNoticeCenterMapEntity entity = new TNoticeCenterMapEntity(); entity.setId(id); + return entity; + }).toList()); + } + + private List targets(Integer noticeId) { + return mapRepository.findByIdNoticeIdx(noticeId).stream().map(v -> v.getId().getCenterCd()).toList(); + } + + private List resolveKept(List existing, List ids) { + if (ids == null) return new ArrayList<>(existing); + Set requested = new HashSet<>(ids); + if (requested.size() != ids.size() || existing.stream().map(TNoticeFileEntity::getId).filter(requested::contains).count() != requested.size()) { + throw BusinessException.validationError("NOTICE_KEEP_FILE_INVALID", "A retained file does not belong to the Notice."); + } + return existing.stream().filter(v -> requested.contains(v.getId())).collect(java.util.stream.Collectors.toCollection(ArrayList::new)); + } + + private void removeFiles(List existing, List kept) { + Set keptIds = kept.stream().map(TNoticeFileEntity::getId).collect(java.util.stream.Collectors.toSet()); + existing.stream().filter(v -> !keptIds.contains(v.getId())).forEach(file -> { + fileStorageService.delete(CATEGORY, file.getNoticeIdx(), file.getId(), file.getFileType()); + fileRepository.delete(file); + }); + } + + private void reorder(List files) { + for (int i = 0; i < files.size(); i++) files.get(i).setFileOrder((short) (i + 1)); + } + + private void addFiles(Integer noticeId, List files, String userId, int start) { + for (int i = 0; i < files.size(); i++) { + MultipartFile upload = files.get(i); + String name = fileStorageService.safeName(upload.getOriginalFilename()); + TNoticeFileEntity entity = new TNoticeFileEntity(); + entity.setNoticeIdx(noticeId); entity.setFileOrder((short) (start + i + 1)); + entity.setFileName(name); entity.setFileType(fileStorageService.extension(name)); + entity.setRegUser(userId); entity.setRegDt(DateTimeUtil.nowKstLocalDateTime()); + fileRepository.save(entity); + fileStorageService.store(CATEGORY, noticeId, entity.getId(), entity.getFileType(), upload); + } + } + + private NoticeResponseDto toDto(TNoticeEntity entity, TUserEntity user) { + List files = fileRepository.findByNoticeIdxOrderByFileOrderAsc(entity.getId()).stream() + .map(this::toFileDto).toList(); + boolean viewed = false; + if (accessControlService.isCenter(user.getUserRole())) { + TNoticeViewEntityId id = new TNoticeViewEntityId(); id.setNoticeIdx(entity.getId()); id.setCenterCd(user.getCenterCd()); + viewed = viewRepository.existsById(id); + } + return new NoticeResponseDto(entity.getId(), entity.getNoticeTitle(), entity.getNoticeContent(), + targets(entity.getId()), files, entity.getRegUser(), entity.getRegDt(), entity.getModUser(), entity.getModDt(), viewed); + } + + private FileResponseDto toFileDto(TNoticeFileEntity file) { + return new FileResponseDto( + file.getId(), file.getFileOrder(), file.getFileName(), file.getFileType()); + } + + public record Download(String fileName, Resource resource) { + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/service/PopupService.java b/src/main/java/com/kri/ksif/manage/back/service/PopupService.java new file mode 100644 index 0000000..d5c3705 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/PopupService.java @@ -0,0 +1,180 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.datetime.DateTimeUtil; +import com.kri.common.feature.web.BusinessException; +import com.kri.common.feature.web.RequestUserContext; +import com.kri.common.feature.web.page.PageResponseDto; +import com.kri.ksif.manage.back.common.auth.AccessControlService; +import com.kri.ksif.manage.back.common.web.ContentSearchCriteria; +import com.kri.ksif.manage.back.common.web.PageRequestSupport; +import com.kri.ksif.manage.back.dto.common.ContentSearchRequestDto; +import com.kri.ksif.manage.back.dto.popup.PopupRequestDto; +import com.kri.ksif.manage.back.dto.popup.PopupResponseDto; +import com.kri.ksif.manage.back.persistence.entity.*; +import com.kri.ksif.manage.back.persistence.entity.id.*; +import com.kri.ksif.manage.back.persistence.repository.*; +import java.time.LocalDateTime; +import java.util.List; +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; + +@Service +@RequiredArgsConstructor +public class PopupService { + private final AccessControlService accessControlService; + private final TargetCenterService targetCenterService; + private final PopupRepository popupRepository; + private final PopupCenterMapRepository mapRepository; + private final PopupViewRepository viewRepository; + + @Transactional(readOnly = true) + public PageResponseDto list( + ContentSearchRequestDto request, + RequestUserContext context + ) { + accessControlService.requireAdmin(context); + var pageable = PageRequestSupport.latest(request, TPopupEntity.class); + ContentSearchCriteria criteria = ContentSearchCriteria.from(request); + var result = popupRepository.search( + criteria.searchPattern(), + criteria.targetFilterEnabled(), + criteria.targetCenterCds(), + pageable); + List popupIds = result.getContent().stream().map(TPopupEntity::getId).toList(); + Map> targetsByPopup = mapRepository.findByIdPopupIdxIn(popupIds).stream() + .collect(Collectors.groupingBy( + value -> value.getId().getPopupIdx(), + Collectors.mapping(value -> value.getId().getCenterCd(), Collectors.toList()) + )); + return PageResponseDto.from(result.map(popup -> new PopupResponseDto( + popup.getId(), + popup.getPopupTitle(), + popup.getPopupContent(), + popup.getStartDt(), + popup.getEndDt(), + targetsByPopup.getOrDefault(popup.getId(), List.of()), + popup.getRegUser(), + popup.getRegDt(), + popup.getModUser(), + popup.getModDt(), + false + ))); + } + + @Transactional + public List active(RequestUserContext context) { + TUserEntity center = accessControlService.requireCenter(context); + LocalDateTime now = DateTimeUtil.nowKstLocalDateTime(); + List popups = popupRepository.findActiveVisible( + center.getCenterCd(), now, now.minusMinutes(1)); + List popupIds = popups.stream().map(TPopupEntity::getId).toList(); + Map> targetsByPopup = mapRepository.findByIdPopupIdxIn(popupIds).stream() + .collect(Collectors.groupingBy( + value -> value.getId().getPopupIdx(), + Collectors.mapping(value -> value.getId().getCenterCd(), Collectors.toList()) + )); + Set viewedPopupIds = viewRepository + .findByIdPopupIdxInAndIdCenterCd(popupIds, center.getCenterCd()).stream() + .map(value -> value.getId().getPopupIdx()) + .collect(Collectors.toSet()); + List newViews = popupIds.stream() + .filter(popupId -> !viewedPopupIds.contains(popupId)) + .map(popupId -> newView(popupId, center)) + .toList(); + viewRepository.saveAll(newViews); + + return popups.stream().map(popup -> new PopupResponseDto( + popup.getId(), + popup.getPopupTitle(), + popup.getPopupContent(), + popup.getStartDt(), + popup.getEndDt(), + targetsByPopup.getOrDefault(popup.getId(), List.of()), + popup.getRegUser(), + popup.getRegDt(), + popup.getModUser(), + popup.getModDt(), + true + )).toList(); + } + + @Transactional + public PopupResponseDto get(Integer popupId, RequestUserContext context) { + TUserEntity user = accessControlService.requireUser(context); + TPopupEntity popup = findActive(popupId); + ensureVisible(popupId, user); + if (accessControlService.isCenter(user.getUserRole())) recordView(popupId, user); + return toDto(popup, user); + } + + @Transactional + public PopupResponseDto create(PopupRequestDto request, RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); + validatePeriod(request); List targets = targetCenterService.validate(request.centerCds()); + TPopupEntity popup = new TPopupEntity(); apply(popup, request); + popup.setRegUser(admin.getUserId()); popup.setRegDt(DateTimeUtil.nowKstLocalDateTime()); popup.setIsDel(false); + popupRepository.save(popup); replaceTargets(popup.getId(), targets); + return toDto(popup, admin); + } + + @Transactional + public PopupResponseDto update(Integer popupId, PopupRequestDto request, RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); + validatePeriod(request); List targets = targetCenterService.validate(request.centerCds()); + TPopupEntity popup = findActive(popupId); apply(popup, request); + popup.setModUser(admin.getUserId()); popup.setModDt(DateTimeUtil.nowKstLocalDateTime()); + replaceTargets(popupId, targets); return toDto(popup, admin); + } + + @Transactional + public void delete(Integer popupId, RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); TPopupEntity popup = findActive(popupId); + popup.setIsDel(true); popup.setDelUser(admin.getUserId()); popup.setDelDt(DateTimeUtil.nowKstLocalDateTime()); + } + + private void apply(TPopupEntity popup, PopupRequestDto request) { + popup.setPopupTitle(request.title()); popup.setPopupContent(request.contentHtml()); + popup.setStartDt(request.startDt()); popup.setEndDt(request.endDt()); + } + private void validatePeriod(PopupRequestDto request) { + if (request.startDt().isAfter(request.endDt())) throw BusinessException.validationError("POPUP_PERIOD_INVALID", "Popup startDt must not be after endDt."); + } + private TPopupEntity findActive(Integer id) { + return popupRepository.findById(id).filter(v -> !v.getIsDel()) + .orElseThrow(() -> BusinessException.notFound("POPUP_NOT_FOUND", "Popup was not found.")); + } + private List targets(Integer id) { return mapRepository.findByIdPopupIdx(id).stream().map(v -> v.getId().getCenterCd()).toList(); } + private void ensureVisible(Integer id, TUserEntity user) { + if (accessControlService.isAdmin(user.getUserRole())) return; + if (!accessControlService.isCenter(user.getUserRole())) throw BusinessException.forbidden("ROLE_NOT_SUPPORTED", "The user role is not supported."); + List targets = targets(id); + if (!targets.isEmpty() && !targets.contains(user.getCenterCd())) throw BusinessException.forbidden("POPUP_ACCESS_DENIED", "Popup is not visible to this Center."); + } + private void replaceTargets(Integer popupId, List centerCds) { + mapRepository.deleteByIdPopupIdx(popupId); + mapRepository.saveAll(centerCds.stream().map(centerCd -> { TPopupCenterMapEntityId id=new TPopupCenterMapEntityId(); id.setPopupIdx(popupId); id.setCenterCd(centerCd); TPopupCenterMapEntity v=new TPopupCenterMapEntity(); v.setId(id); return v; }).toList()); + } + private void recordView(Integer popupId, TUserEntity user) { + TPopupViewEntityId id=new TPopupViewEntityId(); id.setPopupIdx(popupId); id.setCenterCd(user.getCenterCd()); + if (!viewRepository.existsById(id)) { TPopupViewEntity view=new TPopupViewEntity(); view.setId(id); view.setViewUser(user.getUserId()); view.setViewDt(DateTimeUtil.nowKstLocalDateTime()); viewRepository.save(view); } + } + private TPopupViewEntity newView(Integer popupId, TUserEntity user) { + TPopupViewEntityId id = new TPopupViewEntityId(); + id.setPopupIdx(popupId); + id.setCenterCd(user.getCenterCd()); + TPopupViewEntity view = new TPopupViewEntity(); + view.setId(id); + view.setViewUser(user.getUserId()); + view.setViewDt(DateTimeUtil.nowKstLocalDateTime()); + return view; + } + private PopupResponseDto toDto(TPopupEntity p, TUserEntity user) { + boolean viewed=false; + if (accessControlService.isCenter(user.getUserRole())) { TPopupViewEntityId id=new TPopupViewEntityId(); id.setPopupIdx(p.getId()); id.setCenterCd(user.getCenterCd()); viewed=viewRepository.existsById(id); } + return new PopupResponseDto(p.getId(),p.getPopupTitle(),p.getPopupContent(),p.getStartDt(),p.getEndDt(),targets(p.getId()),p.getRegUser(),p.getRegDt(),p.getModUser(),p.getModDt(),viewed); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/service/QnaService.java b/src/main/java/com/kri/ksif/manage/back/service/QnaService.java new file mode 100644 index 0000000..e5d376b --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/QnaService.java @@ -0,0 +1,320 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.datetime.DateTimeUtil; +import com.kri.common.feature.web.BusinessException; +import com.kri.common.feature.web.RequestUserContext; +import com.kri.common.feature.web.page.PageResponseDto; +import com.kri.ksif.manage.back.common.auth.AccessControlService; +import com.kri.ksif.manage.back.common.web.ContentSearchCriteria; +import com.kri.ksif.manage.back.common.web.PageRequestSupport; +import com.kri.ksif.manage.back.dto.common.ContentSearchRequestDto; +import com.kri.ksif.manage.back.dto.common.FileResponseDto; +import com.kri.ksif.manage.back.dto.qna.QnaAnswerRequestDto; +import com.kri.ksif.manage.back.dto.qna.QnaAnswerResponseDto; +import com.kri.ksif.manage.back.dto.qna.QnaQuestionRequestDto; +import com.kri.ksif.manage.back.dto.qna.QnaQuestionResponseDto; +import com.kri.ksif.manage.back.persistence.entity.*; +import com.kri.ksif.manage.back.persistence.repository.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +@Service +@RequiredArgsConstructor +public class QnaService { + private static final String QUESTION_CATEGORY = "qna-question"; + private static final String ANSWER_CATEGORY = "qna-answer"; + private final AccessControlService accessControlService; + private final FileStorageService fileStorageService; + private final QnaQuestionRepository questionRepository; + private final QnaAnswerRepository answerRepository; + private final QnaQuestionFileRepository questionFileRepository; + private final QnaAnswerFileRepository answerFileRepository; + private final CenterRepository centerRepository; + + @Transactional(readOnly = true) + public PageResponseDto list( + ContentSearchRequestDto request, + RequestUserContext context + ) { + TUserEntity user = accessControlService.requireUser(context); + ContentSearchCriteria criteria = ContentSearchCriteria.from(request); + boolean centerRestricted = accessControlService.isCenter(user.getUserRole()); + Integer visibleCenterCd = centerRestricted ? requireCenter(user).getCenterCd() : 0; + String sortBy = request == null ? null : request.getSortBy(); + boolean answerDateSort = "answerDt".equals(sortBy) || "viewDt".equals(sortBy); + var pageable = answerDateSort + ? PageRequestSupport.unsorted(request) + : PageRequestSupport.latest(request, TQnaQuestionEntity.class); + var result = answerDateSort + ? questionRepository.searchByAnswerDate( + criteria.searchPattern(), + centerRestricted, + visibleCenterCd, + criteria.targetFilterEnabled(), + criteria.targetCenterCds(), + sortBy, + "ASC".equalsIgnoreCase(request.getSortDir()), + pageable) + : questionRepository.search( + criteria.searchPattern(), + centerRestricted, + visibleCenterCd, + criteria.targetFilterEnabled(), + criteria.targetCenterCds(), + pageable); + List questionIds = result.getContent().stream() + .map(TQnaQuestionEntity::getId).toList(); + Set centerCds = result.getContent().stream() + .map(TQnaQuestionEntity::getCenterCd).collect(Collectors.toSet()); + + Map centerNames = centerRepository.findAllById(centerCds).stream() + .collect(Collectors.toMap(TCenterEntity::getId, TCenterEntity::getCenterName)); + Map> filesByQuestion = questionFileRepository + .findByQnaQuestionIdxInOrderByQnaQuestionIdxAscFileOrderAsc(questionIds).stream() + .collect(Collectors.groupingBy( + TQnaQuestionFileEntity::getQnaQuestionIdx, + Collectors.mapping(this::toQuestionFileDto, Collectors.toList()) + )); + Map answerByQuestion = answerRepository + .findByQnaQuestionIdxInAndIsDelFalse(questionIds).stream() + .collect(Collectors.toMap( + TQnaAnswerEntity::getQnaQuestionIdx, + Function.identity(), + (first, second) -> second + )); + + return PageResponseDto.from(result.map(question -> new QnaQuestionResponseDto( + question.getId(), + question.getCenterCd(), + centerNames.get(question.getCenterCd()), + question.getQuestionTitle(), + question.getQuestionContent(), + filesByQuestion.getOrDefault(question.getId(), List.of()), + answerByQuestion.containsKey(question.getId()) + ? toAnswerSummary(answerByQuestion.get(question.getId())) : null, + question.getRegUser(), + question.getRegDt(), + question.getModUser(), + question.getModDt() + ))); + } + + @Transactional + public QnaQuestionResponseDto get(Integer questionId, RequestUserContext context) { + TUserEntity user = accessControlService.requireUser(context); + TQnaQuestionEntity question = findQuestion(questionId); + ensureQuestionAccess(question, user); + boolean centerView = accessControlService.isCenter(user.getUserRole()); + if (centerView) { + answerRepository.findByQnaQuestionIdxAndIsDelFalse(questionId).ifPresent(answer -> { + if (!answer.getIsViewAnswer()) { + answer.setIsViewAnswer(true); + answer.setViewUser(user.getUserId()); + answer.setViewDt(DateTimeUtil.nowKstLocalDateTime()); + } + }); + } + return toDto(question, true); + } + + @Transactional + public QnaQuestionResponseDto create(QnaQuestionRequestDto request, List files, + RequestUserContext context) { + TUserEntity center = accessControlService.requireCenter(context); + List uploads = fileStorageService.validate(files, 0); + TQnaQuestionEntity entity = new TQnaQuestionEntity(); + entity.setCenterCd(center.getCenterCd()); entity.setQuestionTitle(request.title()); + entity.setQuestionContent(request.contentHtml()); entity.setRegUser(center.getUserId()); + entity.setRegDt(DateTimeUtil.nowKstLocalDateTime()); entity.setIsDel(false); + questionRepository.save(entity); + addQuestionFiles(entity.getId(), uploads, center.getUserId(), 0); + return toDto(entity, true); + } + + @Transactional + public QnaQuestionResponseDto update(Integer questionId, QnaQuestionRequestDto request, + List files, RequestUserContext context) { + TUserEntity center = accessControlService.requireCenter(context); + TQnaQuestionEntity entity = findQuestion(questionId); + ensureOwner(entity, center); + ensureNoActiveAnswer(questionId); + List existing = questionFileRepository.findByQnaQuestionIdxOrderByFileOrderAsc(questionId); + List kept = keptQuestionFiles(existing, request.keepFileIds()); + List uploads = fileStorageService.validate(files, kept.size()); + entity.setQuestionTitle(request.title()); entity.setQuestionContent(request.contentHtml()); + entity.setModUser(center.getUserId()); entity.setModDt(DateTimeUtil.nowKstLocalDateTime()); + removeQuestionFiles(existing, kept); reorderQuestion(kept); + addQuestionFiles(questionId, uploads, center.getUserId(), kept.size()); + return toDto(entity, true); + } + + @Transactional + public void deleteQuestion(Integer questionId, RequestUserContext context) { + TUserEntity center = accessControlService.requireCenter(context); + TQnaQuestionEntity entity = findQuestion(questionId); + ensureOwner(entity, center); ensureNoActiveAnswer(questionId); + entity.setIsDel(true); entity.setDelUser(center.getUserId()); + entity.setDelDt(DateTimeUtil.nowKstLocalDateTime()); + } + + @Transactional + public QnaAnswerResponseDto createAnswer(Integer questionId, QnaAnswerRequestDto request, + List files, RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); + findQuestion(questionId); + if (answerRepository.findByQnaQuestionIdxAndIsDelFalse(questionId).isPresent()) { + throw BusinessException.conflict("QNA_ANSWER_EXISTS", "An active Answer already exists."); + } + List uploads = fileStorageService.validate(files, 0); + TQnaAnswerEntity entity = new TQnaAnswerEntity(); + entity.setQnaQuestionIdx(questionId); entity.setAnswerContent(request.contentHtml()); + entity.setRegUser(admin.getUserId()); entity.setRegDt(DateTimeUtil.nowKstLocalDateTime()); + entity.setIsDel(false); entity.setIsViewAnswer(false); + answerRepository.save(entity); + addAnswerFiles(entity.getId(), uploads, admin.getUserId(), 0); + return toAnswerDto(entity); + } + + @Transactional + public QnaAnswerResponseDto updateAnswer(Integer questionId, QnaAnswerRequestDto request, + List files, RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); + findQuestion(questionId); + TQnaAnswerEntity entity = findAnswer(questionId); ensureAnswerMutable(entity); + List existing = answerFileRepository.findByQnaAnswerIdxOrderByFileOrderAsc(entity.getId()); + List kept = keptAnswerFiles(existing, request.keepFileIds()); + List uploads = fileStorageService.validate(files, kept.size()); + entity.setAnswerContent(request.contentHtml()); entity.setModUser(admin.getUserId()); + entity.setModDt(DateTimeUtil.nowKstLocalDateTime()); + removeAnswerFiles(existing, kept); reorderAnswer(kept); + addAnswerFiles(entity.getId(), uploads, admin.getUserId(), kept.size()); + return toAnswerDto(entity); + } + + @Transactional + public void deleteAnswer(Integer questionId, RequestUserContext context) { + TUserEntity admin = accessControlService.requireAdmin(context); + findQuestion(questionId); + TQnaAnswerEntity entity = findAnswer(questionId); ensureAnswerMutable(entity); + entity.setIsDel(true); entity.setDelUser(admin.getUserId()); + entity.setDelDt(DateTimeUtil.nowKstLocalDateTime()); + } + + @Transactional(readOnly = true) + public Download downloadQuestion(Integer questionId, Integer fileId, RequestUserContext context) { + TUserEntity user = accessControlService.requireUser(context); + TQnaQuestionEntity question = findQuestion(questionId); ensureQuestionAccess(question, user); + TQnaQuestionFileEntity file = questionFileRepository.findById(fileId) + .filter(v -> v.getQnaQuestionIdx().equals(questionId)) + .orElseThrow(() -> BusinessException.notFound("QNA_FILE_NOT_FOUND", "Question file was not found.")); + return new Download(file.getFileName(), fileStorageService.load(QUESTION_CATEGORY, questionId, fileId, file.getFileType())); + } + + @Transactional(readOnly = true) + public Download downloadAnswer(Integer questionId, Integer fileId, RequestUserContext context) { + TUserEntity user = accessControlService.requireUser(context); + TQnaQuestionEntity question = findQuestion(questionId); ensureQuestionAccess(question, user); + TQnaAnswerEntity answer = findAnswer(questionId); + TQnaAnswerFileEntity file = answerFileRepository.findById(fileId) + .filter(v -> v.getQnaAnswerIdx().equals(answer.getId())) + .orElseThrow(() -> BusinessException.notFound("QNA_FILE_NOT_FOUND", "Answer file was not found.")); + return new Download(file.getFileName(), fileStorageService.load(ANSWER_CATEGORY, answer.getId(), fileId, file.getFileType())); + } + + private TQnaQuestionEntity findQuestion(Integer id) { + return questionRepository.findById(id).filter(v -> !v.getIsDel()) + .orElseThrow(() -> BusinessException.notFound("QNA_QUESTION_NOT_FOUND", "Question was not found.")); + } + private TQnaAnswerEntity findAnswer(Integer questionId) { + return answerRepository.findByQnaQuestionIdxAndIsDelFalse(questionId) + .orElseThrow(() -> BusinessException.notFound("QNA_ANSWER_NOT_FOUND", "Answer was not found.")); + } + private TUserEntity requireCenter(TUserEntity user) { + if (!accessControlService.isCenter(user.getUserRole())) throw BusinessException.forbidden("CENTER_REQUIRED", "Center role is required."); + return user; + } + private void ensureQuestionAccess(TQnaQuestionEntity q, TUserEntity user) { + if (!accessControlService.isAdmin(user.getUserRole()) + && (!accessControlService.isCenter(user.getUserRole()) || !q.getCenterCd().equals(user.getCenterCd()))) { + throw BusinessException.forbidden("QNA_ACCESS_DENIED", "Question is not accessible."); + } + } + private void ensureOwner(TQnaQuestionEntity q, TUserEntity user) { + if (!q.getCenterCd().equals(user.getCenterCd())) throw BusinessException.forbidden("QNA_ACCESS_DENIED", "Question belongs to another Center."); + } + private void ensureNoActiveAnswer(Integer questionId) { + if (answerRepository.findByQnaQuestionIdxAndIsDelFalse(questionId).isPresent()) + throw BusinessException.conflict("QNA_QUESTION_LOCKED", "A Question with an active Answer cannot be changed."); + } + private void ensureAnswerMutable(TQnaAnswerEntity answer) { + if (answer.getIsViewAnswer()) throw BusinessException.conflict("QNA_ANSWER_VIEWED", "A viewed Answer cannot be changed."); + } + + private QnaQuestionResponseDto toDto(TQnaQuestionEntity q, boolean includeDetail) { + String centerName = centerRepository.findById(q.getCenterCd()).map(TCenterEntity::getCenterName).orElse(null); + var files = questionFileRepository.findByQnaQuestionIdxOrderByFileOrderAsc(q.getId()).stream() + .map(this::toQuestionFileDto).toList(); + QnaAnswerResponseDto answer = answerRepository.findByQnaQuestionIdxAndIsDelFalse(q.getId()) + .map(value -> includeDetail ? toAnswerDto(value) : toAnswerSummary(value)).orElse(null); + return new QnaQuestionResponseDto(q.getId(), q.getCenterCd(), centerName, q.getQuestionTitle(), + q.getQuestionContent(), files, answer, q.getRegUser(), q.getRegDt(), q.getModUser(), q.getModDt()); + } + private QnaAnswerResponseDto toAnswerDto(TQnaAnswerEntity a) { + var files = answerFileRepository.findByQnaAnswerIdxOrderByFileOrderAsc(a.getId()).stream() + .map(v -> new FileResponseDto(v.getId(), v.getFileOrder(), v.getFileName(), v.getFileType())).toList(); + return new QnaAnswerResponseDto(a.getId(), a.getAnswerContent(), files, a.getIsViewAnswer(), + a.getViewUser(), a.getViewDt(), a.getRegUser(), a.getRegDt(), a.getModUser(), a.getModDt()); + } + private QnaAnswerResponseDto toAnswerSummary(TQnaAnswerEntity a) { + return new QnaAnswerResponseDto(a.getId(), null, List.of(), a.getIsViewAnswer(), + a.getViewUser(), a.getViewDt(), a.getRegUser(), a.getRegDt(), a.getModUser(), a.getModDt()); + } + private FileResponseDto toQuestionFileDto(TQnaQuestionFileEntity file) { + return new FileResponseDto( + file.getId(), file.getFileOrder(), file.getFileName(), file.getFileType()); + } + + private List keptQuestionFiles(List all, List ids) { + if (ids == null) return new ArrayList<>(all); + validateKeep(all.stream().map(TQnaQuestionFileEntity::getId).toList(), ids, "QNA_QUESTION_KEEP_FILE_INVALID"); + Set set = new HashSet<>(ids); return all.stream().filter(v -> set.contains(v.getId())).collect(java.util.stream.Collectors.toCollection(ArrayList::new)); + } + private List keptAnswerFiles(List all, List ids) { + if (ids == null) return new ArrayList<>(all); + validateKeep(all.stream().map(TQnaAnswerFileEntity::getId).toList(), ids, "QNA_ANSWER_KEEP_FILE_INVALID"); + Set set = new HashSet<>(ids); return all.stream().filter(v -> set.contains(v.getId())).collect(java.util.stream.Collectors.toCollection(ArrayList::new)); + } + private void validateKeep(List existing, List requested, String code) { + Set set = new HashSet<>(requested); + if (set.size() != requested.size() || !existing.containsAll(set)) throw BusinessException.validationError(code, "A retained file does not belong to this content."); + } + private void removeQuestionFiles(List all, List kept) { + Set set = kept.stream().map(TQnaQuestionFileEntity::getId).collect(java.util.stream.Collectors.toSet()); + all.stream().filter(v -> !set.contains(v.getId())).forEach(v -> { fileStorageService.delete(QUESTION_CATEGORY, v.getQnaQuestionIdx(), v.getId(), v.getFileType()); questionFileRepository.delete(v); }); + } + private void removeAnswerFiles(List all, List kept) { + Set set = kept.stream().map(TQnaAnswerFileEntity::getId).collect(java.util.stream.Collectors.toSet()); + all.stream().filter(v -> !set.contains(v.getId())).forEach(v -> { fileStorageService.delete(ANSWER_CATEGORY, v.getQnaAnswerIdx(), v.getId(), v.getFileType()); answerFileRepository.delete(v); }); + } + private void reorderQuestion(List values) { for (int i=0;i values) { for (int i=0;i files, String user, int start) { + for (int i=0;i files, String user, int start) { + for (int i=0;i centers = resolveCenters(user, centerCd); + List headers = reportHeaderRepository + .findByReportHeaderTypeOrderByReportHeaderOrderAsc(ReportHeaderType.CURRENT); + List centerCds = centers.stream().map(TCenterEntity::getId) + .filter(value -> !value.equals(AccessControlService.ALL_CENTER_CD)) + .toList(); + List headerIds = headers.stream().map(TReportHeaderEntity::getId).toList(); + List scoreHeaders = headers.stream() + .filter(header -> header.getKonQid() != null && !header.getKonQid().isBlank()) + .map(header -> new ProgressReportHeaderParamDto( + header.getId(), toJsonPath(header.getKonQid()))) + .toList(); + + List metrics = konMapper.selectProgressReport( + centerCds, headerIds, scoreHeaders); + Map> metricByCenter = new HashMap<>(); + Map completeCountByCenter = new HashMap<>(); + for (ProgressReportMetricDto metric : metrics) { + if (metric.getCenterCd() == null || metric.getHeaderId() == null) { + throw BusinessException.internalError( + "INVALID_PROGRESS_RESULT", "Progress Mapper returned an invalid row."); + } + metricByCenter.computeIfAbsent(metric.getCenterCd(), ignored -> new HashMap<>()) + .put(metric.getHeaderId(), metric); + if (metric.getCompleteCount() != null) { + completeCountByCenter.put(metric.getCenterCd(), metric.getCompleteCount()); + } + } + + CenterCountAggregate countAggregate = containsAggregateCenter(centers) + ? centerRepository.findCountAggregate(AccessControlService.ALL_CENTER_CD) + : null; + List content = centers.stream() + .map(center -> new ReportResponseDto.Content( + center.getId(), + center.getCenterName(), + isAggregateCenter(center) ? toInteger(countAggregate.getTargetCount()) + : center.getCenterQuota(), + completeCountByCenter.get(center.getId()), + headers.stream().map(header -> { + ProgressReportMetricDto metric = metricByCenter + .getOrDefault(center.getId(), Map.of()).get(header.getId()); + return new ReportResponseDto.Value( + header.getId(), + metric == null ? null : metric.getValue7(), + metric == null ? null : metric.getValue100()); + }).toList() + )) + .toList(); + return new ReportResponseDto(toHeaders(headers), content); + } + + @Transactional(readOnly = true) + public ReportResponseDto getFinal(Integer centerCd, RequestUserContext context) { + TUserEntity user = accessControlService.requireUser(context); + List centers = resolveFinalCenters(user, centerCd); + List headers = reportHeaderRepository + .findByReportHeaderTypeOrderByReportHeaderOrderAsc(ReportHeaderType.FINAL); + List centerCds = centers.stream().map(TCenterEntity::getId).toList(); + Map> valuesByCenter = reportFinalDataRepository + .findByIdCenterCdIn(centerCds).stream() + .collect(Collectors.groupingBy( + entity -> entity.getId().getCenterCd(), + Collectors.toMap( + entity -> entity.getId().getReportHeaderId(), + TReportFinalDataEntity::getReportFinalDataValue, + (first, second) -> second))); + + CenterCountAggregate countAggregate = centerRepository.findCountAggregate( + AccessControlService.ALL_CENTER_CD); + List content = centers.stream() + .map(center -> new ReportResponseDto.Content( + center.getId(), + center.getCenterName(), + isAggregateCenter(center) ? toInteger(countAggregate.getTargetCount()) + : center.getCenterQuota(), + isAggregateCenter(center) ? toInteger(countAggregate.getCompleteCount()) + : center.getCenterFinalSample(), + headers.stream() + .map(header -> new ReportResponseDto.Value( + header.getId(), null, + valuesByCenter.getOrDefault(center.getId(), Map.of()).get(header.getId()))) + .toList())) + .toList(); + return new ReportResponseDto(toHeaders(headers), content); + } + + @Transactional(transactionManager = "mainTransactionManager") + public FinalReportImportResponseDto importFinal( + MultipartFile file, + RequestUserContext context + ) { + accessControlService.requireAdmin(context); + if (file == null || file.isEmpty()) { + throw BusinessException.badRequest("FINAL_REPORT_FILE_REQUIRED", "Excel file is required."); + } + + List headers = reportHeaderRepository + .findByReportHeaderTypeOrderByReportHeaderOrderAsc(ReportHeaderType.FINAL); + Map headerById = headers.stream() + .collect(Collectors.toMap(TReportHeaderEntity::getId, header -> header)); + List> rows = readRows(file); + List importRows = validateRows(rows, headerById.keySet()); + + Set centerCds = importRows.stream().map(ImportRow::centerCd).collect(Collectors.toSet()); + Map centerById = centerRepository.findAllById(centerCds).stream() + .collect(Collectors.toMap(TCenterEntity::getId, center -> center)); + if (!centerById.keySet().containsAll(centerCds)) { + Set missing = new HashSet<>(centerCds); + missing.removeAll(centerById.keySet()); + throw BusinessException.validationError( + "FINAL_REPORT_CENTER_NOT_FOUND", "Excel contains an unknown Center.") + .with("centerCds", missing); + } + + List valuesToSave = new ArrayList<>(); + for (ImportRow row : importRows) { + TCenterEntity center = centerById.get(row.centerCd()); + center.setCenterFinalSample(row.completeCount()); + + row.values().forEach((headerId, value) -> { + if (value != null) { + valuesToSave.add(new ReportFinalDataJdbcRepository.Value( + row.centerCd(), headerId, value)); + } + }); + } + long deletedCount = reportFinalDataJdbcRepository.deleteByCenterCds(centerCds); + reportFinalDataJdbcRepository.insertAll(valuesToSave); + + return new FinalReportImportResponseDto(importRows.size(), valuesToSave.size(), deletedCount); + } + + private List resolveCenters(TUserEntity user, Integer requestedCenterCd) { + Integer resolvedCenterCd = accessControlService.resolveCenterFilter(user, requestedCenterCd); + if (resolvedCenterCd == null) { + return centerRepository.findAllByOrderByIdAsc(); + } + return List.of(centerRepository.findById(resolvedCenterCd) + .orElseThrow(() -> BusinessException.notFound( + "CENTER_NOT_FOUND", "Center was not found."))); + } + + private List resolveFinalCenters( + TUserEntity user, + Integer requestedCenterCd + ) { + Integer resolvedCenterCd = accessControlService.resolveCenterFilter(user, requestedCenterCd); + if (resolvedCenterCd == null) { + return centerRepository.findAllByOrderByIdAsc(); + } + + TCenterEntity total = findCenter(AccessControlService.ALL_CENTER_CD); + if (resolvedCenterCd.equals(AccessControlService.ALL_CENTER_CD)) { + return List.of(total); + } + return List.of(total, findCenter(resolvedCenterCd)); + } + + private TCenterEntity findCenter(Integer centerCd) { + return centerRepository.findById(centerCd) + .orElseThrow(() -> BusinessException.notFound( + "CENTER_NOT_FOUND", "Center was not found.")); + } + + private boolean containsAggregateCenter(List centers) { + return centers.stream().anyMatch(this::isAggregateCenter); + } + + private boolean isAggregateCenter(TCenterEntity center) { + return center.getId().equals(AccessControlService.ALL_CENTER_CD); + } + + private int toInteger(Long value) { + return Math.toIntExact(value == null ? 0L : value); + } + + private List toHeaders(List headers) { + return headers.stream().map(header -> new ReportResponseDto.Header( + header.getId(), + header.getReportHeaderOrder(), + header.getReportHeaderGroup(), + header.getVariableGroup(), + header.getVariableName(), + header.getReportHeaderLabel())).toList(); + } + + private String toJsonPath(String konQid) { + int separatorIndex = konQid.indexOf('_'); + String parentQid = separatorIndex < 0 ? konQid : konQid.substring(0, separatorIndex); + return "$." + parentQid + "." + konQid; + } + + private List> readRows(MultipartFile file) { + try (var inputStream = file.getInputStream()) { + List> rows = new ArrayList<>(); + ExcelMapper.readStreaming(inputStream, (row, rowNumber) -> rows.add(row)); + return rows; + } catch (Exception exception) { + throw BusinessException.badRequest( + "FINAL_REPORT_FILE_INVALID", "The Excel file could not be read."); + } + } + + private List validateRows( + List> rows, + Set expectedHeaderIds + ) { + if (rows.isEmpty()) { + throw BusinessException.validationError( + "FINAL_REPORT_EMPTY", "Excel must contain at least one data row."); + } + + Set seenCenters = new HashSet<>(); + List result = new ArrayList<>(); + for (int index = 0; index < rows.size(); index++) { + Map row = new LinkedHashMap<>(); + rows.get(index).forEach((key, value) -> row.put(key == null ? "" : key.trim(), value)); + validateHeaders(row.keySet(), expectedHeaderIds); + int rowNumber = index + 2; + int centerCd = parseNonNegativeInteger(row.get(CENTER_CD_HEADER), CENTER_CD_HEADER, rowNumber); + int completeCount = parseNonNegativeInteger( + row.get(COMPLETE_COUNT_HEADER), COMPLETE_COUNT_HEADER, rowNumber); + if (!seenCenters.add(centerCd)) { + throw BusinessException.validationError( + "FINAL_REPORT_CENTER_DUPLICATED", "Center is duplicated in Excel.") + .with("row", rowNumber).with("centerCd", centerCd); + } + + Map values = new LinkedHashMap<>(); + for (Integer headerId : expectedHeaderIds) { + String value = normalizeValue(row.get(String.valueOf(headerId))); + if (value != null && value.length() > 32) { + throw BusinessException.validationError( + "FINAL_REPORT_VALUE_TOO_LONG", "Final Report value exceeds 32 characters.") + .with("row", rowNumber).with("headerId", headerId); + } + values.put(headerId, value); + } + result.add(new ImportRow(centerCd, completeCount, values)); + } + return result; + } + + private void validateHeaders(Set actualHeaders, Set expectedHeaderIds) { + Set expected = expectedHeaderIds.stream() + .map(String::valueOf).collect(Collectors.toCollection(HashSet::new)); + expected.add(CENTER_CD_HEADER); + expected.add(COMPLETE_COUNT_HEADER); + if (!actualHeaders.equals(expected)) { + throw BusinessException.validationError( + "FINAL_REPORT_HEADERS_INVALID", "Excel headers do not match Report header IDs.") + .with("expected", expected).with("actual", actualHeaders); + } + } + + private int parseNonNegativeInteger(String value, String column, int rowNumber) { + try { + int parsed = new BigDecimal(value == null ? "" : value.trim()).intValueExact(); + if (parsed < 0) { + throw new ArithmeticException("negative"); + } + return parsed; + } catch (RuntimeException exception) { + throw BusinessException.validationError( + "FINAL_REPORT_INTEGER_INVALID", "A non-negative integer is required.") + .with("row", rowNumber).with("column", column); + } + } + + private String normalizeValue(String value) { + if (value == null || value.isBlank() || "-".equals(value.trim())) { + return null; + } + return value.trim(); + } + + private record ImportRow(Integer centerCd, Integer completeCount, Map values) { + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/service/SystemEventLogService.java b/src/main/java/com/kri/ksif/manage/back/service/SystemEventLogService.java new file mode 100644 index 0000000..1252dfd --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/SystemEventLogService.java @@ -0,0 +1,112 @@ +package com.kri.ksif.manage.back.service; + +import static com.kri.common.feature.json.JsonUtil.toMap; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.kri.common.feature.datetime.DateTimeUtil; +import com.kri.common.feature.web.RequestUserContext; +import com.kri.ksif.manage.back.common.enums.SystemEventType; +import com.kri.ksif.manage.back.persistence.entity.TSysEventLogEntity; +import com.kri.ksif.manage.back.persistence.repository.SysEventLogRepository; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +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 + ); + } + + public void writeEventLog( + SystemEventType eventType, + String title, + RequestUserContext context, + Map content + ) { + Map contentMap = new LinkedHashMap<>(); + if (content != null) { + contentMap.putAll(content); + } + saveLog( + eventType, + title, + context.getUserId(), + DateTimeUtil.nowKstLocalDateTime(), + context.getClientIp(), + contentMap + ); + } + + 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/java/com/kri/ksif/manage/back/service/TargetCenterService.java b/src/main/java/com/kri/ksif/manage/back/service/TargetCenterService.java new file mode 100644 index 0000000..d317cf9 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/TargetCenterService.java @@ -0,0 +1,31 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.web.BusinessException; +import com.kri.ksif.manage.back.common.auth.AccessControlService; +import com.kri.ksif.manage.back.persistence.repository.CenterRepository; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class TargetCenterService { + private final CenterRepository centerRepository; + + public List validate(List centerCds) { + if (centerCds == null || centerCds.isEmpty()) { + return List.of(); + } + Set unique = new LinkedHashSet<>(centerCds); + if (unique.contains(null) || unique.contains(AccessControlService.ALL_CENTER_CD)) { + throw BusinessException.validationError( + "TARGET_CENTER_INVALID", "Use an empty Center list to target all Centers."); + } + if (centerRepository.countAllByIdIn(unique) != unique.size()) { + throw BusinessException.validationError("TARGET_CENTER_NOT_FOUND", "A target Center was not found."); + } + return List.copyOf(unique); + } +} diff --git a/src/main/java/com/kri/ksif/manage/back/service/UserService.java b/src/main/java/com/kri/ksif/manage/back/service/UserService.java new file mode 100644 index 0000000..a032f16 --- /dev/null +++ b/src/main/java/com/kri/ksif/manage/back/service/UserService.java @@ -0,0 +1,26 @@ +package com.kri.ksif.manage.back.service; + +import com.kri.common.feature.web.BusinessException; +import com.kri.ksif.manage.back.dto.auth.LoginRequestDto; +import com.kri.ksif.manage.back.dto.user.UserDto; +import com.kri.ksif.manage.back.persistence.entity.TUserEntity; +import com.kri.ksif.manage.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/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..01e531b --- /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_ksif_manage?characterEncoding=UTF-8&rewriteBatchedStatements=true + username: prjct_ksif + password: ksif#260820 + 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..139bdb1 --- /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_ksif_manage?characterEncoding=UTF-8&rewriteBatchedStatements=true + username: prjct_ksif + password: ksif#260820 + 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..e70acc9 --- /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_ksif_manage?characterEncoding=UTF-8&rewriteBatchedStatements=true + username: prjct_ksif + password: ksif#260820 + 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..9839535 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,76 @@ +server: + port: 6109 + forward-headers-strategy: framework + +spring: + application: + name: ksif-manage-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: 5MB + max-request-size: 30MB + +logging: + file: + path: ./logs + +kon: + datasource: + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + url: jdbc:sqlserver://1.235.195.8:20022;databaseName=KON;encrypt=false;loginTimeout=5 + username: kon + password: kon#51304 + mybatis: + mapper-locations: classpath*:mybatis/mapper/kon/*.xml + type-aliases-package: com.kri.ksif.manage.back.dto.kon + configuration: + map-underscore-to-camel-case: true + #log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + +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 + swagger: + enabled: true + title: "ksif-manage-back API" + description: "ksif-manage-back Spring Boot application" + version: "v1.0.0" + base-package: "com.kri.ksif.manage.back" + allowed-ips: [] + file: + base-dir: ./upload-file + resource-pattern: /files/** + web: + enabled: true + redis: + enabled: false + scheduling: + enabled: false + diff --git a/src/main/resources/mybatis/mapper/kon/KonMapper.xml b/src/main/resources/mybatis/mapper/kon/KonMapper.xml new file mode 100644 index 0000000..9c77a5f --- /dev/null +++ b/src/main/resources/mybatis/mapper/kon/KonMapper.xml @@ -0,0 +1,182 @@ + + + + + + + +