Merge pull request 'develop' (#2) from develop into master

Reviewed-on: #2
This commit is contained in:
2026-11-04 15:18:21 +09:00
38 changed files with 1245 additions and 133 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

Binary file not shown.