260908_01_fst: First Commit

This commit is contained in:
2026-09-08 15:33:43 +09:00
commit e2192d8e23
110 changed files with 7531 additions and 0 deletions

21
.agent/profile.yml Normal file
View File

@@ -0,0 +1,21 @@
schema_version: 1
project:
id: k-musical-manage-back
name: "k-musical-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

8
.agent/project.md Normal file
View File

@@ -0,0 +1,8 @@
## 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.
- Use the repository Gradle Wrapper and run `.\gradlew.bat compileJava` followed by focused tests for relevant changes.

7
.gitattributes vendored Normal file
View File

@@ -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

24
.gitignore vendored Normal file
View File

@@ -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

274
AGENTS.md Normal file
View File

@@ -0,0 +1,274 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: k-musical-manage-back
Schema version: 1
Edit the source fragments or repository .agent files, then recompose.
-->
# KRI Development Base Instructions
This document defines the shared working rules for KRI development repositories.
Keep project-specific facts and commands in the project profile and project rules.
## Instruction Resolution
Apply repository instructions in this order:
1. Base rules
2. Project-type rules
3. Technology-stack rules
4. Shared consumer contracts
5. Project-specific rules
6. The explicitly approved task scope
Later and more specific instructions may override earlier general instructions only within their stated scope.
- Apply a shared consumer contract only when `.agent/profile.yml` declares it.
- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files.
- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive.
## Communication
- Respond to the user in Korean unless the user requests another language.
- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form.
- Follow the repository's existing language conventions for code comments and user-facing messages.
- Lead with the result or decision, then provide only the detail needed to verify it.
- Do not create or retain a full session transcript.
## Work Authorization
- The default workflow is discussion first and explicit execution approval second.
- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection.
- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup.
- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state.
- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks.
- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands.
- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope.
- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages.
## Local Development Environment
- Primary OS: Windows 11.
- Primary shell: PowerShell.
- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior.
- Prefer repository-provided wrappers and scripts over globally installed commands.
- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them.
- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration.
- Do not install or modify global toolchains as part of a project task.
Preferred human-facing tools:
- Classic ASP: Visual Studio Code
- Java and Spring Boot: IntelliJ IDEA
- C# and .NET: JetBrains Rider
- JavaScript, TypeScript, and Next.js: JetBrains WebStorm
- Python: JetBrains PyCharm
- Microsoft SQL Server: SQL Server Management Studio
- Other databases: JetBrains DataGrip
- These preferences do not authorize launching or controlling a GUI application.
- Prefer IDE-independent commands that can also run in CI.
- Do not modify global IDE settings.
- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it.
- Preserve existing shared IDE configuration when it is already tracked.
## PowerShell and Path Safety
- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters.
- Prefer `-LiteralPath` when operating on an exact filesystem path.
- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`.
- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations.
- Keep a filesystem operation within one shell from target resolution through execution.
- Before a recursive delete or move, resolve and verify every absolute target.
- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target.
- Prefer recoverable operations when practical.
## Change Discipline
- Preserve all existing user changes, including uncommitted and untracked work.
- Keep changes minimal but complete for the approved objective.
- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring.
- Do not overwrite or revert unrelated changes.
- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely.
- Prefer changing an authoritative source over editing generated output.
- Treat files marked as generated as read-only unless regeneration is part of the approved plan.
- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required.
- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope.
## Text Encoding and Korean Content Safety
- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract.
- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them.
- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text.
- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them.
- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change.
- Avoid whole-file rewrites for small changes.
- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit.
- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding.
- Treat a console display problem and an on-disk encoding problem as separate issues.
- After editing Korean text, inspect the diff for replacement characters (`<60>`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes.
- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding.
- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence.
- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM.
## Git Safety
- Use `git status`, `git diff`, and `git log` for read-only investigation.
- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved.
- Source-edit approval does not include commit or push approval.
- Never amend an existing commit unless explicitly requested.
- Before an approved commit, show the intended files, validation results, and proposed commit message.
- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push.
## Dependencies and External Actions
- Use the package manager, lockfile, and toolchain already selected by the repository.
- Do not install global packages.
- Do not add, remove, or upgrade a dependency unless it was included in the approved plan.
- Pause for approval if an unplanned dependency becomes necessary.
- Keep lockfiles synchronized with approved dependency changes.
- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested.
- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service.
- Remove secrets and unnecessary internal identifiers from external search queries.
## Database Safety
- Treat writing or reviewing SQL as source code separately from executing SQL against a database.
- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope.
- Do not connect to a shared, staging, or production database without explicit authorization for that environment.
- Read-only queries against a non-local database also require authorization because results may contain sensitive data.
- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation.
- Source-change approval does not authorize migration execution.
- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature.
- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output.
## Secrets and Sensitive Data
- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control.
- Read sensitive files only when the approved task requires it and no safer source exists.
- Prefer inspecting configuration keys and schemas without displaying secret values.
- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots.
- Redact sensitive values when reporting errors or command output.
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized.
## 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:<approved-version>` 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.
### Project Instruction Budget
- Keep `.agent/project.md` at or below 9 KiB (9,216 bytes) as the normal target. Do not delete material rules merely to meet the budget; move schema details, query or procedure inventories, API examples, and migration history to linked project documentation, and keep concise read-routing instructions here.
### Upgrade and Verification
- Review KriCommon release notes, README changes, configuration defaults, auto-configuration conditions, and affected public APIs before upgrading.
- Commit dependency-lock or resolved-version changes according to the consumer repository's policy.
- Run the consumer's focused compile and tests after an upgrade, including application-context startup tests when auto-configuration or security behavior is affected.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.
## Generated Spring Boot Repository Rules
- This backend application was generated by `@kri/create-spring-app` with Java 17 and Spring Boot 3.5.7.
- Consume KriCommon through `com.kri.common:starter:beta.1.6.4`; do not change that approved version or duplicate shared behavior without explicit approval.
- The selected primary database is `mysql`. Preserve its configured dialect, driver, transaction, schema, and migration conventions.
- Keep controllers thin and preserve the generated service, DTO, persistence, configuration, QueryDSL, JDBC, and optional MyBatis boundaries.
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
- Use the repository Gradle Wrapper and run `.\gradlew.bat compileJava` followed by focused tests for relevant changes.

1
CLAUDE.md Normal file
View File

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

81
README.md Normal file
View File

@@ -0,0 +1,81 @@
# k-musical-manage-back
k-musical-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: `k-musical-manage-back`
- 프로젝트 유형: `requested-project`
- 권위 원본: `.agent/profile.yml`, `.agent/project.md`
`AGENTS.md`와 `CLAUDE.md`는 중앙 Agent Harness가 합성합니다. 두 파일을 직접 수정하지 않습니다.

107
build.gradle Normal file
View File

@@ -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.kmusical.manage.back'
version = '0.0.1-SNAPSHOT'
description = 'k-musical-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' // 버전은 환경 맞춰 조정
implementation 'org.apache.poi:poi-ooxml:5.5.1'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
def querydslDir = layout.buildDirectory.dir('generated/querydsl').get().asFile
sourceSets {
main.java.srcDirs += [querydslDir]
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
options.generatedSourceOutputDirectory.set(file(querydslDir))
}
tasks.withType(Test).configureEach {
jvmArgs '-Dfile.encoding=UTF-8'
}
tasks.withType(JavaExec).configureEach {
jvmArgs '-Dfile.encoding=UTF-8'
}
tasks.named('test') {
useJUnitPlatform()
}
tasks.named('clean') {
doLast {
delete querydslDir
}
}

5
gradle.properties Normal file
View File

@@ -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

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -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

251
gradlew vendored Normal file
View File

@@ -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" "$@"

94
gradlew.bat vendored Normal file
View File

@@ -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

1
settings.gradle Normal file
View File

@@ -0,0 +1 @@
rootProject.name = 'k-musical-manage-back'

View File

@@ -0,0 +1,14 @@
package com.kri.kmusical.manage.back;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@SpringBootApplication
@ConfigurationPropertiesScan
public class KMusicalManageBackApplication {
public static void main(String[] args) {
SpringApplication.run(KMusicalManageBackApplication.class, args);
}
}

View File

@@ -0,0 +1,15 @@
package com.kri.kmusical.manage.back.common.consts;
import java.util.List;
public class KmusicalConstant {
public static final String SYSTEM_USER_NAME = "SYSTEM";
public static final Integer MONITORING_USER_ROLE = 9003;
public static final Integer MONITORING_REVIEW_TYPE = 1;
public static final Integer CONSULTING_REVIEW_TYPE = 2;
public static final List<Integer> REVIEW_TYPE = List.of(
MONITORING_REVIEW_TYPE,
CONSULTING_REVIEW_TYPE
);
public static final Integer COMPLETE_STATUS = 10;
}

View File

@@ -0,0 +1,42 @@
package com.kri.kmusical.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<Short> {
//1의 자리 1 insert, 2 update, 3 delete, 4 upload
//100의 자리 대분류, 10의 자리 소분류
LOGIN((short) 111), // 로그인
LOGOUT((short) 121), // 로그 아웃
UPDATE_USER((short) 312), // 사용자 수정
DELETE_USER((short) 313), // 사용자 삭제
UPLOAD_USER((short) 314), // 사용자 업로드
UPDATE_PERFORMANCE((short) 1022), //공연 수정
DELETE_PERFORMANCE((short) 1023), //공연 삭제
UPLOAD_PERFORMANCE((short) 1024), //공연 업로드
ASSIGN_PERFORMANCE_REQUEST((short) 1031), //공연 배정 요청
ASSIGN_PERFORMANCE_CONFIRM((short) 1032), //공연 배정 승인
ASSIGN_PERFORMANCE_CANCEL((short) 1033), //공연 배정 거절
ASSIGN_PERFORMANCE_FORCE((short) 1034), //강제 공연 배정
ASSIGN_PERFORMANCE_REJECT((short) 1039), //공연 배정 거절
VISIT_START((short) 2011), //모니터링 출발
VISIT_END((short) 2012), //모니터링 도착
VISIT_RESET((short) 2099), //모니터링 출발.도착 초기화
UPLOAD_REVIEW((short) 2041), //평가 결과 파일 업로드
START_REVIEW((short) 2044), //평가 시작
DUMMY((short) 9999);
private final Short code;
}

View File

@@ -0,0 +1,19 @@
package com.kri.kmusical.manage.back.common.util;
import com.kri.common.feature.excel.ExcelMapper;
import com.kri.kmusical.manage.back.dto.common.CodeDto;
import com.kri.kmusical.manage.back.dto.excel.CodeSheetDto;
import java.util.List;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
@NoArgsConstructor
public final class AppendCodeSheet {
public static void appendCodeSheet(Workbook workbook, List<CodeDto> codeList, String sheetName) {
List<CodeSheetDto> sheetRows = codeList.stream()
.map(CodeSheetDto::from)
.toList();
ExcelMapper.appendSheetToWorkbook(workbook, sheetRows, CodeSheetDto.class, sheetName, 1);
}
}

View File

@@ -0,0 +1,14 @@
package com.kri.kmusical.manage.back.common.util;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public final class DownloadHeaderUtil {
public static String attachmentContentDisposition(String fileName) {
return "attachment; filename*=UTF-8''" +
URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
}
}

View File

@@ -0,0 +1,22 @@
package com.kri.kmusical.manage.back.common.util;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@NoArgsConstructor
public final class ExcelResponseBuilder {
public static ResponseEntity<byte[]> buildExcelResponse(String fileName, byte[] bytes) {
String contentDisposition = "attachment; filename*=UTF-8''" +
URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
}

View File

@@ -0,0 +1,69 @@
package com.kri.kmusical.manage.back.common.util;
import com.kri.common.feature.excel.ExcelMapper;
import com.kri.kmusical.manage.back.dto.excel.ExcelUploadResultDto;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.List;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
@NoArgsConstructor
public final class ExcelUploadResultUtil {
/**
* 엑셀 업로드 결과 + 에러 엑셀 생성까지 공통 처리.
*
* @param totalCount 전체 행 수
* @param successCount 성공 개수
* @param errorList 에러 DTO 리스트
* @param errorClass 에러 DTO 타입 (ExcelMapper용)
* @param errorFileName 에러 엑셀 파일명
*/
public static <E> ExcelUploadResultDto buildUploadResult(
int totalCount,
int successCount,
int failCount,
List<E> errorList,
Class<E> errorClass,
String errorFileName
) {
int errorListCount = (errorList != null) ? errorList.size() : 0;
// 1) 에러가 없으면 파일 없이 반환
if (errorListCount == 0) {
return ExcelUploadResultDto.builder()
.totalCount(totalCount)
.successCount(successCount)
.failCount(0)
.hasErrorFile(false)
.build();
}
// 2) 에러가 있으면 에러 리스트를 엑셀로 생성
try (
Workbook errorWb = ExcelMapper.writeToWorkbook(errorList, errorClass);
ByteArrayOutputStream bos = new ByteArrayOutputStream()
) {
errorWb.write(bos);
byte[] bytes = bos.toByteArray();
return ExcelUploadResultDto.builder()
.totalCount(totalCount)
.successCount(successCount)
.failCount(failCount)
.hasErrorFile(true)
.errorFileName(errorFileName)
.errorFileBase64(Base64.getEncoder().encodeToString(bytes))
.build();
} catch (Exception e) {
// 에러 파일 생성 실패해도 업로드 결과는 그대로 리턴
return ExcelUploadResultDto.builder()
.totalCount(totalCount)
.successCount(successCount)
.failCount(failCount)
.hasErrorFile(false)
.build();
}
}
}

View File

@@ -0,0 +1,58 @@
package com.kri.kmusical.manage.back.common.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public final class MakeExtraFieldMap {
private MakeExtraFieldMap() {
}
public static Map<String, String> toExtraFieldMap(
Object source,
Class<?> targetClass,
Collection<String> ignoreList
) {
Set<String> targetFieldNames = getFieldNames(targetClass);
Set<String> ignoreFieldNames = ignoreList == null
? Set.of()
: new HashSet<>(ignoreList);
Map<String, String> result = new LinkedHashMap<>();
for (Field field : source.getClass().getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())
|| targetFieldNames.contains(field.getName())
|| ignoreFieldNames.contains(field.getName())) {
continue;
}
try {
field.setAccessible(true);
result.put(field.getName(), toDetailValue(field.get(source)));
} catch (IllegalAccessException e) {
throw new IllegalStateException("Failed to read field: " + field.getName(), e);
}
}
return result;
}
private static Set<String> getFieldNames(Class<?> type) {
Set<String> fieldNames = new HashSet<>();
for (Field field : type.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
fieldNames.add(field.getName());
}
}
return fieldNames;
}
private static String toDetailValue(Object value) {
return value == null ? "" : String.valueOf(value);
}
}

View File

@@ -0,0 +1,13 @@
package com.kri.kmusical.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;
}
}

View File

@@ -0,0 +1,41 @@
package com.kri.kmusical.manage.back.common.util;
import com.kri.common.feature.util.StringUtil;
public final class TelUtil {
private TelUtil() {
}
public static String normalizeTel(String value) {
String normalized = StringUtil.normalizeBlank(value);
if (normalized == null) {
return "";
}
normalized = normalized.replace("-", "");
if (!normalized.startsWith("0")) {
normalized = "0" + normalized;
}
return normalized;
}
public static boolean validateTel(String value) {
String normalized = normalizeTel(value);
if (!StringUtil.hasText(normalized) || !normalized.matches("^\\d+$")) {
return false;
}
int length = normalized.length();
if (normalized.startsWith("02")) {
return length >= 9 && length <= 10;
}
if (normalized.startsWith("010")) {
return length == 11;
}
return length >= 10 && length <= 11;
}
}

View File

@@ -0,0 +1,4 @@
/**
* 프로젝트 전용 Bean Validation annotation과 validator를 배치합니다.
*/
package com.kri.kmusical.manage.back.common.validation;

View File

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

View File

@@ -0,0 +1,64 @@
package com.kri.kmusical.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.kmusical.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.kmusical.manage.back.persistence.entity")
.persistenceUnit("main")
.build();
}
@Bean(name = "mainTransactionManager")
@Primary
public PlatformTransactionManager mainTransactionManager(
@Qualifier("mainEntityManagerFactory")
LocalContainerEntityManagerFactoryBean entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory.getObject());
}
}

View File

@@ -0,0 +1,13 @@
package com.kri.kmusical.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 reviewBaseDir;
private String reviewTemplateBaseDir;
}

View File

@@ -0,0 +1,15 @@
package com.kri.kmusical.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);
}
}

View File

@@ -0,0 +1,142 @@
package com.kri.kmusical.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.kmusical.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;
}
}
}

View File

@@ -0,0 +1,19 @@
package com.kri.kmusical.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);
}
}

View File

@@ -0,0 +1,22 @@
package com.kri.kmusical.manage.back.config;
import java.nio.file.Path;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebResourceConfig implements WebMvcConfigurer {
@Value("${kri.file.review-base-dir}")
private String reviewBaseDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// /review-file/** → /data/upload-file/review/** 매핑
registry.addResourceHandler("/review-file/**")
.addResourceLocations("file:" + reviewBaseDir + "/");
}
}

View File

@@ -0,0 +1,103 @@
package com.kri.kmusical.manage.back.controller;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.kmusical.manage.back.dto.assign.AssignUserCountDto;
import com.kri.kmusical.manage.back.dto.assign.MonitoringApplyUserDto;
import com.kri.kmusical.manage.back.dto.assign.PerformanceAssignSaveRequestDto;
import com.kri.kmusical.manage.back.dto.kon.PerformanceApplyCountDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceAssignDto;
import com.kri.kmusical.manage.back.service.AssignService;
import com.kri.kmusical.manage.back.service.common.SystemEventLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/assign")
@RequiredArgsConstructor
@Tag(name = "Assign", description = "배정 API")
public class AssignController {
private final AssignService assignService;
private final SystemEventLogService systemEventLogService;
@Operation(summary = "사용자별 확정 건수 조회")
@GetMapping("/users/count")
public List<AssignUserCountDto> findAssignUserCounts() {
return assignService.findAssignUserCounts();
}
@Operation(summary = "공연별 모니터링 신청자 목록 조회")
@GetMapping("/monitoring/apply-users/{performanceId}")
public List<MonitoringApplyUserDto> findMonitoringApplyUsers(
@PathVariable String performanceId
) {
return assignService.findMonitoringApplyUsers(performanceId);
}
@Operation(summary = "공연별 모니터링 신청자 수 조회")
@GetMapping("/monitoring/apply-users/count")
public List<PerformanceApplyCountDto> findMonitoringApplyUsersCount() {
return assignService.findMonitoringApplyUsersCount();
}
@Operation(summary = "평가 슬롯 담당자 확정 또는 교체")
@PostMapping
public PerformanceAssignDto confirmAssign(
@RequestBody PerformanceAssignSaveRequestDto dto,
RequestUserContext ctx
) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
PerformanceAssignDto result = assignService.confirmAssign(
dto.getPerformanceId(),
dto.getReviewSlot(),
dto.getUserId(),
ctx.getUserId(),
now
);
systemEventLogService.writeAssignConfirmByAdminLog(
ctx.getUserId(),
now,
ctx.getClientIp(),
dto.getPerformanceId(),
dto.getReviewSlot(),
dto.getUserId()
);
return result;
}
@Operation(summary = "평가 슬롯 담당자 확정 취소")
@DeleteMapping("/{performanceId}/{reviewSlot}")
public void cancelAssign(
@PathVariable String performanceId,
@PathVariable Integer reviewSlot,
RequestUserContext ctx
) {
PerformanceAssignDto assign = assignService.findByPerformanceId(performanceId).stream()
.filter(item -> reviewSlot.equals(item.getReviewSlot()))
.findFirst()
.orElse(null);
assignService.cancelAssign(performanceId, reviewSlot);
if (assign != null) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
systemEventLogService.writeAssignCancelLog(
ctx.getUserId(),
now,
ctx.getClientIp(),
performanceId,
reviewSlot,
assign.getAssignUser()
);
}
}
}

View File

@@ -0,0 +1,52 @@
package com.kri.kmusical.manage.back.controller;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.kmusical.manage.back.dto.auth.LoginRequestDto;
import com.kri.kmusical.manage.back.dto.auth.LoginResponseDto;
import com.kri.kmusical.manage.back.service.AuthService;
import com.kri.kmusical.manage.back.service.common.SystemEventLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
@Tag(name = "Auth", description = "인증 API")
public class AuthController {
private final AuthService authService;
private final SystemEventLogService systemEventLogService;
@Operation(summary = "로그인 요청")
@PostMapping("/login")
public LoginResponseDto tryLogin(
@Valid @RequestBody LoginRequestDto request,
RequestUserContext ctx
) {
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
LoginResponseDto response = authService.tryLogin(request);
systemEventLogService.writeLoginLog(response.getUser().getUserId(), now, ctx.getClientIp());
return response;
}
@Operation(summary = "로그아웃 요청")
@PostMapping("/logout/{userId}")
public boolean logout(@PathVariable String userId, RequestUserContext ctx) {
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
systemEventLogService.writeLogoutLog(userId, now, ctx.getClientIp());
return true;
}
}

View File

@@ -0,0 +1,27 @@
package com.kri.kmusical.manage.back.controller;
import com.kri.kmusical.manage.back.dto.common.CodeDto;
import com.kri.kmusical.manage.back.service.CodeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/code")
@RequiredArgsConstructor
@Tag(name = "Code", description = "코드 API")
public class CodeController {
private final CodeService codeService;
@Operation(summary = "코드 조회")
@GetMapping("/{codeGroup}")
public List<CodeDto> getCodeList(@PathVariable String codeGroup) {
return codeService.findByCodeGroup(codeGroup);
}
}

View File

@@ -0,0 +1,122 @@
package com.kri.kmusical.manage.back.controller;
import static com.kri.kmusical.manage.back.common.util.ExcelResponseBuilder.buildExcelResponse;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.kmusical.manage.back.dto.excel.ExcelUploadResultDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceCompactDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceFullDto;
import com.kri.kmusical.manage.back.dto.systemlog.UploadContentDto;
import com.kri.kmusical.manage.back.service.PerformanceService;
import com.kri.kmusical.manage.back.service.common.SystemEventLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/performance")
@RequiredArgsConstructor
@Tag(name = "Performance", description = "Performance API")
public class PerformanceController {
private final SystemEventLogService systemEventLogService;
private final PerformanceService performanceService;
@Operation(summary = "공연 조회")
@GetMapping("/{performanceId}")
public PerformanceFullDto getPerformance(@PathVariable String performanceId) {
return performanceService.getPerformance(performanceId);
}
@Operation(summary = "공연 목록 조회")
@GetMapping("/list")
public List<PerformanceFullDto> getPerformanceList() {
return performanceService.getPerformanceList();
}
@Operation(summary = "공연 목록 조회(간소화된 정보)")
@GetMapping("/list/compact")
public List<PerformanceCompactDto> getPerformanceCompactList() {
return performanceService.getPerformanceCompactList();
}
@Operation(summary = "공연정보 일괄 생성 양식 다운로드")
@PostMapping("/excel/template")
public ResponseEntity<byte[]> exportPerformanceTemplate() {
byte[] bytes = performanceService.exportPerformanceTemplate();
return buildExcelResponse("performance_upload_template.xlsx", bytes);
}
@Operation(summary = "공연정보 엑셀 다운로드")
@PostMapping("/excel/download")
public ResponseEntity<byte[]> exportPerformance(
@RequestBody String[] performanceIds
) {
byte[] bytes = performanceService.exportPerformance(performanceIds);
return buildExcelResponse("performance.xlsx", bytes);
}
@Operation(
summary = "공연 일괄 생성(엑셀 업로드)",
description = "성공하면 JSON, 실패가 있으면 실패 내역 엑셀(xlsx) 반환"
)
@PostMapping(value = "/excel/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ExcelUploadResultDto createPerformanceFromExcel(
@RequestParam("file") MultipartFile file,
RequestUserContext ctx
) {
String regId = ctx.getUserId();
String clientIp = ctx.getClientIp();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
ExcelUploadResultDto result = performanceService.createPerformancesFromExcel(file, regId, now);
systemEventLogService.writeUploadPerformanceLog(regId, now, clientIp, UploadContentDto.from(file, regId));
return result;
}
@Operation(summary = "공연 정보 수정")
@PatchMapping()
public void updatePerformance(
@Valid @RequestBody PerformanceCompactDto dto,
RequestUserContext ctx
) {
String modId = ctx.getUserId();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
performanceService.updatePerformance(dto, modId, now);
systemEventLogService.writeUpdatePerformanceLog(modId, now, ctx.getClientIp(), dto);
}
@Operation(summary = "공연 삭제")
@DeleteMapping("/{performanceId}")
public void deletePerformance(
@PathVariable String performanceId,
RequestUserContext ctx
) {
String delId = ctx.getUserId();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
performanceService.deletePerformance(performanceId, delId);
systemEventLogService.writeDeletePerformanceLog(delId, now, ctx.getClientIp(), performanceId);
}
}

View File

@@ -0,0 +1,120 @@
package com.kri.kmusical.manage.back.controller;
import static com.kri.kmusical.manage.back.common.util.DownloadHeaderUtil.attachmentContentDisposition;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.kmusical.manage.back.dto.performance.PerformanceReviewDto;
import com.kri.kmusical.manage.back.dto.systemlog.UploadContentDto;
import com.kri.kmusical.manage.back.service.ReviewService;
import com.kri.kmusical.manage.back.service.ReviewTemplateService;
import com.kri.kmusical.manage.back.service.common.SystemEventLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/review")
@RequiredArgsConstructor
@Tag(name = "Review", description = "평가 API")
public class ReviewController {
private final ReviewService reviewService;
private final ReviewTemplateService reviewTemplateService;
private final SystemEventLogService systemEventLogService;
@Operation(summary = "평가 파일 업로드")
@PostMapping(value = "/{performanceId}/{reviewSlot}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public PerformanceReviewDto uploadReviewFile(
@PathVariable String performanceId,
@PathVariable Integer reviewSlot,
@RequestParam(required = false) String paramUserId,
@RequestParam("file") MultipartFile file,
RequestUserContext ctx
) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
String userId = paramUserId != null ? paramUserId : ctx.getUserId();
PerformanceReviewDto result = reviewService.uploadReviewFile(performanceId, reviewSlot, file, userId, now);
systemEventLogService.writeUploadReviewFileLog(
ctx.getUserId(),
now,
ctx.getClientIp(),
performanceId,
reviewSlot,
UploadContentDto.from(file, userId)
);
return result;
}
@Operation(summary = "평가 파일 조회")
@GetMapping("/{performanceId}/{reviewSlot}")
public PerformanceReviewDto getReviewFile(
@PathVariable String performanceId,
@PathVariable Integer reviewSlot
) {
return reviewService.getReviewFile(performanceId, reviewSlot);
}
@Operation(summary = "평가 원본 파일 다운로드")
@GetMapping("/download/{performanceId}/{reviewSlot}")
public ResponseEntity<Resource> downloadOriginalFile(
@PathVariable String performanceId,
@PathVariable Integer reviewSlot
) {
return download(reviewService.getOriginalFileResource(performanceId, reviewSlot));
}
@Operation(summary = "PDF 변환 파일 조회/다운로드")
@GetMapping("/pdf/{performanceId}/{reviewSlot}")
public ResponseEntity<Resource> downloadPdfOrOriginalFile(
@PathVariable String performanceId,
@PathVariable Integer reviewSlot
) {
return download(reviewService.getPdfOrOriginalFileResource(performanceId, reviewSlot));
}
@Operation(summary = "평가양식 업로드")
@PostMapping(value = "/template/upload/{reviewType}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadReviewTemplate(
@PathVariable Integer reviewType,
@RequestParam("file") MultipartFile file
) {
return reviewTemplateService.uploadReviewTemplate(reviewType, file);
}
@Operation(summary = "평가양식 다운로드")
@GetMapping("/template/download/{reviewType}")
public ResponseEntity<Resource> downloadReviewTemplate(
@PathVariable Integer reviewType
) {
return download(reviewTemplateService.getReviewTemplateResource(reviewType));
}
@Operation(summary = "평가양식 pdf 다운로드")
@GetMapping("/template/pdf/{reviewType}")
public ResponseEntity<Resource> downloadReviewPdfTemplate(
@PathVariable Integer reviewType
) {
return download(reviewTemplateService.getReviewTemplatePdfResource(reviewType));
}
private ResponseEntity<Resource> download(Resource resource) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, attachmentContentDisposition(resource.getFilename()))
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}

View File

@@ -0,0 +1,118 @@
package com.kri.kmusical.manage.back.controller;
import static com.kri.kmusical.manage.back.common.util.ExcelResponseBuilder.buildExcelResponse;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.kmusical.manage.back.dto.excel.ExcelUploadResultDto;
import com.kri.kmusical.manage.back.dto.systemlog.UploadContentDto;
import com.kri.kmusical.manage.back.dto.user.UserFullDto;
import com.kri.kmusical.manage.back.service.UserService;
import com.kri.kmusical.manage.back.service.common.SystemEventLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/user")
@RequiredArgsConstructor
@Tag(name = "User", description = "사용자 API")
public class UserController {
private final UserService userService;
private final SystemEventLogService systemEventLogService;
@Operation(summary = "사용자 조회")
@GetMapping("{userId}")
public UserFullDto getUser(@PathVariable String userId) {
return userService.getUser(userId);
}
@Operation(summary = "사용자 목록 조회")
@GetMapping("/list/{userRole}")
public List<UserFullDto> getUserList(@PathVariable Integer userRole) {
return userService.getUserList(userRole);
}
@Operation(summary = "사용자 일괄 생성 양식 다운로드")
@PostMapping("/excel/template/{userRole}")
public ResponseEntity<byte[]> exportUserTemplate(
@PathVariable Integer userRole
) {
byte[] bytes = userService.exportUserTemplate(userRole);
return buildExcelResponse("user_upload_template.xlsx", bytes);
}
@Operation(summary = "사용자 엑셀 다운로드")
@PostMapping("/excel/download/{userRole}")
public ResponseEntity<byte[]> exportUser(
@PathVariable Integer userRole,
@RequestBody String[] userIds
) {
byte[] bytes = userService.exportUser(userRole, userIds);
return buildExcelResponse("user.xlsx", bytes);
}
@Operation(
summary = "사용자 일괄 생성(엑셀 업로드)",
description = "성공하면 JSON, 실패가 있으면 실패 내역 엑셀(xlsx) 반환"
)
@PostMapping(value = "/excel/upload/{userRole}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ExcelUploadResultDto createUserFromExcel(
@PathVariable Integer userRole,
@RequestParam("file") MultipartFile file,
RequestUserContext ctx
) {
String regId = ctx.getUserId();
String clientIp = ctx.getClientIp();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
ExcelUploadResultDto result = userService.createUsersFromExcel(userRole, file, regId, now);
systemEventLogService.writeUploadUserLog(regId, now, clientIp, UploadContentDto.from(file, regId));
return result;
}
@Operation(summary = "사용자 정보 수정")
@PatchMapping()
public void updateUser(
@Valid @RequestBody UserFullDto dto,
RequestUserContext ctx
) {
String modId = ctx.getUserId();
String clientIp = ctx.getClientIp();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
userService.updateUser(dto, modId, now);
systemEventLogService.writeUpdateUserLog(modId, now, clientIp, dto);
}
@Operation(summary = "사용자 삭제")
@DeleteMapping("/{userId}")
public void deleteUser(@PathVariable String userId, RequestUserContext ctx) {
String regId = ctx.getUserId();
String clientIp = ctx.getClientIp();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
userService.deleteUser(userId, regId);
systemEventLogService.writeDeleteUserLog(regId, now, clientIp, userId);
}
}

View File

@@ -0,0 +1,16 @@
package com.kri.kmusical.manage.back.dto.assign;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class AssignUserCountDto {
@Schema(description = "배정 사용자 ID")
private String assignUser;
@Schema(description = "배정 건수")
private Long assignCount;
}

View File

@@ -0,0 +1,22 @@
package com.kri.kmusical.manage.back.dto.assign;
import com.kri.kmusical.manage.back.dto.user.UserCompactDto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
@Schema(description = "모니터링 신청자")
public class MonitoringApplyUserDto {
@Schema(description = "공연 ID")
private String performanceId;
@Schema(description = "신청자 ID")
private String userId;
@Schema(description = "서비스 DB 사용자 정보")
private UserCompactDto user;
}

View File

@@ -0,0 +1,19 @@
package com.kri.kmusical.manage.back.dto.assign;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PerformanceAssignSaveRequestDto {
@Schema(description = "공연 ID")
private String performanceId;
@Schema(description = "평가 슬롯")
private Integer reviewSlot;
@Schema(description = "확정할 사용자 ID")
private String userId;
}

View File

@@ -0,0 +1,17 @@
package com.kri.kmusical.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;
}

View File

@@ -0,0 +1,25 @@
package com.kri.kmusical.manage.back.dto.auth;
import com.kri.kmusical.manage.back.dto.user.UserCompactDto;
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 UserCompactDto user;
public static LoginResponseDto from(String accessToken, UserCompactDto user) {
return LoginResponseDto.builder()
.accessToken(accessToken)
.user(user)
.build();
}
}

View File

@@ -0,0 +1,46 @@
package com.kri.kmusical.manage.back.dto.common;
import com.kri.kmusical.manage.back.persistence.entity.TCodeEntity;
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 CodeDto {
@Schema(description = "코드 그룹")
private String codeGroup;
@Schema(description = "코드 값")
private Integer codeValue;
@Schema(description = "코드 그룹 라벨")
private String codeGroupLabel;
@Schema(description = "코드 라벨")
private String codeLabel;
@Schema(description = "메모")
private String memo;
public static CodeDto from(TCodeEntity entity) {
if (entity == null) {
return null;
}
return CodeDto.builder()
.codeGroup(entity.getCodeGroup())
.codeValue(entity.getCodeValue())
.codeGroupLabel(entity.getCodeGroupLabel())
.codeLabel(entity.getCodeLabel())
.memo(entity.getMemo())
.build();
}
}

View File

@@ -0,0 +1,30 @@
package com.kri.kmusical.manage.back.dto.common;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
@AllArgsConstructor
@Schema(description = "데이터 검증에 대한 공용 Dto")
public class DataVerificationDto {
@Schema(description = "데이터 검증 통과 여부")
private boolean success;
@Schema(description = "검증 필드명")
private String fieldName;
@Schema(description = "검증 메시지(error)")
private String errMessage;
public DataVerificationDto() {
this.success = true;
this.fieldName = "";
this.errMessage = "";
}
}

View File

@@ -0,0 +1,34 @@
package com.kri.kmusical.manage.back.dto.excel;
import com.kri.common.feature.excel.ExcelColumn;
import com.kri.kmusical.manage.back.dto.common.CodeDto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CodeSheetDto {
@ExcelColumn(header = "Code", order = 0, width = 10)
private Integer codeValue;
@ExcelColumn(header = "Label", order = 1, width = 20)
private String codeLabel;
public static CodeSheetDto from(CodeDto dto) {
if (dto == null) {
return null;
}
return CodeSheetDto.builder()
.codeValue(dto.getCodeValue())
.codeLabel(dto.getCodeLabel())
.build();
}
}

View File

@@ -0,0 +1,29 @@
package com.kri.kmusical.manage.back.dto.excel;
import com.kri.common.feature.excel.ExcelColumn;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@SuperBuilder
@Getter
@Setter
public class ExcelErrorDto {
@ExcelColumn(header = "행 번호", order = 0)
private int rowNumber;
@ExcelColumn(header = "필드명", order = 1)
private String fieldName;
@ExcelColumn(header = "에러 메시지", order = 2)
private String errorMessage;
public static ExcelErrorDto of(int rowNumber, String fieldName, String errorMessage) {
return ExcelErrorDto.builder()
.rowNumber(rowNumber)
.fieldName(fieldName)
.errorMessage(errorMessage)
.build();
}
}

View File

@@ -0,0 +1,40 @@
package com.kri.kmusical.manage.back.dto.excel;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
public class ExcelUploadResultDto {
@Schema(description = "전체 읽은 행 수 (헤더 제외)")
private int totalCount;
@Schema(description = "DB에 실제로 insert/update 성공한 개수")
private int successCount;
@Schema(description = "실패(에러) 개수")
private int failCount;
@Schema(description = "에러 엑셀 파일이 있는지 여부")
private boolean hasErrorFile;
@Schema(description = "프론트가 저장용으로 쓸 파일명")
private String errorFileName;
@Schema(description = "에러 엑셀 파일 (xlsx)의 Base64 문자열 (hasErrorFile == true일 때만 세팅)")
private String errorFileBase64;
public static ExcelUploadResultDto success(int totalCount, int successCount) {
return ExcelUploadResultDto.builder()
.totalCount(totalCount)
.successCount(successCount)
.failCount(0)
.hasErrorFile(false)
.build();
}
}

View File

@@ -0,0 +1,77 @@
package com.kri.kmusical.manage.back.dto.excel.performance;
import com.kri.common.feature.excel.ExcelColumn;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class PerformanceDownloadDto extends PerformanceUploadDto {
@ExcelColumn(header = "모니터링1 평가자", order = 29, width = 16)
@Schema(description = "모니터링1 평가자")
private String monitoringReviewUser1;
@ExcelColumn(header = "모니터링1 평가 상태", order = 30, width = 16)
@Schema(description = "모니터링1 평가 상태")
private String monitoringReviewStatus1;
@ExcelColumn(header = "모니터링1 평가 일시", order = 31, width = 16)
@Schema(description = "모니터링1 평가 일시")
private String monitoringReviewDt1;
@ExcelColumn(header = "모니터링2 평가자", order = 32, width = 16)
@Schema(description = "모니터링2 평가자")
private String monitoringReviewUser2;
@ExcelColumn(header = "모니터링2 평가 상태", order = 33, width = 16)
@Schema(description = "모니터링2 평가 상태")
private String monitoringReviewStatus2;
@ExcelColumn(header = "모니터링2 평가 일시", order = 34, width = 16)
@Schema(description = "모니터링2 평가 일시")
private String monitoringReviewDt2;
@ExcelColumn(header = "모니터링3 평가자", order = 35, width = 16)
@Schema(description = "모니터링3 평가자")
private String monitoringReviewUser3;
@ExcelColumn(header = "모니터링3 평가 상태", order = 36, width = 16)
@Schema(description = "모니터링3 평가 상태")
private String monitoringReviewStatus3;
@ExcelColumn(header = "모니터링3 평가 일시", order = 37, width = 16)
@Schema(description = "모니터링3 평가 일시")
private String monitoringReviewDt3;
@ExcelColumn(header = "컨설팅1 평가자", order = 38, width = 16)
@Schema(description = "컨설팅1 평가자")
private String consultingReviewUser1;
@ExcelColumn(header = "컨설팅1 평가 상태", order = 39, width = 16)
@Schema(description = "컨설팅1 평가 상태")
private String consultingReviewStatus1;
@ExcelColumn(header = "컨설팅1 평가 일시", order = 40, width = 16)
@Schema(description = "컨설팅1 평가 일시")
private String consultingReviewDt1;
@ExcelColumn(header = "컨설팅2 평가자", order = 41, width = 16)
@Schema(description = "컨설팅2 평가자")
private String consultingReviewUser2;
@ExcelColumn(header = "컨설팅2 평가 상태", order = 42, width = 16)
@Schema(description = "컨설팅2 평가 상태")
private String consultingReviewStatus2;
@ExcelColumn(header = "컨설팅2 평가 일시", order = 43, width = 16)
@Schema(description = "컨설팅2 평가 일시")
private String consultingReviewDt2;
}

View File

@@ -0,0 +1,134 @@
package com.kri.kmusical.manage.back.dto.excel.performance;
import com.kri.common.feature.excel.ExcelColumn;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class PerformanceUploadDto {
@ExcelColumn(header = "NO", order = 0, width = 10)
@Schema(description = "NO")
private String performanceNo;
@ExcelColumn(header = "연번", order = 1, width = 10)
@Schema(description = "연번")
private String performanceId;
@ExcelColumn(header = "사업유형", order = 2, width = 10)
@Schema(description = "사업유형")
private String businessType;
@ExcelColumn(header = "지역", order = 3, width = 10)
@Schema(description = "지역")
private String performanceArea;
@ExcelColumn(header = "지역 세부", order = 4, width = 10)
@Schema(description = "지역 세부")
private String performanceAreaDetail;
@ExcelColumn(header = "단체명", order = 5, width = 11)
@Schema(description = "단체명")
private String artistName;
@ExcelColumn(header = "작품명", order = 6, width = 10)
@Schema(description = "작품명")
private String performanceName;
@ExcelColumn(header = "사업 수행 월", order = 7, width = 12)
@Schema(description = "사업 수행 월")
private String performanceStartMonth;
@ExcelColumn(header = "사업 일정", order = 8, width = 10)
@Schema(description = "사업 일정")
private String performanceDtInfo;
@ExcelColumn(header = "운영 시간", order = 9, width = 10)
@Schema(description = "운영 시간")
private String performanceTimeInfo;
@ExcelColumn(header = "티켓 예약", order = 10, width = 10)
@Schema(description = "티켓 예약")
private String ticketReservationStatus;
@ExcelColumn(header = "티켓 비고", order = 11, width = 10)
@Schema(description = "티켓 비고")
private String ticketReservationMemo;
@ExcelColumn(header = "모니터링 일정", order = 12, width = 14)
@Schema(description = "모니터링 일정")
private String monitoringDate;
@ExcelColumn(header = "모니터링 시간", order = 13, width = 14)
@Schema(description = "모니터링 시간")
private String monitoringTimeInfo;
@ExcelColumn(header = "모니터링 방문장소", order = 14, width = 14)
@Schema(description = "모니터링 방문장소")
private String monitoringAddress;
@ExcelColumn(header = "컨설팅 진행여부", order = 15, width = 14)
@Schema(description = "컨설팅 진행여부")
private String consultingStatus;
@ExcelColumn(header = "교부여부", order = 16, width = 14)
@Schema(description = "교부여부")
private String checkDeliver;
@ExcelColumn(header = "메모", order = 17, width = 10)
@Schema(description = "메모")
private String performanceMemo;
@ExcelColumn(header = "보고서 확인여부", order = 18, width = 10)
@Schema(description = "보고서 확인여부")
private String checkReport;
@ExcelColumn(header = "요원 비용지급일", order = 19, width = 16)
@Schema(description = "요원 비용지급일")
private String monitoringPaymentDate;
@ExcelColumn(header = "대표자 명", order = 20, width = 10)
@Schema(description = "대표자 명")
private String ownStaffName;
@ExcelColumn(header = "대표자 연락처1", order = 21, width = 14)
@Schema(description = "대표자 연락처1")
private String ownStaffTel1;
@ExcelColumn(header = "대표자 연락처2", order = 22, width = 14)
@Schema(description = "대표자 연락처2")
private String ownStaffTel2;
@ExcelColumn(header = "대표자 이메일", order = 23, width = 14)
@Schema(description = "대표자 이메일")
private String ownStaffEmail;
@ExcelColumn(header = "실무자 명", order = 24, width = 10)
@Schema(description = "실무자 명")
private String contactStaffName;
@ExcelColumn(header = "실무자 연락처1", order = 25, width = 14)
@Schema(description = "실무자 연락처1")
private String contactStaffTel1;
@ExcelColumn(header = "실무자 연락처2", order = 26, width = 14)
@Schema(description = "실무자 연락처2")
private String contactStaffTel2;
@ExcelColumn(header = "실무자 이메일", order = 27, width = 14)
@Schema(description = "실무자 이메일")
private String contactStaffEmail;
@ExcelColumn(header = "예경 담당자 명", order = 28, width = 14)
@Schema(description = "예경 담당자 명")
private String clientManagerName;
}

View File

@@ -0,0 +1,49 @@
package com.kri.kmusical.manage.back.dto.excel.user;
import com.kri.common.feature.excel.ExcelColumn;
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 MonitoringUserUploadDto implements UserUploadBaseDto {
@ExcelColumn(header = "사용자 ID", order = 0, width = 11)
@Schema(description = "사용자 ID")
private String userId;
@ExcelColumn(header = "사용자 PW", order = 1, width = 11)
@Schema(description = "사용자 PW")
private String userPw;
@ExcelColumn(header = "사용자 이름", order = 2, width = 11)
@Schema(description = "사용자 이름")
private String userName;
@ExcelColumn(header = "소속", order = 3, width = 11)
@Schema(description = "소속")
private String userCmpn;
@ExcelColumn(header = "직급", order = 4, width = 11)
@Schema(description = "직급")
private String userGrade;
@ExcelColumn(header = "사용자 연락처", order = 5, width = 14)
@Schema(description = "사용자 연락처")
private String userTel;
@ExcelColumn(header = "사용자 이메일", order = 6, width = 14)
@Schema(description = "사용자 이메일")
private String userEmail;
@ExcelColumn(header = "메모", order = 7, width = 20)
@Schema(description = "메모")
private String memo;
}

View File

@@ -0,0 +1,12 @@
package com.kri.kmusical.manage.back.dto.excel.user;
public interface UserUploadBaseDto {
String getUserId();
String getUserPw();
String getUserName();
String getMemo();
}

View File

@@ -0,0 +1,17 @@
package com.kri.kmusical.manage.back.dto.kon;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "KON 공연 신청 수")
public class PerformanceApplyCountDto {
@Schema(description = "공연 ID")
private String performanceId;
@Schema(description = "신청 수")
private Long applyCnt;
}

View File

@@ -0,0 +1,18 @@
package com.kri.kmusical.manage.back.dto.kon;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "KON 공연 신청 자")
public class PerformanceApplyUserDto {
@Schema(description = "공연 ID")
private String performanceId;
@Schema(description = "신청자 ID")
private String userId;
}

View File

@@ -0,0 +1,42 @@
package com.kri.kmusical.manage.back.dto.performance;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceAssignEntity;
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 PerformanceAssignDto {
@Schema(description = "사업고유id")
private String performanceId;
@Schema(description = "평가 슬롯")
private Integer reviewSlot;
@Schema(description = "사용자 id")
private String assignUser;
@Schema(description = "사용자 컨펌 여부")
private Short assignStatus;
public static PerformanceAssignDto from(TPerformanceAssignEntity entity) {
if (entity == null) {
return null;
}
return PerformanceAssignDto.builder()
.performanceId(entity.getId().getPerformanceId())
.reviewSlot(entity.getId().getReviewSlot())
.assignUser(entity.getAssignUser())
.assignStatus(entity.getAssignStatus())
.build();
}
}

View File

@@ -0,0 +1,73 @@
package com.kri.kmusical.manage.back.dto.performance;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class PerformanceBaseDto {
@Schema(description = "사업고유id")
private String performanceId;
@Schema(description = "사업유형")
private Integer businessType;
@Schema(description = "분야(장르)")
private Integer performanceGenre;
@Schema(description = "시도")
private Integer performanceArea;
@Schema(description = "단체(인) 명")
private String artistName;
@Schema(description = "사업 명")
private String performanceName;
@Schema(description = "사업 수행 월")
private Integer performanceStartMonth;
@Schema(description = "사업 일정 정보")
private String performanceDtInfo;
@Schema(description = "운영 시간 정보")
private String performanceTimeInfo;
@Schema(description = "티켓 예약")
private Integer ticketReservationStatus;
@Schema(description = "티켓 비고")
private String ticketReservationMemo;
@Schema(description = "메모")
private String performanceMemo;
public static PerformanceBaseDto from(TPerformanceEntity entity) {
if (entity == null) {
return null;
}
return PerformanceBaseDto.builder()
.performanceId(entity.getPerformanceId())
.businessType(entity.getBusinessType())
.performanceArea(entity.getPerformanceArea())
.artistName(entity.getArtistName())
.performanceName(entity.getPerformanceName())
.performanceStartMonth(entity.getPerformanceStartMonth())
.performanceDtInfo(entity.getPerformanceDtInfo())
.performanceTimeInfo(entity.getPerformanceTimeInfo())
.ticketReservationStatus(entity.getTicketReservationStatus())
.ticketReservationMemo(entity.getTicketReservationMemo())
.performanceMemo(entity.getPerformanceMemo())
.build();
}
}

View File

@@ -0,0 +1,72 @@
package com.kri.kmusical.manage.back.dto.performance;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class PerformanceCompactDto extends PerformanceBaseDto {
@Schema(description = "공연 상세 정보")
private Map<String, String> performanceDetail;
@Schema(description = "공연 관계자 정보")
private List<PerformanceStaffDto> performanceStaff;
@Schema(description = "공연 방문 일정 정보")
private PerformanceMonitoringScheduleDto performanceMonitoringSchedule;
public static PerformanceCompactDto from(
TPerformanceEntity performance,
Map<String, String> performanceDetail,
List<PerformanceStaffDto> performanceStaff,
PerformanceMonitoringScheduleDto performanceMonitoringSchedule
) {
return of(
PerformanceBaseDto.from(performance),
performanceDetail,
performanceStaff,
performanceMonitoringSchedule
);
}
public static PerformanceCompactDto of(
PerformanceBaseDto performance,
Map<String, String> performanceDetail,
List<PerformanceStaffDto> performanceStaff,
PerformanceMonitoringScheduleDto performanceMonitoringSchedule
) {
if (performance == null) {
return null;
}
return PerformanceCompactDto.builder()
.performanceId(performance.getPerformanceId())
.businessType(performance.getBusinessType())
.performanceGenre(performance.getPerformanceGenre())
.performanceArea(performance.getPerformanceArea())
.artistName(performance.getArtistName())
.performanceName(performance.getPerformanceName())
.performanceStartMonth(performance.getPerformanceStartMonth())
.performanceDtInfo(performance.getPerformanceDtInfo())
.performanceTimeInfo(performance.getPerformanceTimeInfo())
.ticketReservationStatus(performance.getTicketReservationStatus())
.ticketReservationMemo(performance.getTicketReservationMemo())
.performanceMemo(performance.getPerformanceMemo())
.performanceDetail(performanceDetail)
.performanceStaff(performanceStaff)
.performanceMonitoringSchedule(performanceMonitoringSchedule)
.build();
}
}

View File

@@ -0,0 +1,85 @@
package com.kri.kmusical.manage.back.dto.performance;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class PerformanceFullDto extends PerformanceBaseDto {
@Schema(description = "공연 상세 정보")
private Map<String, String> performanceDetail;
@Schema(description = "공연 관계자 정보")
private List<PerformanceStaffDto> performanceStaff;
@Schema(description = "공연 방문 일정 정보")
private PerformanceMonitoringScheduleDto performanceMonitoringSchedule;
@Schema(description = "공연 배정 정보")
private List<PerformanceAssignDto> performanceAssignList;
@Schema(description = "평가 슬롯별 평가 정보")
private Map<Integer, PerformanceReviewDto> performanceReviewMap;
public static PerformanceFullDto from(
TPerformanceEntity performance,
Map<String, String> performanceDetail,
List<PerformanceStaffDto> performanceStaff,
PerformanceMonitoringScheduleDto performanceMonitoringSchedule,
List<PerformanceAssignDto> performanceAssignList,
Map<Integer, PerformanceReviewDto> performanceReviewMap
) {
return of(
PerformanceBaseDto.from(performance),
performanceDetail,
performanceStaff,
performanceMonitoringSchedule,
performanceAssignList,
performanceReviewMap
);
}
public static PerformanceFullDto of(
PerformanceBaseDto performance,
Map<String, String> performanceDetail,
List<PerformanceStaffDto> performanceStaff,
PerformanceMonitoringScheduleDto performanceMonitoringSchedule,
List<PerformanceAssignDto> performanceAssignList,
Map<Integer, PerformanceReviewDto> performanceReviewMap
) {
if (performance == null) {
return null;
}
return PerformanceFullDto.builder()
.performanceId(performance.getPerformanceId())
.businessType(performance.getBusinessType())
.performanceGenre(performance.getPerformanceGenre())
.performanceArea(performance.getPerformanceArea())
.artistName(performance.getArtistName())
.performanceName(performance.getPerformanceName())
.performanceStartMonth(performance.getPerformanceStartMonth())
.performanceDtInfo(performance.getPerformanceDtInfo())
.performanceTimeInfo(performance.getPerformanceTimeInfo())
.ticketReservationStatus(performance.getTicketReservationStatus())
.ticketReservationMemo(performance.getTicketReservationMemo())
.performanceMemo(performance.getPerformanceMemo())
.performanceDetail(performanceDetail)
.performanceStaff(performanceStaff)
.performanceMonitoringSchedule(performanceMonitoringSchedule)
.performanceAssignList(performanceAssignList)
.performanceReviewMap(performanceReviewMap)
.build();
}
}

View File

@@ -0,0 +1,48 @@
package com.kri.kmusical.manage.back.dto.performance;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceMonitoringScheduleEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDate;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PerformanceMonitoringScheduleDto {
@Schema(description = "사업 방문 스케쥴 인덱스")
private Long id;
@Schema(description = "사업고유id")
private String performanceId;
@Schema(description = "모니터링 일정")
private LocalDate monitoringDate;
@Schema(description = "모니터링 시간")
private String monitoringTimeInfo;
@Schema(description = "모니터링 방문 장소 주소")
private String monitoringAddress;
public static PerformanceMonitoringScheduleDto from(TPerformanceMonitoringScheduleEntity entity) {
if (entity == null) {
return null;
}
return PerformanceMonitoringScheduleDto.builder()
.id(entity.getId())
.performanceId(entity.getPerformanceId())
.monitoringDate(entity.getMonitoringDate())
.monitoringTimeInfo(entity.getMonitoringTimeInfo())
.monitoringAddress(entity.getMonitoringAddress())
.build();
}
}

View File

@@ -0,0 +1,61 @@
package com.kri.kmusical.manage.back.dto.performance;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceReviewEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PerformanceReviewDto {
@Schema(description = "사업고유id")
private String performanceId;
@Schema(description = "평가 슬롯")
private Integer reviewSlot;
@Schema(description = "등록 사용자")
private String regUser;
@Schema(description = "평가 일시")
private LocalDateTime reviewDt;
@Schema(description = "평가 상태")
private Integer reviewStatus;
@Schema(description = "업로드 파일명")
private String uploadFileName;
@Schema(description = "pdf로 변환성공 여부")
private Short pdfConvert;
@Schema(description = "pdf로 변환된 파일명")
private String pdfFileName;
public static PerformanceReviewDto from(TPerformanceReviewEntity entity) {
if (entity == null) {
return null;
}
LocalDateTime reviewDt = entity.getModDt() != null ? entity.getModDt() : entity.getRegDt();
return PerformanceReviewDto.builder()
.performanceId(entity.getPerformanceId())
.reviewSlot(entity.getReviewSlot())
.regUser(entity.getRegUser())
.reviewDt(reviewDt)
.reviewStatus(entity.getReviewStatus())
.uploadFileName(entity.getUploadFileName())
.pdfConvert(entity.getPdfConvert())
.pdfFileName(entity.getPdfFileName())
.build();
}
}

View File

@@ -0,0 +1,32 @@
package com.kri.kmusical.manage.back.dto.performance;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceReviewSlotEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PerformanceReviewSlotDto {
@Schema(description = "평가 슬롯")
private Integer reviewSlot;
@Schema(description = "평가 타입")
private Integer reviewType;
public static PerformanceReviewSlotDto from(TPerformanceReviewSlotEntity entity) {
return PerformanceReviewSlotDto.builder()
.reviewSlot(entity.getReviewSlot())
.reviewType(entity.getReviewType())
.build();
}
}

View File

@@ -0,0 +1,55 @@
package com.kri.kmusical.manage.back.dto.performance;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceStaffEntity;
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 PerformanceStaffDto {
@Schema(description = "사업 관계자 인덱스")
private Long id;
@Schema(description = "사업고유id")
private String performanceId;
@Schema(description = "관계자 타입")
private Integer staffType;
@Schema(description = "관계자 이름")
private String staffName;
@Schema(description = "관계자 연락처1")
private String staffTel1;
@Schema(description = "관계자 연락처2")
private String staffTel2;
@Schema(description = "관계자 이메일")
private String staffEmail;
public static PerformanceStaffDto from(TPerformanceStaffEntity entity) {
if (entity == null) {
return null;
}
return PerformanceStaffDto.builder()
.id(entity.getId())
.performanceId(entity.getPerformanceId())
.staffType(entity.getStaffType())
.staffName(entity.getStaffName())
.staffTel1(entity.getStaffTel1())
.staffTel2(entity.getStaffTel2())
.staffEmail(entity.getStaffEmail())
.build();
}
}

View File

@@ -0,0 +1,30 @@
package com.kri.kmusical.manage.back.dto.systemlog;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.web.multipart.MultipartFile;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UploadContentDto {
String fileName;
String fileType;
Long fileSize;
String uploadUserId;
public static UploadContentDto from(MultipartFile file, String uploadUserId){
return UploadContentDto.builder()
.fileName(file.getOriginalFilename())
.fileType(file.getContentType())
.fileSize(file.getSize())
.uploadUserId(uploadUserId)
.build();
}
}

View File

@@ -0,0 +1,51 @@
package com.kri.kmusical.manage.back.dto.user;
import com.kri.kmusical.manage.back.persistence.entity.TUserEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserCompactDto {
@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 Map<String, String> userDetail;
public static UserCompactDto from(TUserEntity entity, Map<String, String> userDetail) {
if (entity == null) {
return null;
}
return UserCompactDto.builder()
.userId(entity.getUserId())
.userName(entity.getUserName())
.userCmpn(entity.getUserCmpn())
.userTeam(entity.getUserTeam())
.userRole(entity.getUserRole())
.userDetail(userDetail)
.build();
}
}

View File

@@ -0,0 +1,83 @@
package com.kri.kmusical.manage.back.dto.user;
import static com.kri.kmusical.manage.back.common.util.MakeExtraFieldMap.toExtraFieldMap;
import com.kri.kmusical.manage.back.dto.excel.user.UserUploadBaseDto;
import com.kri.kmusical.manage.back.persistence.entity.TUserEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Collection;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserFullDto {
@Schema(description = "사용자 ID")
private String userId;
@Schema(description = "PW")
private String userPw;
@Schema(description = "이름")
private String userName;
@Schema(description = "소속 회사")
private String userCmpn;
@Schema(description = "팀")
private String userTeam;
@Schema(description = "권한")
private Integer userRole;
@Schema(description = "메모")
private String memo;
@Schema(description = "사용자 상세 정보")
private Map<String, String> userDetail;
public static UserFullDto from(TUserEntity entity, Map<String, String> userDetail) {
if (entity == null) {
return null;
}
return UserFullDto.builder()
.userId(entity.getUserId())
.userPw(entity.getUserPw())
.userName(entity.getUserName())
.userCmpn(entity.getUserCmpn())
.userTeam(entity.getUserTeam())
.userRole(entity.getUserRole())
.memo(entity.getMemo())
.userDetail(userDetail)
.build();
}
public static UserFullDto from(
UserUploadBaseDto dto,
Integer userRole,
Collection<String> ignoreList
) {
Map<String, String> userDetail = toExtraFieldMap(dto, UserFullDto.class, ignoreList);
return UserFullDto.builder()
.userId(dto.getUserId())
.userPw(dto.getUserPw())
.userName(dto.getUserName())
.userCmpn("")
.userTeam("")
.userRole(userRole)
.memo(dto.getMemo())
.userDetail(userDetail)
.build();
}
}

View File

@@ -0,0 +1,67 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.dto.common.CodeDto;
import com.kri.kmusical.manage.back.persistence.entity.id.TCodeEntityId;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Lob;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_code")
public class TCodeEntity {
@EmbeddedId
private TCodeEntityId id;
@Size(max = 64)
@NotNull
@Column(name = "code_group_label", nullable = false, length = 64)
private String codeGroupLabel;
@Size(max = 2048)
@NotNull
@Column(name = "code_label", nullable = false, length = 2048)
private String codeLabel;
@NotNull
@Lob
@Column(name = "memo", nullable = false)
private String memo;
public String getCodeGroup() {
return id.getCodeGroup();
}
public Integer getCodeValue() {
return id.getCodeValue();
}
public static TCodeEntity from(CodeDto dto) {
if (dto == null) {
return null;
}
TCodeEntity entity = new TCodeEntity();
entity.setId(TCodeEntityId.builder()
.codeGroup(dto.getCodeGroup())
.codeValue(dto.getCodeValue())
.build());
entity.setCodeGroupLabel(dto.getCodeGroupLabel());
entity.setCodeLabel(dto.getCodeLabel());
entity.setMemo(dto.getMemo());
return entity;
}
}

View File

@@ -0,0 +1,65 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.dto.performance.PerformanceAssignDto;
import com.kri.kmusical.manage.back.persistence.entity.id.TPerformanceAssignEntityId;
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_performance_assign")
public class TPerformanceAssignEntity {
@EmbeddedId
private TPerformanceAssignEntityId id;
@Size(max = 32)
@NotNull
@Column(name = "assign_user", nullable = false, length = 32)
private String assignUser;
@NotNull
@ColumnDefault("0")
@Column(name = "assign_status", nullable = false)
private Short assignStatus;
@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 String getPerformanceId() {
return id.getPerformanceId();
}
public Integer getReviewSlot() {
return id.getReviewSlot();
}
public static TPerformanceAssignEntity from(PerformanceAssignDto dto) {
if (dto == null) {
return null;
}
TPerformanceAssignEntity entity = new TPerformanceAssignEntity();
entity.setId(new TPerformanceAssignEntityId(dto.getPerformanceId(), dto.getReviewSlot()));
entity.setAssignUser(dto.getAssignUser());
entity.setAssignStatus(dto.getAssignStatus());
return entity;
}
}

View File

@@ -0,0 +1,77 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.persistence.entity.id.TPerformanceDetailEntityId;
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.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_performance_detail")
public class TPerformanceDetailEntity {
@EmbeddedId
private TPerformanceDetailEntityId id;
@Size(max = 2048)
@NotNull
@Column(name = "performance_detail_value", nullable = false, length = 2048)
private String performanceDetailValue;
@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;
public String getPerformanceId() {
return id.getPerformanceId();
}
public String getPerformanceDetailKey() {
return id.getPerformanceDetailKey();
}
public static TPerformanceDetailEntity update(
String performanceId,
String performanceDetailKey,
String performanceDetailValue,
String modUser,
LocalDateTime modDt
) {
return TPerformanceDetailEntity.builder()
.id(TPerformanceDetailEntityId.builder()
.performanceId(performanceId)
.performanceDetailKey(performanceDetailKey)
.build())
.performanceDetailValue(performanceDetailValue)
.regUser(modUser)
.regDt(modDt)
.modUser(modUser)
.modDt(modDt)
.build();
}
}

View File

@@ -0,0 +1,133 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.dto.performance.PerformanceBaseDto;
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.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_performance")
public class TPerformanceEntity {
@Id
@Size(max = 32)
@Column(name = "performance_id", nullable = false, length = 32)
private String performanceId;
@NotNull
@Column(name = "performance_no", nullable = false)
private Integer performanceNo;
@NotNull
@Column(name = "business_type", nullable = false)
private Integer businessType;
@NotNull
@Column(name = "performance_area", nullable = false)
private Integer performanceArea;
@Size(max = 128)
@NotNull
@Column(name = "artist_name", nullable = false, length = 128)
private String artistName;
@Size(max = 128)
@NotNull
@Column(name = "performance_name", nullable = false, length = 128)
private String performanceName;
@NotNull
@Column(name = "performance_start_month", nullable = false)
private Integer performanceStartMonth;
@Size(max = 256)
@NotNull
@Column(name = "performance_dt_info", nullable = false, length = 256)
private String performanceDtInfo;
@Size(max = 256)
@NotNull
@Column(name = "performance_time_info", nullable = false, length = 256)
private String performanceTimeInfo;
@NotNull
@Column(name = "ticket_reservation_status", nullable = false)
private Integer ticketReservationStatus;
@NotNull
@Lob
@Column(name = "ticket_reservation_memo", nullable = false)
private String ticketReservationMemo;
@NotNull
@Lob
@Column(name = "performance_memo", nullable = false)
private String performanceMemo;
@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;
public static TPerformanceEntity from(PerformanceBaseDto dto) {
if (dto == null) {
return null;
}
TPerformanceEntity entity = new TPerformanceEntity();
entity.setPerformanceId(dto.getPerformanceId());
entity.setBusinessType(dto.getBusinessType());
entity.setPerformanceArea(dto.getPerformanceArea());
entity.setArtistName(dto.getArtistName());
entity.setPerformanceName(dto.getPerformanceName());
entity.setPerformanceStartMonth(dto.getPerformanceStartMonth());
entity.setPerformanceDtInfo(dto.getPerformanceDtInfo());
entity.setPerformanceTimeInfo(dto.getPerformanceTimeInfo());
entity.setTicketReservationStatus(dto.getTicketReservationStatus());
entity.setTicketReservationMemo(dto.getTicketReservationMemo());
entity.setPerformanceMemo(dto.getPerformanceMemo());
return entity;
}
public void updateFromDto(PerformanceBaseDto dto, String modUser, LocalDateTime modDt) {
this.businessType = dto.getBusinessType();
this.performanceArea = dto.getPerformanceArea();
this.artistName = dto.getArtistName();
this.performanceName = dto.getPerformanceName();
this.performanceStartMonth = dto.getPerformanceStartMonth();
this.performanceDtInfo = dto.getPerformanceDtInfo();
this.performanceTimeInfo = dto.getPerformanceTimeInfo();
this.ticketReservationStatus = dto.getTicketReservationStatus();
this.ticketReservationMemo = dto.getTicketReservationMemo();
this.performanceMemo = dto.getPerformanceMemo();
this.modUser = modUser;
this.modDt = modDt;
}
}

View File

@@ -0,0 +1,94 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.dto.performance.PerformanceMonitoringScheduleDto;
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.time.LocalDate;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_performance_monitoring_schedule")
public class TPerformanceMonitoringScheduleEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "performance_monitoring_schedule_idx", nullable = false)
private Long id;
@Size(max = 32)
@NotNull
@Column(name = "performance_id", nullable = false, length = 32)
private String performanceId;
@Column(name = "monitoring_date")
private LocalDate monitoringDate;
@Size(max = 256)
@NotNull
@Column(name = "monitoring_time_info", nullable = false, length = 256)
private String monitoringTimeInfo;
@Size(max = 2048)
@NotNull
@Column(name = "monitoring_address", nullable = false, length = 2048)
private String monitoringAddress;
@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;
public static TPerformanceMonitoringScheduleEntity from(PerformanceMonitoringScheduleDto dto) {
if (dto == null) {
return null;
}
TPerformanceMonitoringScheduleEntity entity = new TPerformanceMonitoringScheduleEntity();
entity.setId(dto.getId());
entity.setPerformanceId(dto.getPerformanceId());
entity.setMonitoringDate(dto.getMonitoringDate());
entity.setMonitoringTimeInfo(dto.getMonitoringTimeInfo());
entity.setMonitoringAddress(dto.getMonitoringAddress());
return entity;
}
public void updateFromDto(
PerformanceMonitoringScheduleDto dto,
String modUser,
LocalDateTime modDt
) {
this.monitoringDate = dto.getMonitoringDate();
this.monitoringTimeInfo = dto.getMonitoringTimeInfo();
this.monitoringAddress = dto.getMonitoringAddress();
this.modUser = modUser;
this.modDt = modDt;
}
}

View File

@@ -0,0 +1,92 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.dto.performance.PerformanceReviewDto;
import com.kri.kmusical.manage.back.persistence.entity.id.TPerformanceReviewEntityId;
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.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_performance_review")
public class TPerformanceReviewEntity {
@EmbeddedId
private TPerformanceReviewEntityId id;
@NotNull
@Column(name = "review_status", nullable = false)
private Integer reviewStatus;
@Size(max = 512)
@NotNull
@Column(name = "upload_file_name", nullable = false, length = 512)
private String uploadFileName;
@NotNull
@Column(name = "is_pdf_convert", nullable = false)
private Short pdfConvert;
@Size(max = 512)
@NotNull
@Column(name = "pdf_file_name", nullable = false, length = 512)
private String pdfFileName;
@Column(name = "pdf_convert_dt")
private LocalDateTime pdfConvertDt;
@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;
public String getPerformanceId() {
return id.getPerformanceId();
}
public Integer getReviewSlot() {
return id.getReviewSlot();
}
public static TPerformanceReviewEntity from(PerformanceReviewDto dto) {
if (dto == null) {
return null;
}
TPerformanceReviewEntity entity = new TPerformanceReviewEntity();
entity.setId(TPerformanceReviewEntityId.builder()
.performanceId(dto.getPerformanceId())
.reviewSlot(dto.getReviewSlot())
.build());
entity.setReviewStatus(dto.getReviewStatus());
entity.setUploadFileName(dto.getUploadFileName());
entity.setPdfConvert(dto.getPdfConvert());
entity.setPdfFileName(dto.getPdfFileName());
return entity;
}
}

View File

@@ -0,0 +1,38 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.dto.performance.PerformanceReviewSlotDto;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_performance_review_slot")
public class TPerformanceReviewSlotEntity {
@Id
@Column(name = "review_slot", nullable = false)
private Integer reviewSlot;
@NotNull
@Column(name = "review_type", nullable = false)
private Integer reviewType;
public static TPerformanceReviewSlotEntity from(PerformanceReviewSlotDto dto) {
return TPerformanceReviewSlotEntity.builder()
.reviewSlot(dto.getReviewSlot())
.reviewType(dto.getReviewType())
.build();
}
}

View File

@@ -0,0 +1,91 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.dto.performance.PerformanceStaffDto;
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.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_performance_staff")
public class TPerformanceStaffEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "performance_staff_idx", nullable = false)
private Long id;
@Size(max = 32)
@NotNull
@Column(name = "performance_id", nullable = false, length = 32)
private String performanceId;
@NotNull
@Column(name = "staff_type", nullable = false)
private Integer staffType;
@Size(max = 32)
@NotNull
@Column(name = "staff_name", nullable = false, length = 32)
private String staffName;
@Size(max = 32)
@Column(name = "staff_tel1", length = 32)
private String staffTel1;
@Size(max = 32)
@Column(name = "staff_tel2", length = 32)
private String staffTel2;
@Size(max = 128)
@Column(name = "staff_email", length = 128)
private String staffEmail;
@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;
public static TPerformanceStaffEntity from(PerformanceStaffDto dto) {
if (dto == null) {
return null;
}
TPerformanceStaffEntity entity = new TPerformanceStaffEntity();
entity.setId(dto.getId());
entity.setPerformanceId(dto.getPerformanceId());
entity.setStaffType(dto.getStaffType());
entity.setStaffName(dto.getStaffName());
entity.setStaffTel1(dto.getStaffTel1());
entity.setStaffTel2(dto.getStaffTel2());
entity.setStaffEmail(dto.getStaffEmail());
return entity;
}
}

View File

@@ -0,0 +1,81 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.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<String, Object> 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<String, Object> logContent,
String clientIp,
String regId,
LocalDateTime regDt
) {
return TSysEventLogEntity.builder()
.eventTy(eventType.getCode())
.logTitle(title)
.logContent(logContent)
.ip(clientIp)
.regUser(regId)
.regDt(regDt)
.build();
}
}

View File

@@ -0,0 +1,95 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.persistence.entity.id.TUserDetailEntityId;
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.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_user_detail")
public class TUserDetailEntity {
@EmbeddedId
private TUserDetailEntityId id;
@Size(max = 2048)
@NotNull
@Column(name = "user_detail_value", nullable = false, length = 2048)
private String userDetailValue;
@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;
public String getUserId() {
return id.getUserId();
}
public String getUserDetailKey() {
return id.getUserDetailKey();
}
public static TUserDetailEntity create(
String userId,
String userDetailKey,
String userDetailValue,
String regUser,
LocalDateTime regDt
) {
return TUserDetailEntity.builder()
.id(TUserDetailEntityId.builder()
.userId(userId)
.userDetailKey(userDetailKey)
.build())
.userDetailValue(userDetailValue)
.regUser(regUser)
.regDt(regDt)
.build();
}
public static TUserDetailEntity update(
String userId,
String userDetailKey,
String userDetailValue,
String modUser,
LocalDateTime modDt
) {
return TUserDetailEntity.builder()
.id(TUserDetailEntityId.builder()
.userId(userId)
.userDetailKey(userDetailKey)
.build())
.userDetailValue(userDetailValue)
.regUser(modUser)
.regDt(modDt)
.modUser(modUser)
.modDt(modDt)
.build();
}
}

View File

@@ -0,0 +1,103 @@
package com.kri.kmusical.manage.back.persistence.entity;
import com.kri.kmusical.manage.back.dto.user.UserFullDto;
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.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_user")
public class TUserEntity {
@Id
@Size(max = 32)
@Column(name = "user_id", nullable = false, length = 32)
private String userId;
@Size(max = 64)
@NotNull
@Column(name = "user_pw", nullable = false, length = 64)
private String userPw;
@Size(max = 32)
@NotNull
@Column(name = "user_name", nullable = false, length = 32)
private String userName;
@Size(max = 32)
@NotNull
@Column(name = "user_cmpn", nullable = false, length = 32)
private String userCmpn;
@Size(max = 32)
@NotNull
@Column(name = "user_team", nullable = false, length = 32)
private String userTeam;
@NotNull
@Column(name = "user_role", nullable = false)
private Integer userRole;
@NotNull
@Lob
@Column(name = "memo", nullable = false)
private String memo;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
@Size(max = 32)
@Column(name = "mod_user", length = 32)
private String modUser;
@Column(name = "mod_dt")
private LocalDateTime modDt;
public static TUserEntity from(UserFullDto dto, String regUser, LocalDateTime regDt) {
if (dto == null) {
return null;
}
TUserEntity entity = new TUserEntity();
entity.setUserId(dto.getUserId());
entity.setUserPw(dto.getUserPw());
entity.setUserName(dto.getUserName());
entity.setUserCmpn(dto.getUserCmpn());
entity.setUserTeam(dto.getUserTeam());
entity.setUserRole(dto.getUserRole());
entity.setMemo(dto.getMemo());
entity.setRegUser(regUser);
entity.setRegDt(regDt);
return entity;
}
public void updateFromDto(UserFullDto dto, String modUser, LocalDateTime modDt) {
this.userPw = dto.getUserPw();
this.userName = dto.getUserName();
this.memo = dto.getMemo();
this.modUser = modUser;
this.modDt = modDt;
}
}

View File

@@ -0,0 +1,35 @@
package com.kri.kmusical.manage.back.persistence.entity.id;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.io.Serial;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Embeddable
public class TCodeEntityId implements Serializable {
@Serial
private static final long serialVersionUID = 7929829948288158244L;
@Size(max = 64)
@NotNull
@Column(name = "code_group", nullable = false, length = 64)
private String codeGroup;
@NotNull
@Column(name = "code_value", nullable = false)
private Integer codeValue;
}

View File

@@ -0,0 +1,35 @@
package com.kri.kmusical.manage.back.persistence.entity.id;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.io.Serial;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Embeddable
public class TPerformanceAssignEntityId implements Serializable {
@Serial
private static final long serialVersionUID = -1096367455446307015L;
@Size(max = 32)
@NotNull
@Column(name = "performance_id", nullable = false, length = 32)
private String performanceId;
@NotNull
@Column(name = "review_slot", nullable = false)
private Integer reviewSlot;
}

View File

@@ -0,0 +1,36 @@
package com.kri.kmusical.manage.back.persistence.entity.id;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.io.Serial;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Embeddable
public class TPerformanceDetailEntityId implements Serializable {
@Serial
private static final long serialVersionUID = -759856812074393127L;
@Size(max = 32)
@NotNull
@Column(name = "performance_id", nullable = false, length = 32)
private String performanceId;
@Size(max = 64)
@NotNull
@Column(name = "performance_detail_key", nullable = false, length = 64)
private String performanceDetailKey;
}

View File

@@ -0,0 +1,34 @@
package com.kri.kmusical.manage.back.persistence.entity.id;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.io.Serial;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Embeddable
public class TPerformanceReviewEntityId implements Serializable {
@Serial
private static final long serialVersionUID = -6558083063451609271L;
@Size(max = 32)
@NotNull
@Column(name = "performance_id", nullable = false, length = 32)
private String performanceId;
@NotNull
@Column(name = "review_slot", nullable = false)
private Integer reviewSlot;
}

View File

@@ -0,0 +1,36 @@
package com.kri.kmusical.manage.back.persistence.entity.id;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.io.Serial;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter @Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Embeddable
public class TUserDetailEntityId implements Serializable {
@Serial
private static final long serialVersionUID = 6587704077866002687L;
@Size(max = 32)
@NotNull
@Column(name = "user_id", nullable = false, length = 32)
private String userId;
@Size(max = 64)
@NotNull
@Column(name = "user_detail_key", nullable = false, length = 64)
private String userDetailKey;
}

View File

@@ -0,0 +1,20 @@
package com.kri.kmusical.manage.back.persistence.mapper.kon;
import com.kri.kmusical.manage.back.dto.kon.PerformanceApplyCountDto;
import com.kri.kmusical.manage.back.dto.kon.PerformanceApplyUserDto;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface KonMapper {
List<PerformanceApplyCountDto> findPerformanceApplyCount(
@Param("surveyType") String surveyType
);
List<PerformanceApplyUserDto> findPerformanceApplyUser(
@Param("surveyType") String surveyType,
@Param("performanceId") String performanceId
);
}

View File

@@ -0,0 +1,11 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TCodeEntity;
import com.kri.kmusical.manage.back.persistence.entity.id.TCodeEntityId;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CodeRepository extends JpaRepository<TCodeEntity, TCodeEntityId> {
List<TCodeEntity> findByIdCodeGroup(String codeGroup);
}

View File

@@ -0,0 +1,37 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.dto.assign.AssignUserCountDto;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceAssignEntity;
import com.kri.kmusical.manage.back.persistence.entity.id.TPerformanceAssignEntityId;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface PerformanceAssignRepository extends JpaRepository<TPerformanceAssignEntity, TPerformanceAssignEntityId> {
boolean existsByAssignUser(String assignUser);
boolean existsByIdPerformanceId(String performanceId);
List<TPerformanceAssignEntity> findByIdPerformanceId(String performanceId);
boolean existsByIdPerformanceIdAndAssignUser(String performanceId, String assignUser);
boolean existsByAssignUserAndIdPerformanceIdNot(String assignUser, String performanceId);
Optional<TPerformanceAssignEntity> findByIdPerformanceIdAndIdReviewSlot(
String performanceId,
Integer reviewSlot
);
@Query("""
select new com.kri.kmusical.manage.back.dto.assign.AssignUserCountDto(
assign.assignUser,
count(assign)
)
from TPerformanceAssignEntity assign
group by assign.assignUser
""")
List<AssignUserCountDto> countGroupByAssignUser();
}

View File

@@ -0,0 +1,13 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceDetailEntity;
import com.kri.kmusical.manage.back.persistence.entity.id.TPerformanceDetailEntityId;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PerformanceDetailRepository extends JpaRepository<TPerformanceDetailEntity, TPerformanceDetailEntityId> {
List<TPerformanceDetailEntity> findByIdPerformanceId(String performanceId);
Integer deleteByIdPerformanceId(String performanceId);
}

View File

@@ -0,0 +1,12 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceMonitoringScheduleEntity;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PerformanceMonitoringScheduleRepository extends JpaRepository<TPerformanceMonitoringScheduleEntity, Long> {
Optional<TPerformanceMonitoringScheduleEntity> findFirstByPerformanceId(String performanceId);
Integer deleteByPerformanceId(String performanceId);
}

View File

@@ -0,0 +1,7 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PerformanceRepository extends JpaRepository<TPerformanceEntity, String> {
}

View File

@@ -0,0 +1,23 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceReviewEntity;
import com.kri.kmusical.manage.back.persistence.entity.id.TPerformanceReviewEntityId;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PerformanceReviewRepository extends JpaRepository<TPerformanceReviewEntity, TPerformanceReviewEntityId> {
boolean existsByRegUserOrModUser(String regUser, String modUser);
boolean existsByIdPerformanceId(String performanceId);
List<TPerformanceReviewEntity> findByIdPerformanceId(String performanceId);
Optional<TPerformanceReviewEntity> findByIdPerformanceIdAndIdReviewSlot(
String performanceId,
Integer reviewSlot
);
boolean existsByIdPerformanceIdAndIdReviewSlot(String performanceId, Integer reviewSlot);
}

View File

@@ -0,0 +1,8 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceReviewSlotEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PerformanceReviewSlotRepository extends JpaRepository<TPerformanceReviewSlotEntity, Integer> {
}

View File

@@ -0,0 +1,12 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceStaffEntity;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PerformanceStaffRepository extends JpaRepository<TPerformanceStaffEntity, Long> {
List<TPerformanceStaffEntity> findByPerformanceId(String performanceId);
Integer deleteByPerformanceId(String performanceId);
}

View File

@@ -0,0 +1,7 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TSysEventLogEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SysEventLogRepository extends JpaRepository<TSysEventLogEntity, Long> {
}

View File

@@ -0,0 +1,14 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TUserDetailEntity;
import com.kri.kmusical.manage.back.persistence.entity.id.TUserDetailEntityId;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDetailRepository extends JpaRepository<TUserDetailEntity, TUserDetailEntityId> {
List<TUserDetailEntity> findByIdUserId(String userId);
Integer deleteByIdUserId(String userId);
}

View File

@@ -0,0 +1,16 @@
package com.kri.kmusical.manage.back.persistence.repository;
import com.kri.kmusical.manage.back.persistence.entity.TUserEntity;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<TUserEntity, String> {
Optional<TUserEntity> findByUserIdAndUserPw(String userId, String userPw);
Optional<TUserEntity> findByUserId(String userId);
boolean existsByUserId(String userId);
Integer deleteByUserId(String userId);
}

View File

@@ -0,0 +1,202 @@
package com.kri.kmusical.manage.back.service;
import com.kri.common.feature.util.StringUtil;
import com.kri.common.feature.web.BusinessException;
import com.kri.kmusical.manage.back.dto.assign.AssignUserCountDto;
import com.kri.kmusical.manage.back.dto.assign.MonitoringApplyUserDto;
import com.kri.kmusical.manage.back.dto.kon.PerformanceApplyCountDto;
import com.kri.kmusical.manage.back.dto.kon.PerformanceApplyUserDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceAssignDto;
import com.kri.kmusical.manage.back.dto.user.UserCompactDto;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceAssignEntity;
import com.kri.kmusical.manage.back.persistence.entity.TUserDetailEntity;
import com.kri.kmusical.manage.back.persistence.entity.TUserEntity;
import com.kri.kmusical.manage.back.persistence.entity.id.TPerformanceAssignEntityId;
import com.kri.kmusical.manage.back.persistence.mapper.kon.KonMapper;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceAssignRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceReviewRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceReviewSlotRepository;
import com.kri.kmusical.manage.back.persistence.repository.UserDetailRepository;
import com.kri.kmusical.manage.back.persistence.repository.UserRepository;
import java.time.LocalDateTime;
import java.util.Collections;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class AssignService {
private static final short ASSIGN_STATUS_CONFIRMED = 1;
private final PerformanceAssignRepository performanceAssignRepository;
private final PerformanceReviewRepository performanceReviewRepository;
private final PerformanceReviewSlotRepository performanceReviewSlotRepository;
private final KonMapper konMapper;
private final PerformanceRepository performanceRepository;
private final UserRepository userRepository;
private final UserDetailRepository userDetailRepository;
@Value("${kon.survey-type:LIST}")
private String surveyType;
public boolean hasAssignWithUser(String userId) {
return performanceAssignRepository.existsByAssignUser(userId);
}
public boolean hasAssignWithPerformance(String performanceId) {
return performanceAssignRepository.existsByIdPerformanceId(performanceId);
}
public List<PerformanceAssignDto> findByPerformanceId(String performanceId) {
return performanceAssignRepository.findByIdPerformanceId(performanceId).stream()
.map(PerformanceAssignDto::from)
.toList();
}
public List<AssignUserCountDto> findAssignUserCounts() {
return performanceAssignRepository.countGroupByAssignUser();
}
@Transactional(readOnly = true, transactionManager = "konTransactionManager")
public List<PerformanceApplyUserDto> findKonPerformanceApplyUser(String performanceId) {
return konMapper.findPerformanceApplyUser(surveyType, performanceId);
}
@Transactional(readOnly = true, transactionManager = "konTransactionManager")
public List<PerformanceApplyCountDto> findMonitoringApplyUsersCount() {
return konMapper.findPerformanceApplyCount(surveyType);
}
public List<MonitoringApplyUserDto> findMonitoringApplyUsers(String performanceId) {
List<PerformanceApplyUserDto> applyUsers = findKonPerformanceApplyUser(performanceId);
if (applyUsers.isEmpty()) {
return Collections.emptyList();
}
List<String> userIds = applyUsers.stream()
.map(PerformanceApplyUserDto::getUserId)
.distinct()
.toList();
Set<String> userIdSet = Set.copyOf(userIds);
Map<String, TUserEntity> userMap = userRepository.findAllById(userIds).stream()
.collect(Collectors.toMap(TUserEntity::getUserId, Function.identity()));
Map<String, Map<String, String>> userDetailMap = userDetailRepository.findAll().stream()
.filter(detail -> userIdSet.contains(detail.getUserId()))
.collect(Collectors.groupingBy(
TUserDetailEntity::getUserId,
Collectors.toMap(
TUserDetailEntity::getUserDetailKey,
TUserDetailEntity::getUserDetailValue,
(left, right) -> right
)
));
return applyUsers.stream()
.map(applyUser -> {
TUserEntity user = userMap.get(applyUser.getUserId());
return MonitoringApplyUserDto.builder()
.performanceId(performanceId)
.userId(applyUser.getUserId())
.user(user == null
? null
: UserCompactDto.from(
user,
userDetailMap.getOrDefault(applyUser.getUserId(), Collections.emptyMap())
))
.build();
})
.toList();
}
@Transactional
public PerformanceAssignDto confirmAssign(
String performanceId,
Integer reviewSlot,
String assignUser,
String regUser,
LocalDateTime regDt
) {
validateAssignment(performanceId, reviewSlot, assignUser);
TPerformanceAssignEntity entity = performanceAssignRepository
.findByIdPerformanceIdAndIdReviewSlot(performanceId, reviewSlot)
.orElse(null);
if (entity != null && assignUser.equals(entity.getAssignUser())) {
return PerformanceAssignDto.from(entity);
}
if (entity != null) {
validateNoReviewBeforeAssignChange(performanceId, reviewSlot);
}
if (performanceAssignRepository.existsByIdPerformanceIdAndAssignUser(performanceId, assignUser)) {
throw BusinessException.conflict("ASSIGN_USER_DUPLICATED", "동일 공연의 다른 평가 슬롯에 이미 확정된 사용자입니다.")
.with("performanceId", performanceId)
.with("assignUser", assignUser);
}
if (performanceAssignRepository.existsByAssignUserAndIdPerformanceIdNot(assignUser, performanceId)) {
throw BusinessException.conflict("ASSIGN_USER_ALREADY_CONFIRMED", "다른 공연에 이미 확정된 사용자입니다.")
.with("assignUser", assignUser);
}
if (entity == null) {
entity = new TPerformanceAssignEntity();
entity.setId(new TPerformanceAssignEntityId(performanceId, reviewSlot));
}
entity.setAssignUser(assignUser);
entity.setAssignStatus(ASSIGN_STATUS_CONFIRMED);
entity.setRegUser(regUser);
entity.setRegDt(regDt);
return PerformanceAssignDto.from(performanceAssignRepository.save(entity));
}
@Transactional
public void cancelAssign(String performanceId, Integer reviewSlot) {
TPerformanceAssignEntity entity = performanceAssignRepository
.findByIdPerformanceIdAndIdReviewSlot(performanceId, reviewSlot)
.orElseThrow(() -> BusinessException.notFound("ASSIGN_NOT_FOUND", "배정 정보를 찾을 수 없습니다.")
.with("performanceId", performanceId)
.with("reviewSlot", reviewSlot));
validateNoReviewBeforeAssignChange(performanceId, reviewSlot);
performanceAssignRepository.delete(entity);
}
private void validateAssignment(String performanceId, Integer reviewSlot, String assignUser) {
if (StringUtil.isNullOrBlank(performanceId)) {
throw BusinessException.badRequest("EMPTY_PERFORMANCE_ID", "공연 ID가 없습니다.");
}
if (!performanceRepository.existsById(performanceId)) {
throw BusinessException.notFound("PERFORMANCE_NOT_FOUND", "존재하지 않는 공연입니다.")
.with("performanceId", performanceId);
}
if (reviewSlot == null) {
throw BusinessException.badRequest("EMPTY_REVIEW_SLOT", "평가 슬롯이 없습니다.");
}
if (!performanceReviewSlotRepository.existsById(reviewSlot)) {
throw BusinessException.notFound("REVIEW_SLOT_NOT_FOUND", "존재하지 않는 평가 슬롯입니다.")
.with("reviewSlot", reviewSlot);
}
if (StringUtil.isNullOrBlank(assignUser)) {
throw BusinessException.badRequest("EMPTY_USER_ID", "사용자 ID가 없습니다.");
}
if (!userRepository.existsByUserId(assignUser)) {
throw BusinessException.notFound("USER_NOT_FOUND", "존재하지 않는 사용자 ID입니다.")
.with("userId", assignUser);
}
}
private void validateNoReviewBeforeAssignChange(String performanceId, Integer reviewSlot) {
if (performanceReviewRepository.existsByIdPerformanceIdAndIdReviewSlot(performanceId, reviewSlot)) {
throw BusinessException.conflict("ASSIGN_HAS_REVIEW", "평가가 시작된 슬롯의 배정은 교체하거나 취소할 수 없습니다.")
.with("performanceId", performanceId)
.with("reviewSlot", reviewSlot);
}
}
}

View File

@@ -0,0 +1,34 @@
package com.kri.kmusical.manage.back.service;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.kmusical.manage.back.dto.auth.LoginRequestDto;
import com.kri.kmusical.manage.back.dto.auth.LoginResponseDto;
import com.kri.kmusical.manage.back.dto.user.UserCompactDto;
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) {
UserCompactDto 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);
}
}

View File

@@ -0,0 +1,20 @@
package com.kri.kmusical.manage.back.service;
import com.kri.kmusical.manage.back.dto.common.CodeDto;
import com.kri.kmusical.manage.back.persistence.repository.CodeRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class CodeService {
private final CodeRepository codeRepository;
public List<CodeDto> findByCodeGroup(String codeGroup) {
return codeRepository.findByIdCodeGroup(codeGroup).stream()
.map(CodeDto::from)
.toList();
}
}

View File

@@ -0,0 +1,903 @@
package com.kri.kmusical.manage.back.service;
import static com.kri.kmusical.manage.back.common.util.AppendCodeSheet.appendCodeSheet;
import static java.util.stream.Collectors.toMap;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.excel.ExcelMapper;
import com.kri.common.feature.util.NumericUtil;
import com.kri.common.feature.util.StringUtil;
import com.kri.common.feature.web.BusinessException;
import com.kri.kmusical.manage.back.common.util.ExcelUploadResultUtil;
import com.kri.kmusical.manage.back.common.util.TelUtil;
import com.kri.kmusical.manage.back.dto.common.CodeDto;
import com.kri.kmusical.manage.back.dto.excel.ExcelErrorDto;
import com.kri.kmusical.manage.back.dto.excel.ExcelUploadResultDto;
import com.kri.kmusical.manage.back.dto.excel.performance.PerformanceDownloadDto;
import com.kri.kmusical.manage.back.dto.excel.performance.PerformanceUploadDto;
import com.kri.kmusical.manage.back.dto.kon.PerformanceApplyCountDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceAssignDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceCompactDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceFullDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceMonitoringScheduleDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceReviewDto;
import com.kri.kmusical.manage.back.dto.performance.PerformanceStaffDto;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceAssignEntity;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceDetailEntity;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceEntity;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceMonitoringScheduleEntity;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceReviewEntity;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceStaffEntity;
import com.kri.kmusical.manage.back.persistence.mapper.kon.KonMapper;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceAssignRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceDetailRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceMonitoringScheduleRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceReviewRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceStaffRepository;
import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@Service
@RequiredArgsConstructor
public class PerformanceService {
private static final DateTimeFormatter REVIEW_DT_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final KonMapper konMapper;
private final PerformanceRepository performanceRepository;
private final PerformanceDetailRepository performanceDetailRepository;
private final PerformanceStaffRepository performanceStaffRepository;
private final PerformanceMonitoringScheduleRepository performanceMonitoringScheduleRepository;
private final PerformanceAssignRepository performanceAssignRepository;
private final PerformanceReviewRepository performanceReviewRepository;
private final CodeService codeService;
private final AssignService assignService;
private final ReviewService reviewService;
@Value("${kon.survey-type:LIST}")
private String surveyType;
public PerformanceFullDto getPerformance(String performanceId) {
TPerformanceEntity performance = getPerformanceEntity(performanceId);
return toFullDto(performance);
}
public List<PerformanceFullDto> getPerformanceList() {
List<TPerformanceEntity> performances = performanceRepository.findAll();
PerformanceFullLookup lookup = buildPerformanceFullLookup();
return performances.stream()
.map(performance -> toFullDto(performance, lookup))
.sorted(Comparator.comparing(
this::getPerformanceNoForSort,
Comparator.nullsLast(Integer::compareTo)
))
.toList();
}
public List<PerformanceCompactDto> getPerformanceCompactList() {
List<TPerformanceEntity> performances = performanceRepository.findAll();
PerformanceCompactLookup lookup = buildPerformanceCompactLookup();
return performances.stream()
.map(performance -> toCompactDto(performance, lookup))
.sorted(Comparator.comparing(
this::getPerformanceNoForSort,
Comparator.nullsLast(Integer::compareTo)
))
.toList();
}
@Transactional
public ExcelUploadResultDto createPerformancesFromExcel(
MultipartFile file,
String regUser,
LocalDateTime regDt
) {
if (file == null || file.isEmpty()) {
throw BusinessException.badRequest("EMPTY_FILE", "업로드된 파일이 없습니다.");
}
String fileName = file.getOriginalFilename();
String errorFileName = fileName != null && fileName.endsWith(".xlsx")
? fileName.substring(0, fileName.length() - 5) + "_error.xlsx"
: fileName + "_error.xlsx";
List<PerformanceUploadDto> rows;
try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
rows = ExcelMapper.readFromWorkbook(workbook, PerformanceUploadDto.class);
} catch (Exception e) {
throw BusinessException.badRequest("INVALID_EXCEL", "엑셀 파일을 읽는 중 오류가 발생했습니다.")
.with("fileName", fileName);
}
List<CodeDto> businessTypeList = codeService.findByCodeGroup("business_type");
List<CodeDto> genreList = codeService.findByCodeGroup("genre");
List<CodeDto> areaList = codeService.findByCodeGroup("area");
List<CodeDto> ticketReservationStatusList =
codeService.findByCodeGroup("ticket_reservation_status");
int totalCount = rows.size();
int successCount = 0;
List<ExcelErrorDto> errorList = new ArrayList<>();
Set<String> existingPerformanceIds = performanceRepository.findAll().stream()
.map(TPerformanceEntity::getPerformanceId)
.collect(Collectors.toSet());
for (int i = 0; i < rows.size(); i++) {
PerformanceUploadDto row = rows.get(i);
int rowNumber = i + 2;
List<ExcelErrorDto> rowErrors = validatePerformanceUploadRow(
row,
rowNumber,
businessTypeList,
genreList,
areaList,
ticketReservationStatusList,
existingPerformanceIds
);
if (!rowErrors.isEmpty()) {
errorList.addAll(rowErrors);
continue;
}
try {
createPerformanceInternal(row, regUser, regDt);
existingPerformanceIds.add(row.getPerformanceId().trim());
successCount++;
} catch (BusinessException e) {
errorList.add(ExcelErrorDto.of(rowNumber, "SYSTEM", e.getMessage()));
}
}
int failCount = errorList.stream()
.map(ExcelErrorDto::getRowNumber)
.distinct()
.toList()
.size();
return ExcelUploadResultUtil.buildUploadResult(
totalCount,
successCount,
failCount,
errorList,
ExcelErrorDto.class,
errorFileName
);
}
@Transactional
public void updatePerformance(
PerformanceCompactDto dto,
String modUser,
LocalDateTime modDt
) {
TPerformanceEntity entity = getPerformanceEntity(dto.getPerformanceId());
entity.updateFromDto(dto, modUser, modDt);
updatePerformanceDetail(dto.getPerformanceId(), dto.getPerformanceDetail(), modUser, modDt);
updatePerformanceStaff(dto.getPerformanceId(), dto.getPerformanceStaff(), modUser, modDt);
upsertPerformanceMonitoringSchedule(
dto.getPerformanceId(),
dto.getPerformanceMonitoringSchedule(),
modUser,
modDt
);
}
@Transactional
public void deletePerformance(String performanceId, String delUser) {
TPerformanceEntity performance = getPerformanceEntity(performanceId);
validatePerformanceDeletable(performanceId);
performanceDetailRepository.deleteByIdPerformanceId(performanceId);
performanceStaffRepository.deleteByPerformanceId(performanceId);
performanceMonitoringScheduleRepository.deleteByPerformanceId(performanceId);
performanceRepository.delete(performance);
}
public byte[] exportPerformanceTemplate() {
List<CodeDto> businessTypeList = codeService.findByCodeGroup("business_type");
List<CodeDto> genreList = codeService.findByCodeGroup("genre");
List<CodeDto> areaList = codeService.findByCodeGroup("area");
List<CodeDto> ticketReservationStatusList =
codeService.findByCodeGroup("ticket_reservation_status");
try (Workbook workbook =
ExcelMapper.writeToWorkbook(Collections.emptyList(), PerformanceUploadDto.class);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
appendCodeSheet(workbook, businessTypeList, "사업유형");
appendCodeSheet(workbook, genreList, "장르");
appendCodeSheet(workbook, areaList, "지역");
appendCodeSheet(workbook, ticketReservationStatusList, "티켓 예약");
workbook.write(out);
return out.toByteArray();
} catch (Exception e) {
throw BusinessException.internalError("공연 업로드 템플릿 엑셀 생성 중 오류");
}
}
public byte[] exportPerformance(String[] performanceIds) {
Set<String> selectedPerformanceIds = performanceIds == null
? Collections.emptySet()
: Arrays.stream(performanceIds).collect(Collectors.toSet());
List<PerformanceDownloadDto> performanceList = getPerformanceList().stream()
.filter(performance -> selectedPerformanceIds.contains(performance.getPerformanceId()))
.map(this::toPerformanceDownloadRow)
.toList();
List<CodeDto> businessTypeList = codeService.findByCodeGroup("business_type");
List<CodeDto> genreList = codeService.findByCodeGroup("genre");
List<CodeDto> areaList = codeService.findByCodeGroup("area");
List<CodeDto> ticketReservationStatusList =
codeService.findByCodeGroup("ticket_reservation_status");
List<CodeDto> reviewStatusList = codeService.findByCodeGroup("review_status");
try (Workbook workbook =
ExcelMapper.writeToWorkbook(performanceList, PerformanceDownloadDto.class);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
appendCodeSheet(workbook, businessTypeList, "사업유형");
appendCodeSheet(workbook, genreList, "장르");
appendCodeSheet(workbook, areaList, "지역");
appendCodeSheet(workbook, ticketReservationStatusList, "티켓 예약");
appendCodeSheet(workbook, reviewStatusList, "평가 상태");
workbook.write(out);
return out.toByteArray();
} catch (Exception e) {
throw BusinessException.internalError("공연 엑셀 생성 중 오류");
}
}
private PerformanceDownloadDto toPerformanceDownloadRow(PerformanceFullDto performance) {
Map<String, String> detail = performance.getPerformanceDetail() == null
? Collections.emptyMap()
: performance.getPerformanceDetail();
PerformanceMonitoringScheduleDto schedule = performance.getPerformanceMonitoringSchedule();
PerformanceStaffDto ownStaff = findStaff(performance, 1);
PerformanceStaffDto contactStaff = findStaff(performance, 2);
PerformanceAssignDto monitoringAssign1 = findAssign(performance, 1);
PerformanceAssignDto monitoringAssign2 = findAssign(performance, 2);
PerformanceAssignDto monitoringAssign3 = findAssign(performance, 3);
PerformanceAssignDto consultingAssign1 = findAssign(performance, 4);
PerformanceAssignDto consultingAssign2 = findAssign(performance, 5);
PerformanceReviewDto monitoringReview1 = findReview(performance, 1);
PerformanceReviewDto monitoringReview2 = findReview(performance, 2);
PerformanceReviewDto monitoringReview3 = findReview(performance, 3);
PerformanceReviewDto consultingReview1 = findReview(performance, 4);
PerformanceReviewDto consultingReview2 = findReview(performance, 5);
return PerformanceDownloadDto.builder()
.performanceId(performance.getPerformanceId())
.businessType(toStringValue(performance.getBusinessType()))
.performanceArea(toStringValue(performance.getPerformanceArea()))
.artistName(performance.getArtistName())
.performanceName(performance.getPerformanceName())
.performanceStartMonth(toStringValue(performance.getPerformanceStartMonth()))
.performanceDtInfo(performance.getPerformanceDtInfo())
.performanceTimeInfo(performance.getPerformanceTimeInfo())
.ticketReservationStatus(toStringValue(performance.getTicketReservationStatus()))
.ticketReservationMemo(performance.getTicketReservationMemo())
.monitoringDate(schedule == null ? null : toStringValue(schedule.getMonitoringDate()))
.monitoringTimeInfo(schedule == null ? null : schedule.getMonitoringTimeInfo())
.monitoringAddress(schedule == null ? null : schedule.getMonitoringAddress())
.ownStaffName(ownStaff == null ? null : ownStaff.getStaffName())
.ownStaffTel1(ownStaff == null ? null : ownStaff.getStaffTel1())
.ownStaffTel2(ownStaff == null ? null : ownStaff.getStaffTel2())
.ownStaffEmail(ownStaff == null ? null : ownStaff.getStaffEmail())
.contactStaffName(contactStaff == null ? null : contactStaff.getStaffName())
.contactStaffTel1(contactStaff == null ? null : contactStaff.getStaffTel1())
.contactStaffTel2(contactStaff == null ? null : contactStaff.getStaffTel2())
.contactStaffEmail(contactStaff == null ? null : contactStaff.getStaffEmail())
.performanceMemo(performance.getPerformanceMemo())
.monitoringPaymentDate(detail.get("monitoringPaymentDate"))
.monitoringReviewUser1(monitoringAssign1 == null ? null : monitoringAssign1.getAssignUser())
.monitoringReviewStatus1(monitoringReview1 == null ? null : toStringValue(monitoringReview1.getReviewStatus()))
.monitoringReviewDt1(formatReviewDt(monitoringReview1))
.monitoringReviewUser2(monitoringAssign2 == null ? null : monitoringAssign2.getAssignUser())
.monitoringReviewStatus2(monitoringReview2 == null ? null : toStringValue(monitoringReview2.getReviewStatus()))
.monitoringReviewDt2(formatReviewDt(monitoringReview2))
.monitoringReviewUser3(monitoringAssign3 == null ? null : monitoringAssign3.getAssignUser())
.monitoringReviewStatus3(monitoringReview3 == null ? null : toStringValue(monitoringReview3.getReviewStatus()))
.monitoringReviewDt3(formatReviewDt(monitoringReview3))
.consultingReviewUser1(consultingAssign1 == null ? null : consultingAssign1.getAssignUser())
.consultingReviewStatus1(consultingReview1 == null ? null : toStringValue(consultingReview1.getReviewStatus()))
.consultingReviewDt1(formatReviewDt(consultingReview1))
.consultingReviewUser2(consultingAssign2 == null ? null : consultingAssign2.getAssignUser())
.consultingReviewStatus2(consultingReview2 == null ? null : toStringValue(consultingReview2.getReviewStatus()))
.consultingReviewDt2(formatReviewDt(consultingReview2))
.build();
}
private PerformanceStaffDto findStaff(PerformanceFullDto performance, Integer staffType) {
if (performance.getPerformanceStaff() == null) {
return null;
}
return performance.getPerformanceStaff().stream()
.filter(staff -> Objects.equals(staff.getStaffType(), staffType))
.findFirst()
.orElse(null);
}
private PerformanceAssignDto findAssign(
PerformanceFullDto performance,
Integer reviewSlot
) {
if (performance.getPerformanceAssignList() == null) {
return null;
}
return performance.getPerformanceAssignList().stream()
.filter(assign -> Objects.equals(assign.getReviewSlot(), reviewSlot))
.findFirst()
.orElse(null);
}
private PerformanceReviewDto findReview(PerformanceFullDto performance, Integer reviewSlot) {
if (performance.getPerformanceReviewMap() == null) {
return null;
}
return performance.getPerformanceReviewMap().get(reviewSlot);
}
private String formatReviewDt(PerformanceReviewDto review) {
return review == null || review.getReviewDt() == null
? null
: review.getReviewDt().format(REVIEW_DT_FORMATTER);
}
private String toStringValue(Object value) {
return value == null ? null : String.valueOf(value);
}
private Integer getPerformanceNoForSort(PerformanceFullDto performance) {
if (performance == null || performance.getPerformanceDetail() == null) {
return null;
}
return NumericUtil.parseOnlyInteger(performance.getPerformanceDetail().get("performanceNo"));
}
private Integer getPerformanceNoForSort(PerformanceCompactDto performance) {
if (performance == null || performance.getPerformanceDetail() == null) {
return null;
}
return NumericUtil.parseOnlyInteger(performance.getPerformanceDetail().get("performanceNo"));
}
@Transactional(readOnly = true, transactionManager = "konTransactionManager")
public List<PerformanceApplyCountDto> findPerformanceApplyCount() {
return konMapper.findPerformanceApplyCount(surveyType);
}
private PerformanceFullDto toFullDto(TPerformanceEntity performance) {
String performanceId = performance.getPerformanceId();
return PerformanceFullDto.from(
performance,
getPerformanceDetailMap(performanceId),
getPerformanceStaffList(performanceId),
getPerformanceMonitoringSchedule(performanceId),
assignService.findByPerformanceId(performanceId),
reviewService.findMapByPerformanceId(performanceId)
);
}
private PerformanceFullDto toFullDto(TPerformanceEntity performance, PerformanceFullLookup lookup) {
String performanceId = performance.getPerformanceId();
return PerformanceFullDto.from(
performance,
lookup.performanceDetailMap().getOrDefault(performanceId, Collections.emptyMap()),
lookup.performanceStaffMap().getOrDefault(performanceId, Collections.emptyList()),
lookup.performanceMonitoringScheduleMap().get(performanceId),
lookup.performanceAssignMap().getOrDefault(performanceId, Collections.emptyList()),
lookup.performanceReviewMap().getOrDefault(performanceId, Collections.emptyMap())
);
}
private PerformanceCompactDto toCompactDto(TPerformanceEntity performance) {
String performanceId = performance.getPerformanceId();
return PerformanceCompactDto.from(
performance,
getPerformanceDetailMap(performanceId),
getPerformanceStaffList(performanceId),
getPerformanceMonitoringSchedule(performanceId)
);
}
private PerformanceCompactDto toCompactDto(
TPerformanceEntity performance,
PerformanceCompactLookup lookup
) {
String performanceId = performance.getPerformanceId();
return PerformanceCompactDto.from(
performance,
lookup.performanceDetailMap().getOrDefault(performanceId, Collections.emptyMap()),
lookup.performanceStaffMap().getOrDefault(performanceId, Collections.emptyList()),
lookup.performanceMonitoringScheduleMap().get(performanceId)
);
}
private PerformanceFullLookup buildPerformanceFullLookup() {
PerformanceCompactLookup compactLookup = buildPerformanceCompactLookup();
Map<String, List<PerformanceAssignDto>> assignMap = performanceAssignRepository.findAll()
.stream()
.collect(Collectors.groupingBy(
TPerformanceAssignEntity::getPerformanceId,
Collectors.mapping(PerformanceAssignDto::from, Collectors.toList())
));
Map<String, Map<Integer, PerformanceReviewDto>> reviewMap =
performanceReviewRepository.findAll()
.stream()
.collect(Collectors.groupingBy(
TPerformanceReviewEntity::getPerformanceId,
Collectors.toMap(
TPerformanceReviewEntity::getReviewSlot,
PerformanceReviewDto::from
)
));
return new PerformanceFullLookup(
compactLookup.performanceDetailMap(),
compactLookup.performanceStaffMap(),
compactLookup.performanceMonitoringScheduleMap(),
assignMap,
reviewMap
);
}
private PerformanceCompactLookup buildPerformanceCompactLookup() {
Map<String, Map<String, String>> detailMap = performanceDetailRepository.findAll()
.stream()
.collect(Collectors.groupingBy(
TPerformanceDetailEntity::getPerformanceId,
toMap(
TPerformanceDetailEntity::getPerformanceDetailKey,
TPerformanceDetailEntity::getPerformanceDetailValue,
(left, right) -> right,
LinkedHashMap::new
)
));
Map<String, List<PerformanceStaffDto>> staffMap = performanceStaffRepository.findAll()
.stream()
.collect(Collectors.groupingBy(
TPerformanceStaffEntity::getPerformanceId,
Collectors.mapping(PerformanceStaffDto::from, Collectors.toList())
));
Map<String, PerformanceMonitoringScheduleDto> scheduleMap =
performanceMonitoringScheduleRepository.findAll()
.stream()
.collect(toMap(
TPerformanceMonitoringScheduleEntity::getPerformanceId,
PerformanceMonitoringScheduleDto::from,
(first, ignored) -> first
));
return new PerformanceCompactLookup(detailMap, staffMap, scheduleMap);
}
private record PerformanceCompactLookup(
Map<String, Map<String, String>> performanceDetailMap,
Map<String, List<PerformanceStaffDto>> performanceStaffMap,
Map<String, PerformanceMonitoringScheduleDto> performanceMonitoringScheduleMap
) {
}
private record PerformanceFullLookup(
Map<String, Map<String, String>> performanceDetailMap,
Map<String, List<PerformanceStaffDto>> performanceStaffMap,
Map<String, PerformanceMonitoringScheduleDto> performanceMonitoringScheduleMap,
Map<String, List<PerformanceAssignDto>> performanceAssignMap,
Map<String, Map<Integer, PerformanceReviewDto>> performanceReviewMap
) {
}
private List<ExcelErrorDto> validatePerformanceUploadRow(
PerformanceUploadDto row,
int rowNumber,
List<CodeDto> businessTypeList,
List<CodeDto> genreList,
List<CodeDto> areaList,
List<CodeDto> ticketReservationStatusList,
Set<String> existingPerformanceIds
) {
List<ExcelErrorDto> errors = new ArrayList<>();
Integer performanceNo = NumericUtil.parseOnlyInteger(row.getPerformanceNo());
if (performanceNo == null) {
errors.add(ExcelErrorDto.of(rowNumber, "No", "No는 숫자여야 합니다."));
}
String performanceId = StringUtil.normalizeBlank(row.getPerformanceId());
if (performanceId == null) {
errors.add(ExcelErrorDto.of(rowNumber, "연번", "연번을 입력해야 합니다."));
} else if (existingPerformanceIds.contains(performanceId)) {
errors.add(ExcelErrorDto.of(rowNumber, "연번", "이미 등록된 공연 ID입니다."));
}
validateCode(errors, rowNumber, "사업유형", row.getBusinessType(), businessTypeList);
validateCode(errors, rowNumber, "지역", row.getPerformanceArea(), areaList);
validateCode(
errors,
rowNumber,
"티켓 예약",
row.getTicketReservationStatus(),
ticketReservationStatusList
);
Integer performanceStartMonth = NumericUtil.parseOnlyInteger(row.getPerformanceStartMonth());
if(performanceStartMonth == null){
performanceStartMonth = 0;
}
else if (performanceStartMonth < 1 || performanceStartMonth > 12) {
errors.add(ExcelErrorDto.of(rowNumber, "사업 수행 월", "사업 수행 월은 1~12 사이 숫자여야 합니다."));
}
String monitoringDate = row.getMonitoringDate();
if (!StringUtil.isNullOrBlank(monitoringDate) && DateTimeUtil.parseLocalDate(monitoringDate) == null) {
errors.add(ExcelErrorDto.of(rowNumber, "모니터링 일정", "모니터링 일정은 yyyy-MM-dd 형식이어야 합니다."));
}
validateRequired(errors, rowNumber, "단체(인) 명", row.getArtistName());
validateRequired(errors, rowNumber, "사업 명", row.getPerformanceName());
validateRequired(errors, rowNumber, "모니터링 방문 장소", row.getMonitoringAddress());
validateStaff(errors, rowNumber, "대표자", row.getOwnStaffName(),
row.getOwnStaffTel1(), row.getOwnStaffTel2(), row.getOwnStaffEmail());
validateStaff(errors, rowNumber, "실무자", row.getContactStaffName(),
row.getContactStaffTel1(), row.getContactStaffTel2(), row.getContactStaffEmail());
return errors;
}
private void createPerformanceInternal(
PerformanceUploadDto row,
String regUser,
LocalDateTime regDt
) {
String performanceId = row.getPerformanceId().trim();
Integer performanceStartMonth = NumericUtil.parseOnlyInteger(row.getPerformanceStartMonth());
if(performanceStartMonth == null){
performanceStartMonth = 0;
}
TPerformanceEntity performance = TPerformanceEntity.builder()
.performanceId(performanceId)
.performanceNo(NumericUtil.parseOnlyInteger(row.getPerformanceNo()))
.businessType(NumericUtil.parseOnlyInteger(row.getBusinessType()))
.performanceArea(NumericUtil.parseOnlyInteger(row.getPerformanceArea()))
.artistName(Objects.toString(StringUtil.normalizeBlank(row.getArtistName()), ""))
.performanceName(Objects.toString(StringUtil.normalizeBlank(row.getPerformanceName()), ""))
.performanceStartMonth(performanceStartMonth)
.performanceDtInfo(Objects.toString(StringUtil.normalizeBlank(row.getPerformanceDtInfo()), ""))
.performanceTimeInfo(Objects.toString(StringUtil.normalizeBlank(row.getPerformanceTimeInfo()), ""))
.ticketReservationStatus(NumericUtil.parseOnlyInteger(row.getTicketReservationStatus()))
.ticketReservationMemo(Objects.toString(StringUtil.normalizeBlank(row.getTicketReservationMemo()), ""))
.performanceMemo(Objects.toString(StringUtil.normalizeBlank(row.getPerformanceMemo()), ""))
.regUser(regUser)
.regDt(regDt)
.build();
performanceRepository.save(performance);
savePerformanceUploadDetail(performanceId, row, regUser, regDt);
savePerformanceUploadStaff(performanceId, row, regUser, regDt);
savePerformanceUploadMonitoringSchedule(performanceId, row, regUser, regDt);
}
private void savePerformanceUploadDetail(
String performanceId,
PerformanceUploadDto row,
String regUser,
LocalDateTime regDt
) {
Map<String, String> detail = new LinkedHashMap<>();
detail.put("monitoringPaymentDate", Objects.toString(StringUtil.normalizeBlank(row.getMonitoringPaymentDate()), ""));
detail.put("performanceNo", Objects.toString(StringUtil.normalizeBlank(row.getPerformanceNo()), ""));
detail.put("performanceAreaDetail", Objects.toString(StringUtil.normalizeBlank(row.getPerformanceAreaDetail()), ""));
detail.put("consultingStatus", Objects.toString(StringUtil.normalizeBlank(row.getConsultingStatus()), ""));
detail.put("checkDeliver", Objects.toString(StringUtil.normalizeBlank(row.getCheckDeliver()), ""));
detail.put("checkReport", Objects.toString(StringUtil.normalizeBlank(row.getCheckReport()), ""));
detail.put("clientManagerName", Objects.toString(StringUtil.normalizeBlank(row.getClientManagerName()), ""));
List<TPerformanceDetailEntity> detailEntities = detail.entrySet().stream()
.map(entry -> TPerformanceDetailEntity.update(
performanceId,
entry.getKey(),
entry.getValue(),
regUser,
regDt
))
.toList();
performanceDetailRepository.saveAll(detailEntities);
}
private void savePerformanceUploadStaff(
String performanceId,
PerformanceUploadDto row,
String regUser,
LocalDateTime regDt
) {
List<TPerformanceStaffEntity> staffEntities = new ArrayList<>();
if (hasAnyText(row.getOwnStaffName(), row.getOwnStaffTel1(), row.getOwnStaffTel2(),
row.getOwnStaffEmail())) {
staffEntities.add(buildPerformanceStaff(
performanceId,
1,
row.getOwnStaffName(),
row.getOwnStaffTel1(),
row.getOwnStaffTel2(),
row.getOwnStaffEmail(),
regUser,
regDt
));
}
if (hasAnyText(row.getContactStaffName(), row.getContactStaffTel1(), row.getContactStaffTel2(),
row.getContactStaffEmail())) {
staffEntities.add(buildPerformanceStaff(
performanceId,
2,
row.getContactStaffName(),
row.getContactStaffTel1(),
row.getContactStaffTel2(),
row.getContactStaffEmail(),
regUser,
regDt
));
}
performanceStaffRepository.saveAll(staffEntities);
}
private TPerformanceStaffEntity buildPerformanceStaff(
String performanceId,
Integer staffType,
String staffName,
String staffTel1,
String staffTel2,
String staffEmail,
String regUser,
LocalDateTime regDt
) {
return TPerformanceStaffEntity.builder()
.performanceId(performanceId)
.staffType(staffType)
.staffName(Objects.toString(StringUtil.normalizeBlank(staffName), ""))
.staffTel1(TelUtil.normalizeTel(staffTel1))
.staffTel2(TelUtil.normalizeTel(staffTel2))
.staffEmail(Objects.toString(StringUtil.normalizeBlank(staffEmail), ""))
.regUser(regUser)
.regDt(regDt)
.build();
}
private void savePerformanceUploadMonitoringSchedule(
String performanceId,
PerformanceUploadDto row,
String regUser,
LocalDateTime regDt
) {
TPerformanceMonitoringScheduleEntity schedule =
TPerformanceMonitoringScheduleEntity.builder()
.performanceId(performanceId)
.monitoringDate(DateTimeUtil.parseLocalDate(row.getMonitoringDate()))
.monitoringTimeInfo(Objects.toString(StringUtil.normalizeBlank(row.getMonitoringTimeInfo()), ""))
.monitoringAddress(Objects.toString(StringUtil.normalizeBlank(row.getMonitoringAddress()), ""))
.regUser(regUser)
.regDt(regDt)
.build();
performanceMonitoringScheduleRepository.save(schedule);
}
private void validateCode(
List<ExcelErrorDto> errors,
int rowNumber,
String fieldName,
String value,
List<CodeDto> codeList
) {
Integer codeValue = NumericUtil.parseOnlyInteger(value);
if (codeValue == null || codeList.stream().noneMatch(code -> code.getCodeValue().equals(codeValue))) {
errors.add(ExcelErrorDto.of(rowNumber, fieldName, fieldName + " 코드가 유효하지 않습니다."));
}
}
private void validateRequired(
List<ExcelErrorDto> errors,
int rowNumber,
String fieldName,
String value
) {
if (!StringUtil.hasText(value)) {
errors.add(ExcelErrorDto.of(rowNumber, fieldName, fieldName + " 값이 비어 있습니다."));
}
}
private void validateStaff(
List<ExcelErrorDto> errors,
int rowNumber,
String staffLabel,
String staffName,
String staffTel1,
String staffTel2,
String staffEmail
) {
if (!hasAnyText(staffName, staffTel1, staffTel2, staffEmail)) {
return;
}
validateRequired(errors, rowNumber, staffLabel + " 명", staffName);
validateTel(errors, rowNumber, staffLabel + " 연락처1", staffTel1);
validateTel(errors, rowNumber, staffLabel + " 연락처2", staffTel2);
}
private void validateTel(
List<ExcelErrorDto> errors,
int rowNumber,
String fieldName,
String value
) {
if (!StringUtil.hasText(value)) {
return;
}
if (!TelUtil.validateTel(value)) {
errors.add(ExcelErrorDto.of(rowNumber, fieldName, fieldName + " 형식이 올바르지 않습니다."));
}
}
private boolean hasAnyText(String... values) {
return Arrays.stream(values).anyMatch(StringUtil::hasText);
}
private Map<String, String> getPerformanceDetailMap(String performanceId) {
return performanceDetailRepository.findByIdPerformanceId(performanceId).stream()
.collect(toMap(
TPerformanceDetailEntity::getPerformanceDetailKey,
TPerformanceDetailEntity::getPerformanceDetailValue
));
}
private List<PerformanceStaffDto> getPerformanceStaffList(String performanceId) {
return performanceStaffRepository.findByPerformanceId(performanceId).stream()
.map(PerformanceStaffDto::from)
.toList();
}
private PerformanceMonitoringScheduleDto getPerformanceMonitoringSchedule(String performanceId) {
return performanceMonitoringScheduleRepository.findFirstByPerformanceId(performanceId)
.map(PerformanceMonitoringScheduleDto::from)
.orElse(null);
}
private void updatePerformanceDetail(
String performanceId,
Map<String, String> performanceDetail,
String modUser,
LocalDateTime modDt
) {
Map<String, String> detail = performanceDetail == null
? Collections.emptyMap()
: performanceDetail;
List<TPerformanceDetailEntity> detailEntities = detail.entrySet().stream()
.map(entry -> TPerformanceDetailEntity.update(
performanceId,
entry.getKey(),
entry.getValue(),
modUser,
modDt
))
.toList();
performanceDetailRepository.saveAll(detailEntities);
}
private void updatePerformanceStaff(
String performanceId,
List<PerformanceStaffDto> performanceStaff,
String modUser,
LocalDateTime modDt
) {
performanceStaffRepository.deleteByPerformanceId(performanceId);
if (performanceStaff == null || performanceStaff.isEmpty()) {
return;
}
List<TPerformanceStaffEntity> staffEntities = performanceStaff.stream()
.map(dto -> {
TPerformanceStaffEntity entity = TPerformanceStaffEntity.from(dto);
entity.setId(null);
entity.setPerformanceId(performanceId);
entity.setRegUser(modUser);
entity.setRegDt(modDt);
return entity;
})
.toList();
performanceStaffRepository.saveAll(staffEntities);
}
private void upsertPerformanceMonitoringSchedule(
String performanceId,
PerformanceMonitoringScheduleDto dto,
String modUser,
LocalDateTime modDt
) {
if (dto == null) {
return;
}
performanceMonitoringScheduleRepository.findFirstByPerformanceId(performanceId)
.ifPresentOrElse(
entity -> entity.updateFromDto(dto, modUser, modDt),
() -> {
TPerformanceMonitoringScheduleEntity entity =
TPerformanceMonitoringScheduleEntity.from(dto);
entity.setId(null);
entity.setPerformanceId(performanceId);
entity.setRegUser(modUser);
entity.setRegDt(modDt);
performanceMonitoringScheduleRepository.save(entity);
}
);
}
private void validatePerformanceDeletable(String performanceId) {
if (assignService.hasAssignWithPerformance(performanceId)) {
throw BusinessException.conflict("PERFORMANCE_HAS_ASSIGN", "배정 정보가 있는 공연은 삭제할 수 없습니다.")
.with("performanceId", performanceId);
}
if (reviewService.hasReviewWithPerformance(performanceId)) {
throw BusinessException.conflict("PERFORMANCE_HAS_REVIEW", "평가 결과가 있는 공연은 삭제할 수 없습니다.")
.with("performanceId", performanceId);
}
}
private TPerformanceEntity getPerformanceEntity(String performanceId) {
return performanceRepository.findById(performanceId)
.orElseThrow(() ->
BusinessException.notFound("PERFORMANCE_NOT_FOUND", "공연을 찾을 수 없습니다.")
.with("performanceId", performanceId)
);
}
}

View File

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

View File

@@ -0,0 +1,329 @@
package com.kri.kmusical.manage.back.service;
import static com.kri.kmusical.manage.back.common.consts.KmusicalConstant.COMPLETE_STATUS;
import com.kri.common.feature.util.StringUtil;
import com.kri.common.feature.web.BusinessException;
import com.kri.kmusical.manage.back.config.FileStorageProperties;
import com.kri.kmusical.manage.back.dto.performance.PerformanceReviewDto;
import com.kri.kmusical.manage.back.persistence.entity.TPerformanceReviewEntity;
import com.kri.kmusical.manage.back.persistence.entity.id.TPerformanceReviewEntityId;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceReviewRepository;
import com.kri.kmusical.manage.back.persistence.repository.PerformanceAssignRepository;
import com.kri.kmusical.manage.back.service.file.AbstractFileService;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.PathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.multipart.MultipartFile;
@Service
public class ReviewService extends AbstractFileService {
private static final short PDF_CONVERT_PENDING = 0;
private static final short PDF_CONVERT_COMPLETE = 1;
private static final short PDF_CONVERT_NOT_TARGET = 8;
private final PerformanceReviewRepository performanceReviewRepository;
private final PerformanceAssignRepository performanceAssignRepository;
private final FileStorageProperties fileStorageProperties;
private final ReviewPdfConvertService reviewPdfConvertService;
private final Executor pdfConvertTaskExecutor;
public ReviewService(
PerformanceReviewRepository performanceReviewRepository,
PerformanceAssignRepository performanceAssignRepository,
FileStorageProperties fileStorageProperties,
ReviewPdfConvertService reviewPdfConvertService,
@Qualifier("pdfConvertTaskExecutor") Executor pdfConvertTaskExecutor
) {
this.performanceReviewRepository = performanceReviewRepository;
this.performanceAssignRepository = performanceAssignRepository;
this.fileStorageProperties = fileStorageProperties;
this.reviewPdfConvertService = reviewPdfConvertService;
this.pdfConvertTaskExecutor = pdfConvertTaskExecutor;
}
@Override
protected Path getBaseDir() {
return Path.of(fileStorageProperties.getReviewBaseDir())
.toAbsolutePath()
.normalize();
}
public boolean hasReviewWithUser(String userId) {
return performanceReviewRepository.existsByRegUserOrModUser(userId, userId);
}
public boolean hasReviewWithPerformance(String performanceId) {
return performanceReviewRepository.existsByIdPerformanceId(performanceId);
}
public Map<Integer, PerformanceReviewDto> findMapByPerformanceId(String performanceId) {
return performanceReviewRepository.findByIdPerformanceId(performanceId).stream()
.collect(Collectors.toMap(
TPerformanceReviewEntity::getReviewSlot,
PerformanceReviewDto::from
));
}
@Transactional
public PerformanceReviewDto uploadReviewFile(
String performanceId,
Integer reviewSlot,
MultipartFile file,
String userId,
LocalDateTime now
) {
validateAssignedUser(performanceId, reviewSlot, userId);
if (file == null || file.isEmpty()) {
throw BusinessException.badRequest("EMPTY_FILE", "업로드할 파일이 없습니다.");
}
try {
Path dir = reviewDir(performanceId, reviewSlot);
String uploadFileName = buildFileNameWithTime(file, now);
saveFile(dir, file, uploadFileName);
Path uploadPath = dir.resolve(uploadFileName).normalize();
boolean pdfFile = isPdf(uploadFileName);
boolean pdfConvertTarget = isPdfConvertTarget(uploadFileName);
String pdfFileName = pdfFile ? uploadFileName : "";
Short pdfConvert = resolveInitialPdfConvertStatus(pdfFile, pdfConvertTarget);
TPerformanceReviewEntity entity = performanceReviewRepository
.findByIdPerformanceIdAndIdReviewSlot(performanceId, reviewSlot)
.orElseGet(() -> TPerformanceReviewEntity.builder()
.id(TPerformanceReviewEntityId.builder()
.performanceId(performanceId)
.reviewSlot(reviewSlot)
.build())
.regDt(now)
.regUser(userId)
.build());
entity.setReviewStatus(COMPLETE_STATUS);
entity.setUploadFileName(uploadFileName);
entity.setPdfConvert(pdfConvert);
entity.setPdfFileName(pdfFileName);
entity.setPdfConvertDt(null);
if (entity.getRegUser() == null) {
entity.setRegUser(userId);
entity.setRegDt(now);
} else {
entity.setModUser(userId);
entity.setModDt(now);
}
TPerformanceReviewEntity saved = performanceReviewRepository.save(entity);
if (pdfConvert == PDF_CONVERT_PENDING) {
convertPdfAfterCommit(performanceId, reviewSlot, uploadFileName, uploadPath, dir);
}
return PerformanceReviewDto.from(saved);
} catch (IOException e) {
throw BusinessException.internalError("REVIEW_FILE_SAVE_FAILED", "평가/모니터링 파일 저장 중 오류가 발생했습니다.");
}
}
public PerformanceReviewDto getReviewFile(String performanceId, Integer reviewSlot) {
return PerformanceReviewDto.from(getReviewEntity(performanceId, reviewSlot));
}
private void convertPdfAfterCommit(
String performanceId,
Integer reviewSlot,
String uploadFileName,
Path uploadPath,
Path dir
) {
Runnable task = () -> reviewPdfConvertService.convertReviewFileToPdf(
performanceId,
reviewSlot,
uploadFileName,
uploadPath,
dir
);
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
pdfConvertTaskExecutor.execute(task);
}
});
return;
}
pdfConvertTaskExecutor.execute(task);
}
public PathResource getOriginalFileResource(String performanceId, Integer reviewSlot) {
TPerformanceReviewEntity entity = getReviewEntity(performanceId, reviewSlot);
return toResource(reviewDir(performanceId, reviewSlot).resolve(entity.getUploadFileName()));
}
public PathResource getOriginalFileZipResource(String performanceId, Integer reviewSlot) {
List<TPerformanceReviewEntity> reviews = performanceReviewRepository.findAll()
.stream()
.filter(review -> Integer.valueOf(reviewSlot).equals(review.getReviewSlot()))
.filter(review -> StringUtil.hasText(review.getUploadFileName()))
.toList();
if (reviews.isEmpty()) {
throw BusinessException.notFound("REVIEW_FILE_NOT_FOUND", "평가/모니터링 파일이 없습니다.")
.with("performanceId", performanceId)
.with("reviewSlot", reviewSlot);
}
try {
Path zip = Files.createTempFile(getOriginalFileZipBaseName(performanceId, reviewSlot), ".zip");
int entryCount = 0;
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
Set<String> entryNames = new HashSet<>();
for (TPerformanceReviewEntity review : reviews) {
Path sourceDir = reviewDir(review.getPerformanceId(), reviewSlot);
Path source = sourceDir.resolve(review.getUploadFileName()).normalize();
if (!source.startsWith(sourceDir) || !Files.exists(source) || !Files.isRegularFile(source)) {
continue;
}
String entryName = buildZipEntryName(review, entryNames);
out.putNextEntry(new ZipEntry(entryName));
Files.copy(source, out);
out.closeEntry();
entryCount++;
}
}
if (entryCount == 0) {
Files.deleteIfExists(zip);
throw BusinessException.notFound("REVIEW_FILE_NOT_FOUND", "평가/모니터링 파일이 없습니다.")
.with("performanceId", performanceId)
.with("reviewSlot", reviewSlot);
}
return new PathResource(zip);
} catch (IOException e) {
throw BusinessException.internalError("REVIEW_FILE_ZIP_FAILED", "평가/모니터링 파일 압축 중 오류가 발생했습니다.");
}
}
private String buildZipEntryName(TPerformanceReviewEntity review, Set<String> entryNames) {
String userId = StringUtil.isNullOrBlank(review.getRegUser()) ? "user" : review.getRegUser();
String fileName = removeTimestampPrefix(review.getUploadFileName());
String entryName = sanitizeZipEntryName(review.getPerformanceId() + "_" + userId + "_" + fileName);
if (entryNames.add(entryName)) {
return entryName;
}
String baseName = stripExtension(entryName);
String extension = extractExtension(entryName);
int index = 2;
while (true) {
String candidate = baseName + "_" + index + extension;
if (entryNames.add(candidate)) {
return candidate;
}
index++;
}
}
private String sanitizeZipEntryName(String fileName) {
String sanitized = Path.of(fileName).getFileName().toString()
.replace('\\', '_')
.replace('/', '_');
return StringUtil.isNullOrBlank(sanitized) ? "review-file" : sanitized;
}
private String getOriginalFileZipBaseName(String performanceId, Integer reviewSlot) {
return "review_" + performanceId + "_" + reviewSlot;
}
public PathResource getPdfOrOriginalFileResource(String performanceId, Integer reviewSlot) {
TPerformanceReviewEntity entity = getReviewEntity(performanceId, reviewSlot);
String fileName = StringUtil.isNullOrBlank(entity.getPdfFileName())
? entity.getUploadFileName()
: entity.getPdfFileName();
return toResource(reviewDir(performanceId, reviewSlot).resolve(fileName));
}
private TPerformanceReviewEntity getReviewEntity(String performanceId, Integer reviewSlot) {
return performanceReviewRepository.findByIdPerformanceIdAndIdReviewSlot(
performanceId,
reviewSlot
)
.orElseThrow(() -> BusinessException.notFound("REVIEW_FILE_NOT_FOUND", "평가/모니터링 파일이 없습니다.")
.with("performanceId", performanceId)
.with("reviewSlot", reviewSlot));
}
private void validateAssignedUser(String performanceId, Integer reviewSlot, String userId) {
performanceAssignRepository.findByIdPerformanceIdAndIdReviewSlot(performanceId, reviewSlot)
.filter(assign -> assign.getAssignUser().equals(userId))
.orElseThrow(() -> BusinessException.forbidden(
"REVIEW_ASSIGNMENT_REQUIRED",
"해당 평가 슬롯에 확정된 사용자만 평가할 수 있습니다."
)
.with("performanceId", performanceId)
.with("reviewSlot", reviewSlot));
}
private PathResource toResource(Path path) {
Path normalized = path.toAbsolutePath().normalize();
if (!Files.exists(normalized)) {
throw BusinessException.notFound("FILE_NOT_FOUND", "파일이 없습니다.");
}
return new PathResource(normalized);
}
private Path reviewDir(String performanceId, Integer reviewSlot) {
return getBaseDir()
.resolve(String.valueOf(performanceId))
.resolve(String.valueOf(reviewSlot))
.toAbsolutePath()
.normalize();
}
private String stripExtension(String fileName) {
int dot = fileName.lastIndexOf('.');
return dot > 0 ? fileName.substring(0, dot) : fileName;
}
private boolean isPdf(String fileName) {
return ".pdf".equalsIgnoreCase(extractExtension(fileName));
}
private Short resolveInitialPdfConvertStatus(boolean pdfFile, boolean pdfConvertTarget) {
if (pdfFile) {
return PDF_CONVERT_COMPLETE;
}
return pdfConvertTarget ? PDF_CONVERT_PENDING : PDF_CONVERT_NOT_TARGET;
}
private boolean isPdfConvertTarget(String fileName) {
String extension = extractExtension(fileName).toLowerCase();
return Set.of(".docx", ".hwpx", ".hwp", ".pptx", ".xlsx").contains(extension);
}
private String removeTimestampPrefix(String fileName) {
if (StringUtil.isNullOrBlank(fileName)) {
return fileName;
}
return fileName.replaceFirst("^\\d{4}-\\d{2}-\\d{2}_\\d{6}_", "");
}
}

View File

@@ -0,0 +1,164 @@
package com.kri.kmusical.manage.back.service;
import static com.kri.kmusical.manage.back.common.consts.KmusicalConstant.REVIEW_TYPE;
import com.kri.common.feature.util.StringUtil;
import com.kri.common.feature.web.BusinessException;
import com.kri.kmusical.manage.back.config.FileStorageProperties;
import com.kri.kmusical.manage.back.service.file.AbstractFileService;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.PathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
@RequiredArgsConstructor
public class ReviewTemplateService extends AbstractFileService {
private final FileStorageProperties fileStorageProperties;
@Value("${kri.file.pdf-converter-command:soffice}")
private String pdfConverterCommand;
@Override
protected Path getBaseDir() {
return Path.of(fileStorageProperties.getReviewTemplateBaseDir())
.toAbsolutePath()
.normalize();
}
public String uploadReviewTemplate(Integer reviewType, MultipartFile file) {
validateReviewTemplateType(reviewType);
if (file == null || file.isEmpty()) {
throw BusinessException.badRequest("EMPTY_FILE", "업로드된 파일이 없습니다.");
}
String fileName = sanitizeFileName(file.getOriginalFilename());
Path dir = templateDir(reviewType);
try {
deleteExistingFiles(dir);
saveFile(dir, file, fileName);
Path uploadPath = dir.resolve(fileName).normalize();
convertToPdfIfPossible(uploadPath, dir);
return fileName;
} catch (IOException e) {
throw BusinessException.internalError("REVIEW_TEMPLATE_SAVE_FAILED", "평가양식 파일 저장 중 오류가 발생했습니다.");
}
}
public PathResource getReviewTemplateResource(Integer reviewType) {
Path file = findReviewTemplateFile(reviewType, false);
return new PathResource(file);
}
public PathResource getReviewTemplatePdfResource(Integer reviewType) {
Path file = findReviewTemplateFile(reviewType, true);
return new PathResource(file);
}
private Path findReviewTemplateFile(Integer reviewType, boolean pdf) {
validateReviewTemplateType(reviewType);
Path dir = templateDir(reviewType);
if (!Files.isDirectory(dir)) {
throw BusinessException.notFound("REVIEW_TEMPLATE_NOT_FOUND", "평가양식 파일이 없습니다.")
.with("reviewType", reviewType);
}
try (var files = Files.list(dir)) {
return files
.filter(Files::isRegularFile)
.filter(path -> pdf == isPdf(path.getFileName().toString()))
.sorted(Comparator.comparing(path -> path.getFileName().toString()))
.findFirst()
.orElseThrow(() -> BusinessException.notFound("REVIEW_TEMPLATE_NOT_FOUND", "평가양식 파일이 없습니다.")
.with("reviewType", reviewType));
} catch (IOException e) {
throw BusinessException.internalError("REVIEW_TEMPLATE_READ_FAILED", "평가양식 파일 조회 중 오류가 발생했습니다.");
}
}
private void deleteExistingFiles(Path dir) throws IOException {
if (!Files.isDirectory(dir)) {
return;
}
try (var files = Files.list(dir)) {
for (Path file : files.filter(Files::isRegularFile).toList()) {
Files.deleteIfExists(file);
}
}
}
private String convertToPdfIfPossible(Path source, Path dir) {
String extension = extractExtension(source.getFileName().toString()).toLowerCase();
Set<String> targets = new HashSet<>(Set.of(".docx", ".hwpx", ".hwp", ".pptx", ".xlsx"));
if (isPdf(source.getFileName().toString()) || !targets.contains(extension)) {
return "";
}
try {
Process process = new ProcessBuilder(
pdfConverterCommand,
"--headless",
"--convert-to",
"pdf",
"--outdir",
dir.toString(),
source.toString()
).redirectErrorStream(true).start();
boolean finished = process.waitFor(60, TimeUnit.SECONDS);
if (!finished || process.exitValue() != 0) {
process.destroyForcibly();
return "";
}
String baseName = stripExtension(source.getFileName().toString());
Path pdf = dir.resolve(baseName + ".pdf").normalize();
return Files.exists(pdf) ? pdf.getFileName().toString() : "";
} catch (Exception e) {
return "";
}
}
private String stripExtension(String fileName) {
int dot = fileName.lastIndexOf('.');
return dot > 0 ? fileName.substring(0, dot) : fileName;
}
private boolean isPdf(String fileName) {
return ".pdf".equalsIgnoreCase(extractExtension(fileName));
}
private Path templateDir(Integer reviewType) {
return getBaseDir()
.resolve(String.valueOf(reviewType))
.toAbsolutePath()
.normalize();
}
private void validateReviewTemplateType(Integer reviewType) {
if (!REVIEW_TYPE.contains(reviewType)) {
throw BusinessException.badRequest("INVALID_REVIEW_TEMPLATE_TYPE", "유효하지 않은 평가양식 타입입니다.")
.with("reviewType", reviewType);
}
}
private String sanitizeFileName(String originalFileName) {
if (StringUtil.isNullOrBlank(originalFileName)) {
return "review-template";
}
return Path.of(originalFileName).getFileName().toString();
}
}

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