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

Reviewed-on: #1
This commit is contained in:
2026-10-27 09:05:08 +09:00
66 changed files with 450 additions and 459 deletions

View File

@@ -145,6 +145,7 @@
- Derived create/update/delete and single/all recalculate routes are under /project/{projectType}/{pkey}/derived. Preserve saved QUESTIONJSON/DERIVEDJSON and original single/multi/ELSE/open-num response keys; parse legacy conditions through shared service/statistics/LegacyFilterService and compute with StatisticsFilterService. Unsupported SQL grammar is explicit failure, not SQL execution. Quota retains QUOTA_FILTER_INVALID at its boundary. - Derived create/update/delete and single/all recalculate routes are under /project/{projectType}/{pkey}/derived. Preserve saved QUESTIONJSON/DERIVEDJSON and original single/multi/ELSE/open-num response keys; parse legacy conditions through shared service/statistics/LegacyFilterService and compute with StatisticsFilterService. Unsupported SQL grammar is explicit failure, not SQL execution. Quota retains QUOTA_FILTER_INVALID at its boundary.
- Use KON/KONKIWI-specific TransactionTemplate with project locking for definition/data writes and order changes. Preserve other JSON groups with bound JSON_MODIFY paths and original GETDATE timestamp behavior. actor/team come from RequestUserContext, logs through LogService. Return IDs/boolean/counts; frontend owns messages. Shared DB execution and ordinary role authorization are separate. - Use KON/KONKIWI-specific TransactionTemplate with project locking for definition/data writes and order changes. Preserve other JSON groups with bound JSON_MODIFY paths and original GETDATE timestamp behavior. actor/team come from RequestUserContext, logs through LogService. Return IDs/boolean/counts; frontend owns messages. Shared DB execution and ordinary role authorization are separate.
- Per user decision (2026-10-23), derived values take precedence over raw DATA keys with the same derived ID: derived calculation ignores raw DATA keys of every stored derived ID. Statistics/Export SQL is unchanged (approach C2: keep such keys out of DATA instead of rewriting read queries). An update whose variable ID equals originId (case-insensitive) skips the duplicate check; renames and creates keep the full check.
- Aggregate Excel POST routes are /project/{projectType}/{pkey}/export/excel/table and /quota/{projectType}/{pkey}/export/excel. Accept typed ordered tables/turn and legacy cell display/span strings, retaining frontend N/% presentation choice; do not requery raw data. Keep original workbook layout, multiple quota sheets and complete/target output. Link scopes must allow only their matching aggregate paths. - Aggregate Excel POST routes are /project/{projectType}/{pkey}/export/excel/table and /quota/{projectType}/{pkey}/export/excel. Accept typed ordered tables/turn and legacy cell display/span strings, retaining frontend N/% presentation choice; do not requery raw data. Keep original workbook layout, multiple quota sheets and complete/target output. Link scopes must allow only their matching aggregate paths.
- Use KriCommon ExcelMapper then format with current POI, without new dependencies. Wordcloud input is validated PNG Base64 from frontend, preserving original 1000x512 position; no SVG or external URL loading. Use static measured Malgun Gothic glyph advances to avoid platform autoSize changes. Compare original EPPlus workbooks: cells/styles/merged ranges/row sizes exact, column rounding within one 1/256-character unit and image anchor rounding within one pixel. Actual production files, shaping/emoji, frontend PNG/render/download and live SQL checks remain separate. - Use KriCommon ExcelMapper then format with current POI, without new dependencies. Wordcloud input is validated PNG Base64 from frontend, preserving original 1000x512 position; no SVG or external URL loading. Use static measured Malgun Gothic glyph advances to avoid platform autoSize changes. Compare original EPPlus workbooks: cells/styles/merged ranges/row sizes exact, column rounding within one 1/256-character unit and image anchor rounding within one pixel. Actual production files, shaping/emoji, frontend PNG/render/download and live SQL checks remain separate.
@@ -157,8 +158,8 @@
## Upload migration ## Upload migration
- Implement POST /project/{projectType}/{pkey}/import/title, /question and /data as multipart file uploads. Return processedRows/affectedRows/removedRows/archivedRows; no presentation messages. Common JWT is required; the existing External allowlist denies all imports. Ordinary role/team restrictions stay deferred. - Implement POST /project/{projectType}/{pkey}/import/title, /question and /data as multipart file uploads. Return processedRows/affectedRows/removedRows/archivedRows; no presentation messages. Common JWT is required; the existing External allowlist denies all imports. Ordinary role/team restrictions stay deferred.
- Title upload resets eligible explain values, then updates only explain by pkey/QID; variable/title are ignored, unknown IDs no-op and duplicate IDs are sequential. Question upload resets QUESTION/QOPTION/QUOTASET/QUOTA(original QSORDER condition) and STRUCTURE before sequential Q1/Qorder creation; retain existing dataset/option quirks and JSON strings in QINFO/LINFO, never introduce JSON_QUERY around those string parameters. - Title upload resets eligible explain values, then updates only explain by pkey/QID; variable/title are ignored, unknown IDs no-op and duplicate IDs are sequential. Question upload resets QUESTION/QOPTION/QUOTASET/QUOTA(original QSORDER condition) and STRUCTURE before sequential Q1/Qorder creation; retain existing dataset/option quirks and JSON strings in QINFO/LINFO, never introduce JSON_QUERY around those string parameters. Per user decision (2026-10-22), O/N questions with no input rows (none, attribute-only or blank titles) get one open input {label:"", option all/num, must 1} instead of failing; other types still require choices.
- Data upload deletes UPLOAD responses, moves actual completed responses to DEL_+PKEY, and inserts UPLOAD rows; do not mutate TEST/incomplete/other projects/DERIVED_DATA. Preserve two header rows, six distinct fixed-group skip, multi pull-up keys including duplicates, INDEX and midpoint/final timestamps, empty defaults and original text normalization. - Data upload deletes UPLOAD responses, moves actual completed responses to DEL_+PKEY, and inserts UPLOAD rows; do not mutate TEST/incomplete/other projects. Per user decision (2026-10-23), columns equal to a stored derived ID or starting with "{ID}_" (case-insensitive) are not uploaded, and after all rows are inserted every derived variable is recalculated in the same KON/KONKIWI transaction (no role check or extra SiteLog; failure rolls back the upload). Preserve two header rows, six distinct fixed-group skip, multi pull-up keys including duplicates, INDEX and midpoint/final timestamps, empty defaults and original text normalization.
- Parse/convert the entire file before destructive SQL; all changes use the selected KON/KONKIWI transaction with a project lock and rollback. SQL values/JSON paths are bound. No shared DB execution or schema changes are authorized. - Parse/convert the entire file before destructive SQL; all changes use the selected KON/KONKIWI transaction with a project lock and rollback. SQL values/JSON paths are bound. No shared DB execution or schema changes are authorized.
- Preserve xlsx first-sheet/positional columns/blank rows/cached formulas and csv/txt simple delimiter plus EUC-KR/BOM behavior. Use Common ExcelUtil; its map reader drops rows and changes positional/formula rules, so a domain-specific POI reader is necessary. Existing 20MB limit applies. - Preserve xlsx first-sheet/positional columns/blank rows/cached formulas and csv/txt simple delimiter plus EUC-KR/BOM behavior. Use Common ExcelUtil; its map reader drops rows and changes positional/formula rules, so a domain-specific POI reader is necessary. Existing 20MB limit applies.
- Keep original file archives under kri.kart.upload.directory (./upload_data, Git ignored) and Upload File logging through LogService with authenticated context. Archives and best-effort audit attempts may remain after database rollback; do not expose stored paths or raw content on parse errors. - Keep original file archives under kri.kart.upload.directory (./upload_data, Git ignored) and Upload File logging through LogService with authenticated context. Archives and best-effort audit attempts may remain after database rollback; do not expose stored paths or raw content on parse errors.
@@ -180,7 +181,7 @@
- User approved: userRole 1001 has no authenticated-team/assignment limit in project list/summary. This intentionally unifies legacy admin 0 and DCO 1. Existing business search/exclusion filters still apply. - User approved: userRole 1001 has no authenticated-team/assignment limit in project list/summary. This intentionally unifies legacy admin 0 and DCO 1. Existing business search/exclusion filters still apply.
- Controller RequestUserContext is authoritative for role/team/id for JWT and API Key. No permission enums/grants or user-submitted authorization claims. Missing project identity metadata fails instead of broadening visibility. - Controller RequestUserContext is authoritative for role/team/id for JWT and API Key. No permission enums/grants or user-submitted authorization claims. Missing project identity metadata fails instead of broadening visibility.
- Preserve current frontend v2 KON/KIWI list branching for other roles: team != M101 excludes GKEY M101; R-prefixed teams additionally require own GKEY; team M101 list has no extra team filter. Summary preserves its different legacy if/else-if: M101 team only own GKEY, all other teams exclude M101, including R teams without an added own-team condition. - Preserve current frontend v2 KON/KIWI list branching for other roles: team != M101 excludes GKEY M101; R-prefixed teams additionally require own GKEY; team M101 list has no extra team filter. Summary: M101 team only own GKEY, all other teams exclude M101, and (user decision 2026-10-22, replacing the legacy else-if) R-prefixed teams additionally require own GKEY, matching the list. Per the same user decision, summary candidates also apply the list's title NOT LIKE '%사례비%' and status IN (2, 3) before TOP 50; the list's date/surveyclass/must-view window is intentionally not added.
- Role 9001 additionally intersects REPORT_ASSIGN by exact member_mail=verified userId. Query the kart session (Report DB) once per request for both survey sources, do not add is_use (not used by original), do not append email domains, and empty assignments return no rows. REPORT_MEMBER emits exact member_mail as userId; other authentication also uses verified userId verbatim. - Role 9001 additionally intersects REPORT_ASSIGN by exact member_mail=verified userId. Query the kart session (Report DB) once per request for both survey sources, do not add is_use (not used by original), do not append email domains, and empty assignments return no rows. REPORT_MEMBER emits exact member_mail as userId; other authentication also uses verified userId verbatim.
- Apply team/assignment before candidate TOP 50 and ordering, never after Java merge/TOP 6. Must-view does not override authorization. Linked list retains its business query team and adds separately named authenticated-team/role/assignment constraints. - Apply team/assignment before candidate TOP 50 and ordering, never after Java merge/TOP 6. Must-view does not override authorization. Linked list retains its business query team and adds separately named authenticated-team/role/assignment constraints.
- Derived management list: role 1001 sees all project definitions; others see matching GKEY only. Keep normal questions/report metadata unfiltered by this management rule. - Derived management list: role 1001 sees all project definitions; others see matching GKEY only. Keep normal questions/report metadata unfiltered by this management rule.

View File

@@ -55,7 +55,7 @@ configurations.configureEach {
} }
dependencies { dependencies {
implementation 'com.kri.common:starter:beta.1.6.9' implementation 'com.kri.common:starter:beta.1.7.0'
implementation 'org.apache.poi:poi-ooxml:5.5.1' implementation 'org.apache.poi:poi-ooxml:5.5.1'
implementation "kr.pe.bab2min:kiwi-java:${kiwiVersion}:${kiwiPlatform}@jar" implementation "kr.pe.bab2min:kiwi-java:${kiwiVersion}:${kiwiPlatform}@jar"

View File

@@ -104,7 +104,7 @@ public class ExportController {
private ResponseEntity<byte[]> download(ExportFileDto file) { private ResponseEntity<byte[]> download(ExportFileDto file) {
String fileName = String fileName =
FileUtil.extractFileNameFromPath(file.getFileName()) FileUtil.extractFileNameFromPath(file.fileName())
.replaceAll("[\\p{Cntrl}\\\\/:*?\"<>|]", "_"); .replaceAll("[\\p{Cntrl}\\\\/:*?\"<>|]", "_");
String disposition = String disposition =
ContentDisposition.attachment() ContentDisposition.attachment()
@@ -115,6 +115,6 @@ public class ExportController {
.contentType(MediaType.APPLICATION_OCTET_STREAM) .contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, disposition) .header(HttpHeaders.CONTENT_DISPOSITION, disposition)
.header(HttpHeaders.CACHE_CONTROL, "no-store") .header(HttpHeaders.CACHE_CONTROL, "no-store")
.body(file.getContent()); .body(file.content());
} }
} }

View File

@@ -32,12 +32,12 @@ public class LogController {
ShareLinkDto link = ShareLinkDto link =
(ShareLinkDto) servletRequest.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE); (ShareLinkDto) servletRequest.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE);
if (link != null if (link != null
&& (link.getProjectType() != request.getProjectType() && (link.projectType() != request.projectType()
|| !link.getPkey().equals(request.getPkey()))) { || !link.pkey().equals(request.pkey()))) {
throw BusinessException.forbidden("EXTERNAL_SCOPE_DENIED", "공유 프로젝트의 방문 로그만 기록할 수 있습니다."); throw BusinessException.forbidden("EXTERNAL_SCOPE_DENIED", "공유 프로젝트의 방문 로그만 기록할 수 있습니다.");
} }
logService.writeVisitLog( logService.writeVisitLog(
request.getProjectType(), request.getPkey(), request.getLogContent(), ctx); request.projectType(), request.pkey(), request.logContent(), ctx);
return "PASS"; return "PASS";
} }
} }

View File

@@ -85,7 +85,7 @@ public class StatisticsController {
ShareLinkDto link = ShareLinkDto link =
(ShareLinkDto) servletRequest.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE); (ShareLinkDto) servletRequest.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE);
return link != null return link != null
&& link.isPageOnly() && link.pageOnly()
&& URI.create(link.getRealUrl()).getPath().equals(KartConstant.CROSSTAB_PAGE); && URI.create(link.realUrl()).getPath().equals(KartConstant.CROSSTAB_PAGE);
} }
} }

View File

@@ -2,16 +2,11 @@ package com.kri.kart.server.dto.auth;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "로그인 요청") @Schema(description = "로그인 요청")
public class LoginRequestDto { public record LoginRequestDto(
@NotBlank private String userId; @NotBlank String userId,
@NotBlank @NotBlank
@Schema(accessMode = Schema.AccessMode.WRITE_ONLY) @Schema(accessMode = Schema.AccessMode.WRITE_ONLY)
private String userPw; String userPw) {}
}

View File

@@ -1,13 +1,8 @@
package com.kri.kart.server.dto.auth; package com.kri.kart.server.dto.auth;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto; import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter public record LoginResponseDto(
@AllArgsConstructor String accessToken,
public class LoginResponseDto { JwtUserClaimsDto user,
private final String accessToken; String memberRedirect) {}
private final JwtUserClaimsDto user;
private final String memberRedirect;
}

View File

@@ -5,30 +5,25 @@ import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Pattern;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class BookmarkSaveRequestDto {
public interface Create {}
public record BookmarkSaveRequestDto(
@Schema(description = "생성 시 필수. 수정 시 페이지는 변경하지 않음") @Schema(description = "생성 시 필수. 수정 시 페이지는 변경하지 않음")
@NotNull(groups = Create.class) @NotNull(groups = Create.class)
@Pattern(regexp = "TABULATION|CROSSTAB") @Pattern(regexp = "TABULATION|CROSSTAB")
private String bookmarkPage; String bookmarkPage,
@NotNull @NotNull
private String bookmarkTitle; String bookmarkTitle,
@NotNull @NotNull
private String bookmarkInfo; String bookmarkInfo,
@Schema(description = "기존 북마크 설정 JSON 문자열. 저장 시 원문 유지") @Schema(description = "기존 북마크 설정 JSON 문자열. 저장 시 원문 유지")
@NotNull @NotNull
private String bookmarkJson; String bookmarkJson,
@NotNull @NotNull
@Min(0) @Min(0)
@Max(1) @Max(1)
private Integer isOpen; Integer isOpen) {
public interface Create {}
} }

View File

@@ -1,9 +1,6 @@
package com.kri.kart.server.dto.derived; package com.kri.kart.server.dto.derived;
import lombok.Value;
@Value public record DerivedCalculationDto(
public class DerivedCalculationDto { int variableCount,
int variableCount; int matchedRespondents) {}
int matchedRespondents;
}

View File

@@ -5,24 +5,19 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter public record DerivedSaveRequestDto(
@Setter
public class DerivedSaveRequestDto {
@NotBlank @NotBlank
@Size(max = 128) @Size(max = 128)
@Pattern(regexp = "[A-Za-z][A-Za-z0-9_]*") @Pattern(regexp = "[A-Za-z][A-Za-z0-9_]*")
private String variableId; String variableId,
@NotBlank @NotBlank
@Size(max = 4000) @Size(max = 4000)
private String variableTitle; String variableTitle,
@NotNull @NotNull
@Pattern(regexp = "single|multi|scale|num") @Pattern(regexp = "single|multi|scale|num")
private String variableType; String variableType,
@NotNull private JsonNode variableInfo; @NotNull JsonNode variableInfo) {}
}

View File

@@ -5,16 +5,11 @@ import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import java.util.List; import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Getter public record AggregateExcelRequestDto(
@Setter
public class AggregateExcelRequestDto {
@Valid @Valid
@NotEmpty @NotEmpty
@Size(max = 1000) @Size(max = 1000)
private List<@NotNull AggregateExcelTableDto> tables; List<@NotNull AggregateExcelTableDto> tables,
private boolean turn; boolean turn) {}
}

View File

@@ -1,11 +1,6 @@
package com.kri.kart.server.dto.export; package com.kri.kart.server.dto.export;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter public record ExportFileDto(
@RequiredArgsConstructor String fileName,
public class ExportFileDto { byte[] content) {}
private final String fileName;
private final byte[] content;
}

View File

@@ -1,24 +1,19 @@
package com.kri.kart.server.dto.export; package com.kri.kart.server.dto.export;
import com.kri.common.feature.excel.ExcelColumn; import com.kri.common.feature.excel.ExcelColumn;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter public record ExportGuideDto(
@AllArgsConstructor
public class ExportGuideDto {
@ExcelColumn(header = "문항 타입", order = 0) @ExcelColumn(header = "문항 타입", order = 0)
private String questionType; String questionType,
@ExcelColumn(header = "문항 / 보기번호", order = 1) @ExcelColumn(header = "문항 / 보기번호", order = 1)
private String variable; String variable,
@ExcelColumn(header = "내용", order = 2) @ExcelColumn(header = "내용", order = 2)
private String content; String content,
@ExcelColumn(header = "VALUE LABEL", order = 3) @ExcelColumn(header = "VALUE LABEL", order = 3)
private String valueLabel; String valueLabel,
@ExcelColumn(header = "VARIABLE LABEL", order = 4) @ExcelColumn(header = "VARIABLE LABEL", order = 4)
private String variableLabel; String variableLabel) {}
}

View File

@@ -5,20 +5,15 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "화면 방문 로그. 프로젝트 정보는 둘 다 생략하거나 함께 지정한다.") @Schema(description = "화면 방문 로그. 프로젝트 정보는 둘 다 생략하거나 함께 지정한다.")
public class VisitLogRequestDto { public record VisitLogRequestDto(
private ProjectType projectType; ProjectType projectType,
@Size(max = 20) @Size(max = 20)
@Pattern(regexp = "^[^|]*$") @Pattern(regexp = "^[^|]*$")
private String pkey; String pkey,
@NotBlank @NotBlank
@Schema(description = "방문한 화면 URL 또는 페이지 정보") @Schema(description = "방문한 화면 URL 또는 페이지 정보")
private String logContent; String logContent) {}
}

View File

@@ -2,19 +2,14 @@ package com.kri.kart.server.dto.project;
import com.kri.common.feature.web.BusinessException; import com.kri.common.feature.web.BusinessException;
import java.time.LocalDate; import java.time.LocalDate;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
@Getter public record ProgressSearchDto(
@Setter
public class ProgressSearchDto {
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate startDate; LocalDate startDate,
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate endDate; LocalDate endDate) {
public void validateRange() { public void validateRange() {
if ((startDate == null) != (endDate == null) if ((startDate == null) != (endDate == null)
|| (startDate != null && startDate.isAfter(endDate))) { || (startDate != null && startDate.isAfter(endDate))) {

View File

@@ -3,21 +3,16 @@ package com.kri.kart.server.dto.project;
import com.kri.kart.server.common.enums.ProjectType; import com.kri.kart.server.common.enums.ProjectType;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter public record ProjectLinkSearchDto(
@Setter ProjectType projectType,
public class ProjectLinkSearchDto {
private ProjectType projectType;
@Size(max = 128) @Size(max = 128)
@Schema(description = "서비스 연동 조회용 인트라넷 프로젝트 코드. 첫 _ 앞 부분으로 검색") @Schema(description = "서비스 연동 조회용 인트라넷 프로젝트 코드. 첫 _ 앞 부분으로 검색")
private String intranetCode; String intranetCode,
@Size(max = 32) @Size(max = 32)
private String userTeam; String userTeam,
@Size(max = 512) @Size(max = 512)
private String keyword; String keyword) {}
}

View File

@@ -3,26 +3,19 @@ package com.kri.kart.server.dto.project;
import com.kri.kart.server.common.enums.ProjectType; import com.kri.kart.server.common.enums.ProjectType;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Objects; import java.util.Objects;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@Getter
@EqualsAndHashCode
@Schema(description = "프로젝트 유형과 프로젝트 키") @Schema(description = "프로젝트 유형과 프로젝트 키")
public final class ProjectRefDto { public record ProjectRefDto(
@Schema(description = "프로젝트 유형: 0=KON, 1=KIWI") @Schema(description = "프로젝트 유형: 0=KON, 1=KIWI")
private final ProjectType projectType; ProjectType projectType,
@Schema(description = "프로젝트 키", maxLength = 20) @Schema(description = "프로젝트 키", maxLength = 20)
private final String pkey; String pkey) {
public ProjectRefDto {
public ProjectRefDto(ProjectType projectType, String pkey) {
Objects.requireNonNull(projectType, "Project type is required"); Objects.requireNonNull(projectType, "Project type is required");
if (pkey == null || pkey.isBlank() || pkey.length() > 20 || pkey.contains("|")) { if (pkey == null || pkey.isBlank() || pkey.length() > 20 || pkey.contains("|")) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Project key must be nonblank, at most 20 UTF-16 units, without legacy markers"); "Project key must be nonblank, at most 20 UTF-16 units, without legacy markers");
} }
this.projectType = projectType;
this.pkey = pkey;
} }
} }

View File

@@ -1,20 +1,17 @@
package com.kri.kart.server.dto.quota; package com.kri.kart.server.dto.quota;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
@Getter
@Builder @Builder
public class QuotaCellDto { public record QuotaCellDto(
private int columnIndex; int columnIndex,
private String kind; String kind,
private String textValue; String textValue,
private Long complete; Long complete,
private Long target; Long target,
private Double achievementPercent; Double achievementPercent,
private String achievementState; String achievementState,
private String achievementDisplayText; String achievementDisplayText,
private String displayText; String displayText,
private String isUsed; String isUsed,
private Long quotaId; Long quotaId) {}
}

View File

@@ -4,17 +4,14 @@ import com.kri.kart.server.dto.statistics.StatisticsColumnDto;
import com.kri.kart.server.dto.statistics.StatisticsRowDto; import com.kri.kart.server.dto.statistics.StatisticsRowDto;
import java.util.List; import java.util.List;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
@Getter
@Builder @Builder
public class QuotaResultDto { public record QuotaResultDto(
private Long quotaSetId; Long quotaSetId,
private Integer quotaOrder; Integer quotaOrder,
private String title; String title,
private String index; String index,
private List<List<String>> banners; List<List<String>> banners,
private List<StatisticsColumnDto> columns; List<StatisticsColumnDto> columns,
private List<StatisticsRowDto> headerRows; List<StatisticsRowDto> headerRows,
private List<QuotaRowDto> rows; List<QuotaRowDto> rows) {}
}

View File

@@ -1,14 +1,9 @@
package com.kri.kart.server.dto.quota; package com.kri.kart.server.dto.quota;
import java.util.List; import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter public record QuotaRowDto(
@AllArgsConstructor int rowIndex,
public class QuotaRowDto { String rowId,
private int rowIndex; String kind,
private String rowId; List<QuotaCellDto> cells) {}
private String kind;
private List<QuotaCellDto> cells;
}

View File

@@ -1,11 +1,8 @@
package com.kri.kart.server.dto.share; package com.kri.kart.server.dto.share;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto; import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import lombok.Value;
@Value public record ExternalLoginResponseDto(
public class ExternalLoginResponseDto { String accessToken,
String accessToken; JwtUserClaimsDto user,
JwtUserClaimsDto user; ShareLinkDto link) {}
ShareLinkDto link;
}

View File

@@ -1,15 +1,12 @@
package com.kri.kart.server.dto.share; package com.kri.kart.server.dto.share;
import com.kri.kart.server.common.enums.ProjectType; import com.kri.kart.server.common.enums.ProjectType;
import lombok.Value;
@Value public record ShareLinkDto(
public class ShareLinkDto { String urlKey,
String urlKey; String url,
String url; String realUrl,
String realUrl; ProjectType projectType,
ProjectType projectType; String pkey,
String pkey; String projectTitle,
String projectTitle; boolean pageOnly) {}
boolean pageOnly;
}

View File

@@ -3,17 +3,12 @@ package com.kri.kart.server.dto.share;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter public record ShareLinkRequestDto(
@Setter
public class ShareLinkRequestDto {
@NotBlank @NotBlank
@Size(max = 4096) @Size(max = 4096)
private String realUrl; String realUrl,
@NotBlank @NotBlank
@Pattern(regexp = "P|U") @Pattern(regexp = "P|U")
private String mode; String mode) {}
}

View File

@@ -1,13 +1,8 @@
package com.kri.kart.server.dto.statistics; package com.kri.kart.server.dto.statistics;
import java.util.List; import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter public record StatisticsColumnDto(
@AllArgsConstructor String columnId,
public class StatisticsColumnDto { String kind,
private final String columnId; List<String> labels) {}
private final String kind;
private final List<String> labels;
}

View File

@@ -2,17 +2,14 @@ package com.kri.kart.server.dto.statistics;
import java.util.List; import java.util.List;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
@Getter
@Builder @Builder
public class StatisticsResponseDto { public record StatisticsResponseDto(
private String type; String type,
private String questionId; String questionId,
private String title; String title,
private List<StatisticsColumnDto> columns; List<StatisticsColumnDto> columns,
private List<StatisticsRowDto> headerRows; List<StatisticsRowDto> headerRows,
private List<StatisticsRowDto> rows; List<StatisticsRowDto> rows,
private List<StatisticsWordDto> words; List<StatisticsWordDto> words,
private StatisticsRequestDto appliedOptions; StatisticsRequestDto appliedOptions) {}
}

View File

@@ -1,14 +1,9 @@
package com.kri.kart.server.dto.statistics; package com.kri.kart.server.dto.statistics;
import java.util.List; import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter public record StatisticsRowDto(
@AllArgsConstructor int rowIndex,
public class StatisticsRowDto { String rowId,
private final int rowIndex; String kind,
private final String rowId; List<StatisticsCellDto> cells) {}
private final String kind;
private final List<StatisticsCellDto> cells;
}

View File

@@ -3,21 +3,18 @@ package com.kri.kart.server.dto.statistics;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder; import lombok.Builder;
import lombok.Getter;
@Getter
@Builder @Builder
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(description = "NDJSON 한 줄 이벤트. result/error는 문항별, complete는 스트림 완료") @Schema(description = "NDJSON 한 줄 이벤트. result/error는 문항별, complete는 스트림 완료")
public class StatisticsStreamEventDto { public record StatisticsStreamEventDto(
private String type; String type,
private Integer position; Integer position,
private String index; String index,
private StatisticsResponseDto result; StatisticsResponseDto result,
private Integer status; Integer status,
private String code; String code,
private String message; String message,
private Integer total; Integer total,
private Integer succeeded; Integer succeeded,
private Integer failed; Integer failed) {}
}

View File

@@ -3,13 +3,8 @@ package com.kri.kart.server.dto.statistics;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotEmpty;
import java.util.List; import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Getter public record StatisticsValueGroupDto(
@Setter @NotBlank String label,
public class StatisticsValueGroupDto {
@NotBlank private String label;
@NotEmpty private List<@NotBlank String> values; @NotEmpty List<@NotBlank String> values) {}
}

View File

@@ -1,12 +1,7 @@
package com.kri.kart.server.dto.statistics; package com.kri.kart.server.dto.statistics;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter public record StatisticsWordDto(
@AllArgsConstructor String text,
public class StatisticsWordDto { String tag,
private final String text; long count) {}
private final String tag;
private final long count;
}

View File

@@ -1,12 +1,9 @@
package com.kri.kart.server.dto.upload; package com.kri.kart.server.dto.upload;
import lombok.Value;
@Value public record ImportQuestionDto(
public class ImportQuestionDto { String qid,
String qid; int qOrder,
int qOrder; String questionJson,
String questionJson; String qinfo,
String qinfo; String linfo) {}
String linfo;
}

View File

@@ -1,12 +1,9 @@
package com.kri.kart.server.dto.upload; package com.kri.kart.server.dto.upload;
import lombok.Value;
@Value public record ImportResponseDto(
public class ImportResponseDto { String idkey,
String idkey; String status,
String status; String pageName,
String pageName; String datjson,
String datjson; String surveyDate) {}
String surveyDate;
}

View File

@@ -1,11 +1,8 @@
package com.kri.kart.server.dto.upload; package com.kri.kart.server.dto.upload;
import lombok.Value;
@Value public record ImportResultDto(
public class ImportResultDto { int processedRows,
int processedRows; int affectedRows,
int affectedRows; int removedRows,
int removedRows; int archivedRows) {}
int archivedRows;
}

View File

@@ -1,10 +1,7 @@
package com.kri.kart.server.dto.upload; package com.kri.kart.server.dto.upload;
import java.util.List; import java.util.List;
import lombok.Value;
@Value public record UploadTableDto(
public class UploadTableDto { List<String> headers,
List<String> headers; List<List<String>> rows) {}
List<List<String>> rows;
}

View File

@@ -22,7 +22,7 @@ public class SurveySessionProvider {
} }
public <T> T mapper(ProjectRefDto project, Class<T> mapperType) { public <T> T mapper(ProjectRefDto project, Class<T> mapperType) {
return mapper(project.getProjectType(), mapperType); return mapper(project.projectType(), mapperType);
} }
public <T> T mapper(ProjectType type, Class<T> mapperType) { public <T> T mapper(ProjectType type, Class<T> mapperType) {

View File

@@ -22,12 +22,12 @@ public class BookmarkRepository {
public List<BookmarkDto> list(ProjectRefDto project, String page, String userId) { public List<BookmarkDto> list(ProjectRefDto project, String page, String userId) {
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class) return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
.list(project.getPkey(), page, userId); .list(project.pkey(), page, userId);
} }
public BookmarkDto find(ProjectRefDto project, String bookmarkId) { public BookmarkDto find(ProjectRefDto project, String bookmarkId) {
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class) return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
.find(project.getPkey(), bookmarkId); .find(project.pkey(), bookmarkId);
} }
public int create( public int create(
@@ -37,22 +37,22 @@ public class BookmarkRepository {
String userTeam, String userTeam,
String userId) { String userId) {
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class) return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
.create(project.getPkey(), bookmarkId, request, userTeam, userId); .create(project.pkey(), bookmarkId, request, userTeam, userId);
} }
public int update( public int update(
ProjectRefDto project, String bookmarkId, BookmarkSaveRequestDto request, String userId) { ProjectRefDto project, String bookmarkId, BookmarkSaveRequestDto request, String userId) {
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class) return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
.update(project.getPkey(), bookmarkId, request, userId); .update(project.pkey(), bookmarkId, request, userId);
} }
public int shiftOrderAfterDelete(ProjectRefDto project, String bookmarkId, String userId) { public int shiftOrderAfterDelete(ProjectRefDto project, String bookmarkId, String userId) {
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class) return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
.shiftOrderAfterDelete(project.getPkey(), bookmarkId, userId); .shiftOrderAfterDelete(project.pkey(), bookmarkId, userId);
} }
public int delete(ProjectRefDto project, String bookmarkId, String userId) { public int delete(ProjectRefDto project, String bookmarkId, String userId) {
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class) return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
.delete(project.getPkey(), bookmarkId, userId); .delete(project.pkey(), bookmarkId, userId);
} }
} }

View File

@@ -19,27 +19,27 @@ public class DerivedRepository {
public List<QuestionDto> list(ProjectRefDto project, Integer userRole, String userTeam) { public List<QuestionDto> list(ProjectRefDto project, Integer userRole, String userTeam) {
return surveySessionProvider.mapper(project, DerivedMapper.class) return surveySessionProvider.mapper(project, DerivedMapper.class)
.list(project.getPkey(), userRole, userTeam); .list(project.pkey(), userRole, userTeam);
} }
public String lockProject(ProjectRefDto project) { public String lockProject(ProjectRefDto project) {
return surveySessionProvider.mapper(project, DerivedMapper.class) return surveySessionProvider.mapper(project, DerivedMapper.class)
.lockProject(project.getPkey()); .lockProject(project.pkey());
} }
public List<DerivedDefinitionDto> definitions(ProjectRefDto project) { public List<DerivedDefinitionDto> definitions(ProjectRefDto project) {
return surveySessionProvider.mapper(project, DerivedMapper.class) return surveySessionProvider.mapper(project, DerivedMapper.class)
.definitions(project.getPkey()); .definitions(project.pkey());
} }
public DerivedDefinitionDto find(ProjectRefDto project, String qid) { public DerivedDefinitionDto find(ProjectRefDto project, String qid) {
return surveySessionProvider.mapper(project, DerivedMapper.class) return surveySessionProvider.mapper(project, DerivedMapper.class)
.find(project.getPkey(), qid); .find(project.pkey(), qid);
} }
public boolean duplicate(ProjectRefDto project, String qid, String originId) { public boolean duplicate(ProjectRefDto project, String qid, String originId) {
return surveySessionProvider.mapper(project, DerivedMapper.class) return surveySessionProvider.mapper(project, DerivedMapper.class)
.duplicate(project.getPkey(), qid, originId == null ? "" : originId) .duplicate(project.pkey(), qid, originId == null ? "" : originId)
> 0; > 0;
} }
@@ -52,14 +52,14 @@ public class DerivedRepository {
var derivedMapper = surveySessionProvider.mapper(project, DerivedMapper.class); var derivedMapper = surveySessionProvider.mapper(project, DerivedMapper.class);
return originId == null return originId == null
? derivedMapper.create( ? derivedMapper.create(
project.getPkey(), project.pkey(),
definition.getQid(), definition.getQid(),
definition.getQuestionJson(), definition.getQuestionJson(),
definition.getDerivedJson(), definition.getDerivedJson(),
userTeam, userTeam,
userId) userId)
: derivedMapper.update( : derivedMapper.update(
project.getPkey(), project.pkey(),
definition.getQid(), definition.getQid(),
definition.getQuestionJson(), definition.getQuestionJson(),
definition.getDerivedJson(), definition.getDerivedJson(),
@@ -70,41 +70,41 @@ public class DerivedRepository {
public void shiftOrder(ProjectRefDto project, String qid) { public void shiftOrder(ProjectRefDto project, String qid) {
surveySessionProvider.mapper(project, DerivedMapper.class) surveySessionProvider.mapper(project, DerivedMapper.class)
.shiftOrder(project.getPkey(), qid); .shiftOrder(project.pkey(), qid);
} }
public int delete(ProjectRefDto project, String qid) { public int delete(ProjectRefDto project, String qid) {
return surveySessionProvider.mapper(project, DerivedMapper.class) return surveySessionProvider.mapper(project, DerivedMapper.class)
.delete(project.getPkey(), qid); .delete(project.pkey(), qid);
} }
public void clearData(ProjectRefDto project, String qid) { public void clearData(ProjectRefDto project, String qid) {
surveySessionProvider.mapper(project, DerivedMapper.class) surveySessionProvider.mapper(project, DerivedMapper.class)
.clearData(project.getPkey(), "$.\"" + qid + "\""); .clearData(project.pkey(), "$.\"" + qid + "\"");
} }
public List<DerivedDataDto> responses(ProjectRefDto project) { public List<DerivedDataDto> responses(ProjectRefDto project) {
return surveySessionProvider.mapper(project, DerivedMapper.class) return surveySessionProvider.mapper(project, DerivedMapper.class)
.responses(project.getPkey()); .responses(project.pkey());
} }
public void ensureRespondent(ProjectRefDto project, String idkey) { public void ensureRespondent(ProjectRefDto project, String idkey) {
surveySessionProvider.mapper(project, DerivedMapper.class) surveySessionProvider.mapper(project, DerivedMapper.class)
.ensureRespondent(project.getPkey(), idkey); .ensureRespondent(project.pkey(), idkey);
} }
public void clearRespondentData(ProjectRefDto project, String qid, String idkey) { public void clearRespondentData(ProjectRefDto project, String qid, String idkey) {
surveySessionProvider.mapper(project, DerivedMapper.class) surveySessionProvider.mapper(project, DerivedMapper.class)
.clearRespondentData(project.getPkey(), "$.\"" + qid + "\"", idkey); .clearRespondentData(project.pkey(), "$.\"" + qid + "\"", idkey);
} }
public List<DerivedDataDto> respondentResponses(ProjectRefDto project, String idkey) { public List<DerivedDataDto> respondentResponses(ProjectRefDto project, String idkey) {
return surveySessionProvider.mapper(project, DerivedMapper.class) return surveySessionProvider.mapper(project, DerivedMapper.class)
.respondentResponses(project.getPkey(), idkey); .respondentResponses(project.pkey(), idkey);
} }
public void saveData(ProjectRefDto project, String qid, String idkey, String groupJson) { public void saveData(ProjectRefDto project, String qid, String idkey, String groupJson) {
surveySessionProvider.mapper(project, DerivedMapper.class) surveySessionProvider.mapper(project, DerivedMapper.class)
.saveData(project.getPkey(), "$.\"" + qid + "\"", idkey, groupJson); .saveData(project.pkey(), "$.\"" + qid + "\"", idkey, groupJson);
} }
} }

View File

@@ -21,32 +21,32 @@ public class ExportRepository {
public String additionalColumns(ProjectRefDto project) { public String additionalColumns(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ExportMapper.class) return surveySessionProvider.mapper(project, ExportMapper.class)
.additionalColumns(project.getPkey()); .additionalColumns(project.pkey());
} }
public List<ExportDerivedHeaderDto> derivedHeaders(ProjectRefDto project) { public List<ExportDerivedHeaderDto> derivedHeaders(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ExportMapper.class) return surveySessionProvider.mapper(project, ExportMapper.class)
.derivedHeaders(project.getPkey()); .derivedHeaders(project.pkey());
} }
public List<ExportHeaderDto> questionHeaders(ProjectRefDto project) { public List<ExportHeaderDto> questionHeaders(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ExportMapper.class) return surveySessionProvider.mapper(project, ExportMapper.class)
.questionHeaders(project.getPkey()); .questionHeaders(project.pkey());
} }
public List<ExportTitleDto> titles(ProjectRefDto project) { public List<ExportTitleDto> titles(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ExportMapper.class).titles(project.getPkey()); return surveySessionProvider.mapper(project, ExportMapper.class).titles(project.pkey());
} }
public String surveyType(ProjectRefDto project) { public String surveyType(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ExportMapper.class).surveyType(project.getPkey()); return surveySessionProvider.mapper(project, ExportMapper.class).surveyType(project.pkey());
} }
public List<ExportDataDto> data( public List<ExportDataDto> data(
ProjectRefDto project, RawDataExportRequestDto request, boolean includeInterviewer) { ProjectRefDto project, RawDataExportRequestDto request, boolean includeInterviewer) {
return surveySessionProvider.mapper(project, ExportMapper.class) return surveySessionProvider.mapper(project, ExportMapper.class)
.data( .data(
project.getPkey(), project.pkey(),
request.getType(), request.getType(),
request.getStartDate(), request.getStartDate(),
request.getEndDate() == null ? request.getStartDate() : request.getEndDate(), request.getEndDate() == null ? request.getStartDate() : request.getEndDate(),

View File

@@ -16,65 +16,65 @@ public class ImportRepository {
private final SurveySessionProvider surveySessionProvider; private final SurveySessionProvider surveySessionProvider;
public String lockProject(ProjectRefDto project) { public String lockProject(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class).lockProject(project.getPkey()); return surveySessionProvider.mapper(project, ImportMapper.class).lockProject(project.pkey());
} }
public int resetTitles(ProjectRefDto project) { public int resetTitles(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class).resetTitles(project.getPkey()); return surveySessionProvider.mapper(project, ImportMapper.class).resetTitles(project.pkey());
} }
public int deleteQuestions(ProjectRefDto project) { public int deleteQuestions(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.deleteQuestions(project.getPkey()); .deleteQuestions(project.pkey());
} }
public int deleteOptions(ProjectRefDto project) { public int deleteOptions(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.deleteOptions(project.getPkey()); .deleteOptions(project.pkey());
} }
public int deleteQuotaSets(ProjectRefDto project) { public int deleteQuotaSets(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.deleteQuotaSets(project.getPkey()); .deleteQuotaSets(project.pkey());
} }
public int deleteQuotas(ProjectRefDto project) { public int deleteQuotas(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.deleteQuotas(project.getPkey()); .deleteQuotas(project.pkey());
} }
public int resetStructure(ProjectRefDto project) { public int resetStructure(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.resetStructure(project.getPkey()); .resetStructure(project.pkey());
} }
public int deleteUploaded(ProjectRefDto project) { public int deleteUploaded(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.deleteUploaded(project.getPkey()); .deleteUploaded(project.pkey());
} }
public int archiveCompleted(ProjectRefDto project) { public int archiveCompleted(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.archiveCompleted(project.getPkey()); .archiveCompleted(project.pkey());
} }
public int title(ProjectRefDto project, String qid, String explain) { public int title(ProjectRefDto project, String qid, String explain) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.title(project.getPkey(), qid, explain); .title(project.pkey(), qid, explain);
} }
public int question(ProjectRefDto project, ImportQuestionDto question) { public int question(ProjectRefDto project, ImportQuestionDto question) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.question(project.getPkey(), question); .question(project.pkey(), question);
} }
public int structure(ProjectRefDto project, ImportQuestionDto question) { public int structure(ProjectRefDto project, ImportQuestionDto question) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.structure(project.getPkey(), question, "$." + question.getQid()); .structure(project.pkey(), question, "$." + question.qid());
} }
public int response(ProjectRefDto project, ImportResponseDto response) { public int response(ProjectRefDto project, ImportResponseDto response) {
return surveySessionProvider.mapper(project, ImportMapper.class) return surveySessionProvider.mapper(project, ImportMapper.class)
.response(project.getPkey(), response); .response(project.pkey(), response);
} }
} }

View File

@@ -22,31 +22,31 @@ public class ProgressRepository {
public List<ProgressDayDto> daily(ProjectRefDto project) { public List<ProgressDayDto> daily(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ProgressMapper.class) return surveySessionProvider.mapper(project, ProgressMapper.class)
.daily(project.getPkey()); .daily(project.pkey());
} }
public List<ProgressTypeDto> type(ProjectRefDto project, ProgressSearchDto search) { public List<ProgressTypeDto> type(ProjectRefDto project, ProgressSearchDto search) {
return surveySessionProvider.mapper(project, ProgressMapper.class) return surveySessionProvider.mapper(project, ProgressMapper.class)
.type(project.getPkey(), search.getStartDate(), search.getEndDate()); .type(project.pkey(), search.startDate(), search.endDate());
} }
public List<LoiDto> loi(ProjectRefDto project, ProgressSearchDto search) { public List<LoiDto> loi(ProjectRefDto project, ProgressSearchDto search) {
return surveySessionProvider.mapper(project, ProgressMapper.class) return surveySessionProvider.mapper(project, ProgressMapper.class)
.loi(project.getPkey(), search.getStartDate(), search.getEndDate()); .loi(project.pkey(), search.startDate(), search.endDate());
} }
public List<ProgressScreenDto> screen(ProjectRefDto project, ProgressSearchDto search) { public List<ProgressScreenDto> screen(ProjectRefDto project, ProgressSearchDto search) {
return surveySessionProvider.mapper(project, ProgressMapper.class) return surveySessionProvider.mapper(project, ProgressMapper.class)
.screen(project.getPkey(), search.getStartDate(), search.getEndDate()); .screen(project.pkey(), search.startDate(), search.endDate());
} }
public List<CustomProgressDto> reportUrls(ProjectRefDto project) { public List<CustomProgressDto> reportUrls(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ProgressMapper.class) return surveySessionProvider.mapper(project, ProgressMapper.class)
.reportUrls(project.getPkey()); .reportUrls(project.pkey());
} }
public List<CustomProgressDto> appendFiles(ProjectRefDto project) { public List<CustomProgressDto> appendFiles(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ProgressMapper.class) return surveySessionProvider.mapper(project, ProgressMapper.class)
.appendFiles(project.getPkey()); .appendFiles(project.pkey());
} }
} }

View File

@@ -17,6 +17,6 @@ public class QuestionRepository {
public List<QuestionDto> list(ProjectRefDto project, boolean includeProfiles) { public List<QuestionDto> list(ProjectRefDto project, boolean includeProfiles) {
return surveySessionProvider.mapper(project, QuestionMapper.class) return surveySessionProvider.mapper(project, QuestionMapper.class)
.list(project.getPkey(), includeProfiles); .list(project.pkey(), includeProfiles);
} }
} }

View File

@@ -18,16 +18,16 @@ public class QuotaRepository {
public List<QuotaSetDto> quotaSets(ProjectRefDto project) { public List<QuotaSetDto> quotaSets(ProjectRefDto project) {
return surveySessionProvider.mapper(project, QuotaMapper.class) return surveySessionProvider.mapper(project, QuotaMapper.class)
.quotaSets(project.getPkey()); .quotaSets(project.pkey());
} }
public QuotaSetDto quotaSet(ProjectRefDto project, int quotaOrder) { public QuotaSetDto quotaSet(ProjectRefDto project, int quotaOrder) {
return surveySessionProvider.mapper(project, QuotaMapper.class) return surveySessionProvider.mapper(project, QuotaMapper.class)
.quotaSet(project.getPkey(), quotaOrder); .quotaSet(project.pkey(), quotaOrder);
} }
public List<QuotaEntryDto> quotaEntries(ProjectRefDto project, int quotaOrder) { public List<QuotaEntryDto> quotaEntries(ProjectRefDto project, int quotaOrder) {
return surveySessionProvider.mapper(project, QuotaMapper.class) return surveySessionProvider.mapper(project, QuotaMapper.class)
.quotaEntries(project.getPkey(), quotaOrder); .quotaEntries(project.pkey(), quotaOrder);
} }
} }

View File

@@ -28,7 +28,7 @@ public class ShareLinkRepository {
public String projectTitle(ProjectRefDto project) { public String projectTitle(ProjectRefDto project) {
return surveySessionProvider.mapper(project, ShareLinkMapper.class) return surveySessionProvider.mapper(project, ShareLinkMapper.class)
.projectTitle(project.getPkey()); .projectTitle(project.pkey());
} }
public ShareLinkRecordDto reusable(ShareLinkRecordDto link) { public ShareLinkRecordDto reusable(ShareLinkRecordDto link) {

View File

@@ -23,7 +23,7 @@ public class StatisticsRepository {
List<String> selectedRoots) { List<String> selectedRoots) {
return surveySessionProvider.mapper(project, StatisticsMapper.class) return surveySessionProvider.mapper(project, StatisticsMapper.class)
.data( .data(
project.getPkey(), project.pkey(),
request.getDataScope(), request.getDataScope(),
request.getStartDate(), request.getStartDate(),
request.getEndDate() == null ? request.getStartDate() : request.getEndDate(), request.getEndDate() == null ? request.getStartDate() : request.getEndDate(),

View File

@@ -58,12 +58,12 @@ public class AggregateExcelService {
private ExportFileDto export( private ExportFileDto export(
ProjectRefDto project, AggregateExcelRequestDto request, boolean quota) { ProjectRefDto project, AggregateExcelRequestDto request, boolean quota) {
validate(request); validate(request);
String firstSheet = quota ? clean(request.getTables().get(0).getHead()) : "목차"; String firstSheet = quota ? clean(request.tables().get(0).getHead()) : "목차";
try (Workbook workbook = ExcelMapper.writeFromMapList(List.of(), firstSheet); try (Workbook workbook = ExcelMapper.writeFromMapList(List.of(), firstSheet);
var output = new ByteArrayOutputStream()) { var output = new ByteArrayOutputStream()) {
if (quota) { if (quota) {
for (int i = 0; i < request.getTables().size(); i++) { for (int i = 0; i < request.tables().size(); i++) {
var table = request.getTables().get(i); var table = request.tables().get(i);
Sheet sheet = Sheet sheet =
i == 0 ? workbook.getSheetAt(0) : workbook.createSheet(clean(table.getHead())); i == 0 ? workbook.getSheetAt(0) : workbook.createSheet(clean(table.getHead()));
CellStyle base = baseStyle(workbook, 9, false); CellStyle base = baseStyle(workbook, 9, false);
@@ -82,7 +82,7 @@ public class AggregateExcelService {
initializeSheet(contents, contentsStyle); initializeSheet(contents, contentsStyle);
initializeSheet(tables, bodyStyle); initializeSheet(tables, bodyStyle);
var heading = titleStyle(workbook, contentsStyle, 25, true); var heading = titleStyle(workbook, contentsStyle, 25, true);
for (int row = 0; row < request.getTables().size() + 4; row++) { for (int row = 0; row < request.tables().size() + 4; row++) {
contents.createRow(row).setHeightInPoints(20); contents.createRow(row).setHeightInPoints(20);
} }
rectangle( rectangle(
@@ -93,7 +93,7 @@ public class AggregateExcelService {
cell.setCellValue("목차"); cell.setCellValue("목차");
}); });
contents.addMergedRegion(new CellRangeAddress(0, 3, 0, 1)); contents.addMergedRegion(new CellRangeAddress(0, 3, 0, 1));
var area = new CellRangeAddress(4, request.getTables().size() + 3, 0, 1); var area = new CellRangeAddress(4, request.tables().size() + 3, 0, 1);
rectangle( rectangle(
contents, contents,
area, area,
@@ -113,8 +113,8 @@ public class AggregateExcelService {
}); });
border(contents, area, BorderStyle.THIN); border(contents, area, BorderStyle.THIN);
int nextRow = 1; int nextRow = 1;
for (int i = 0; i < request.getTables().size(); i++) { for (int i = 0; i < request.tables().size(); i++) {
var item = request.getTables().get(i); var item = request.tables().get(i);
cell(contents, i + 5, 1).setCellValue(title(item)); cell(contents, i + 5, 1).setCellValue(title(item));
var link = cell(contents, i + 5, 2); var link = cell(contents, i + 5, 2);
link.setCellValue("Go"); link.setCellValue("Go");
@@ -127,7 +127,7 @@ public class AggregateExcelService {
font.setUnderline(org.apache.poi.ss.usermodel.Font.U_SINGLE); font.setUnderline(org.apache.poi.ss.usermodel.Font.U_SINGLE);
font.setColor(org.apache.poi.ss.usermodel.IndexedColors.BLUE.getIndex()); font.setColor(org.apache.poi.ss.usermodel.IndexedColors.BLUE.getIndex());
CellUtil.setCellStyleProperty(link, CellUtil.FONT, font.getIndex()); CellUtil.setCellStyleProperty(link, CellUtil.FONT, font.getIndex());
nextRow = table(tables, item, nextRow, request.isTurn(), false, bodyStyle) + 1; nextRow = table(tables, item, nextRow, request.turn(), false, bodyStyle) + 1;
} }
legacyExcelWidthService.autoFit(contents, 0, 10); legacyExcelWidthService.autoFit(contents, 0, 10);
contents.createFreezePane(0, 4); contents.createFreezePane(0, 4);
@@ -137,7 +137,7 @@ public class AggregateExcelService {
"[" "["
+ (quota ? "QUOTA" : "REPORT") + (quota ? "QUOTA" : "REPORT")
+ "]" + "]"
+ project.getPkey() + project.pkey()
+ "_" + "_"
+ DateTimeUtil.nowKstLocalDateTime().format(TIMESTAMP) + DateTimeUtil.nowKstLocalDateTime().format(TIMESTAMP)
+ ".xlsx", + ".xlsx",
@@ -445,7 +445,7 @@ public class AggregateExcelService {
private void validate(AggregateExcelRequestDto request) { private void validate(AggregateExcelRequestDto request) {
long total = 0; long total = 0;
for (var table : request.getTables()) { for (var table : request.tables()) {
var keys = new ArrayList<>(table.getBody().get(0).keySet()); var keys = new ArrayList<>(table.getBody().get(0).keySet());
if (keys.size() < 2 || keys.size() > 1024) { if (keys.size() < 2 || keys.size() > 1024) {
throw invalid(); throw invalid();

View File

@@ -37,13 +37,13 @@ public class BookmarkService {
@Transactional(transactionManager = "kartTransactionManager") @Transactional(transactionManager = "kartTransactionManager")
public String create( public String create(
ProjectRefDto project, BookmarkSaveRequestDto request, RequestUserContext ctx) { ProjectRefDto project, BookmarkSaveRequestDto request, RequestUserContext ctx) {
if (!StringUtil.hasText(request.getBookmarkPage())) { if (!StringUtil.hasText(request.bookmarkPage())) {
throw BusinessException.badRequest("생성할 북마크 페이지를 입력해 주세요."); throw BusinessException.badRequest("생성할 북마크 페이지를 입력해 주세요.");
} }
String bookmarkId = String bookmarkId =
project.getPkey() project.pkey()
+ "_" + "_"
+ request.getBookmarkPage().charAt(0) + request.bookmarkPage().charAt(0)
+ "_" + "_"
+ DateTimeUtil.nowKstLocalDateTime().format(ID_TIMESTAMP); + DateTimeUtil.nowKstLocalDateTime().format(ID_TIMESTAMP);
bookmarkRepository.create(project, bookmarkId, request, ctx.getUserTeam(), ctx.getUserId()); bookmarkRepository.create(project, bookmarkId, request, ctx.getUserTeam(), ctx.getUserId());
@@ -100,10 +100,10 @@ public class BookmarkService {
private ObjectNode snapshot(String bookmarkId, BookmarkSaveRequestDto request) { private ObjectNode snapshot(String bookmarkId, BookmarkSaveRequestDto request) {
return snapshot( return snapshot(
bookmarkId, bookmarkId,
request.getBookmarkTitle(), request.bookmarkTitle(),
request.getBookmarkInfo(), request.bookmarkInfo(),
request.getBookmarkJson(), request.bookmarkJson(),
request.getIsOpen()); request.isOpen());
} }
private ObjectNode snapshot(BookmarkDto bookmark) { private ObjectNode snapshot(BookmarkDto bookmark) {

View File

@@ -55,7 +55,7 @@ public class DerivedManagementService {
DerivedSaveRequestDto request, DerivedSaveRequestDto request,
RequestUserContext ctx) { RequestUserContext ctx) {
requireRole(ctx); requireRole(ctx);
validateId(request.getVariableId()); validateId(request.variableId());
if (originId != null) { if (originId != null) {
validateId(originId); validateId(originId);
} }
@@ -68,7 +68,9 @@ public class DerivedManagementService {
if (original != null) { if (original != null) {
requireTeam(original, ctx); requireTeam(original, ctx);
} }
if (derivedRepository.duplicate(project, definition.getQid(), originId)) { // An update that keeps its ID cannot collide; raw DATA keys with that ID are ignored.
boolean sameId = originId != null && originId.equalsIgnoreCase(definition.getQid());
if (!sameId && derivedRepository.duplicate(project, definition.getQid(), originId)) {
throw BusinessException.conflict("DERIVED_ID_DUPLICATE", "이미 사용 중인 변수 ID입니다."); throw BusinessException.conflict("DERIVED_ID_DUPLICATE", "이미 사용 중인 변수 ID입니다.");
} }
if (derivedRepository.save( if (derivedRepository.save(
@@ -79,7 +81,7 @@ public class DerivedManagementService {
if (original != null && !original.getQid().equals(definition.getQid())) { if (original != null && !original.getQid().equals(definition.getQid())) {
derivedRepository.clearData(project, original.getQid()); derivedRepository.clearData(project, original.getQid());
} }
calculate(project, definition); calculate(project, definition, null, derivedIds(derivedRepository.definitions(project)));
var content = objectMapper.createObjectNode(); var content = objectMapper.createObjectNode();
content.set("NEW", objectMapper.valueToTree(definition)); content.set("NEW", objectMapper.valueToTree(definition));
if (original != null) { if (original != null) {
@@ -129,9 +131,11 @@ public class DerivedManagementService {
qid == null qid == null
? derivedRepository.definitions(project) ? derivedRepository.definitions(project)
: List.of(requireDefinition(project, qid)); : List.of(requireDefinition(project, qid));
var derivedIds =
derivedIds(qid == null ? definitions : derivedRepository.definitions(project));
int matched = 0; int matched = 0;
for (var definition : definitions) { for (var definition : definitions) {
matched += calculate(project, definition); matched += calculate(project, definition, null, derivedIds);
} }
if (qid == null) { if (qid == null) {
logService.writeSiteLog( logService.writeSiteLog(
@@ -156,19 +160,47 @@ public class DerivedManagementService {
// response. // response.
derivedRepository.ensureRespondent(project, idkey); derivedRepository.ensureRespondent(project, idkey);
var definitions = derivedRepository.definitions(project); var definitions = derivedRepository.definitions(project);
var derivedIds = derivedIds(definitions);
int matched = 0; int matched = 0;
for (var definition : definitions) { for (var definition : definitions) {
matched += calculate(project, definition, idkey); matched += calculate(project, definition, idkey, derivedIds);
} }
return new DerivedCalculationDto(definitions.size(), matched); return new DerivedCalculationDto(definitions.size(), matched);
}); });
} }
private int calculate(ProjectRefDto project, DerivedDefinitionDto definition) { /** Stored derived variable IDs; uploaded response columns with these IDs are not imported. */
return calculate(project, definition, null); public List<String> derivedIds(ProjectRefDto project) {
return derivedIds(derivedRepository.definitions(project));
} }
private int calculate(ProjectRefDto project, DerivedDefinitionDto definition, String idkey) { /**
* Recalculates every definition after a data upload. It joins the caller's KON/KONKIWI
* transaction, so a failure rolls back the upload; no role check or extra audit log applies.
*/
public DerivedCalculationDto recalculateAfterImport(ProjectRefDto project) {
return transaction(
project,
() -> {
var definitions = derivedRepository.definitions(project);
var derivedIds = derivedIds(definitions);
int matched = 0;
for (var definition : definitions) {
matched += calculate(project, definition, null, derivedIds);
}
return new DerivedCalculationDto(definitions.size(), matched);
});
}
private List<String> derivedIds(List<DerivedDefinitionDto> definitions) {
return definitions.stream().map(DerivedDefinitionDto::getQid).toList();
}
private int calculate(
ProjectRefDto project,
DerivedDefinitionDto definition,
String idkey,
List<String> derivedIds) {
validateId(definition.getQid()); validateId(definition.getQid());
if (idkey == null) { if (idkey == null) {
derivedRepository.clearData(project, definition.getQid()); derivedRepository.clearData(project, definition.getQid());
@@ -181,7 +213,7 @@ public class DerivedManagementService {
: derivedRepository.respondentResponses(project, idkey); : derivedRepository.respondentResponses(project, idkey);
var results = var results =
derivedComputationService.calculate( derivedComputationService.calculate(
definition, questionService.list(project, idkey == null ? 0 : 1001), data); definition, questionService.list(project, idkey == null ? 0 : 1001), data, derivedIds);
int matched = 0; int matched = 0;
for (int i = 0; i < data.size(); i++) { for (int i = 0; i < data.size(); i++) {
var group = results.get(i); var group = results.get(i);
@@ -235,7 +267,7 @@ public class DerivedManagementService {
private <T> T transaction(ProjectRefDto project, Supplier<T> action) { private <T> T transaction(ProjectRefDto project, Supplier<T> action) {
var transactionTemplate = var transactionTemplate =
new TransactionTemplate( new TransactionTemplate(
project.getProjectType() == ProjectType.KON project.projectType() == ProjectType.KON
? konTransactionManager ? konTransactionManager
: konkiwiTransactionManager); : konkiwiTransactionManager);
return Objects.requireNonNull(transactionTemplate.execute(status -> action.get())); return Objects.requireNonNull(transactionTemplate.execute(status -> action.get()));

View File

@@ -326,7 +326,7 @@ public class ExportService {
"[" "["
+ prefix + prefix
+ "]" + "]"
+ project.getPkey() + project.pkey()
+ "_" + "_"
+ DateTimeUtil.nowKstLocalDateTime().format(FILE_TIMESTAMP) + DateTimeUtil.nowKstLocalDateTime().format(FILE_TIMESTAMP)
+ ".xlsx"; + ".xlsx";

View File

@@ -33,6 +33,7 @@ public class ImportService {
private final QuestionImportService questionImportService; private final QuestionImportService questionImportService;
private final ResponseImportService responseImportService; private final ResponseImportService responseImportService;
private final UploadArchiveService uploadArchiveService; private final UploadArchiveService uploadArchiveService;
private final DerivedManagementService derivedManagementService;
private final LogService logService; private final LogService logService;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final PlatformTransactionManager konTransactionManager; private final PlatformTransactionManager konTransactionManager;
@@ -45,6 +46,7 @@ public class ImportService {
QuestionImportService questionImportService, QuestionImportService questionImportService,
ResponseImportService responseImportService, ResponseImportService responseImportService,
UploadArchiveService uploadArchiveService, UploadArchiveService uploadArchiveService,
DerivedManagementService derivedManagementService,
LogService logService, LogService logService,
ObjectMapper objectMapper, ObjectMapper objectMapper,
@Qualifier("konTransactionManager") PlatformTransactionManager konTransactionManager, @Qualifier("konTransactionManager") PlatformTransactionManager konTransactionManager,
@@ -56,6 +58,7 @@ public class ImportService {
this.questionImportService = questionImportService; this.questionImportService = questionImportService;
this.responseImportService = responseImportService; this.responseImportService = responseImportService;
this.uploadArchiveService = uploadArchiveService; this.uploadArchiveService = uploadArchiveService;
this.derivedManagementService = derivedManagementService;
this.logService = logService; this.logService = logService;
this.objectMapper = objectMapper; this.objectMapper = objectMapper;
this.konTransactionManager = konTransactionManager; this.konTransactionManager = konTransactionManager;
@@ -72,10 +75,10 @@ public class ImportService {
requireProject(project); requireProject(project);
importRepository.resetTitles(project); importRepository.resetTitles(project);
int affected = 0; int affected = 0;
for (var row : table.getRows()) { for (var row : table.rows()) {
affected += importRepository.title(project, row.get(0), row.get(3)); affected += importRepository.title(project, row.get(0), row.get(3));
} }
return new ImportResultDto(table.getRows().size(), affected, 0, 0); return new ImportResultDto(table.rows().size(), affected, 0, 0);
}); });
} }
@@ -118,12 +121,16 @@ public class ImportService {
.filter(question -> "multi".equalsIgnoreCase(question.getQtype())) .filter(question -> "multi".equalsIgnoreCase(question.getQtype()))
.map(question -> question.getQid().split("_", -1)[0]) .map(question -> question.getQid().split("_", -1)[0])
.collect(Collectors.toSet()); .collect(Collectors.toSet());
var responses = responseImportService.prepare(table, multi); // Derived columns are not uploaded; derived values are regenerated from the new data.
var responses =
responseImportService.prepare(
table, multi, derivedManagementService.derivedIds(project));
int removed = importRepository.deleteUploaded(project); int removed = importRepository.deleteUploaded(project);
int archived = importRepository.archiveCompleted(project); int archived = importRepository.archiveCompleted(project);
for (var response : responses) { for (var response : responses) {
requireOne(importRepository.response(project, response)); requireOne(importRepository.response(project, response));
} }
derivedManagementService.recalculateAfterImport(project);
return new ImportResultDto(responses.size(), responses.size(), removed, archived); return new ImportResultDto(responses.size(), responses.size(), removed, archived);
}); });
} }
@@ -155,7 +162,7 @@ public class ImportService {
private <T> T transaction(ProjectRefDto project, Supplier<T> action) { private <T> T transaction(ProjectRefDto project, Supplier<T> action) {
var manager = var manager =
project.getProjectType() == ProjectType.KON project.projectType() == ProjectType.KON
? konTransactionManager ? konTransactionManager
: konkiwiTransactionManager; : konkiwiTransactionManager;
return Objects.requireNonNull(new TransactionTemplate(manager).execute(status -> action.get())); return Objects.requireNonNull(new TransactionTemplate(manager).execute(status -> action.get()));

View File

@@ -44,8 +44,8 @@ public class LogService {
ProjectRefDto project, String title, JsonNode content, RequestUserContext ctx) { ProjectRefDto project, String title, JsonNode content, RequestUserContext ctx) {
var pageInfo = objectMapper.createObjectNode(); var pageInfo = objectMapper.createObjectNode();
// The existing frontend calls the v2 endpoint, which stores projectCode rather than PKEY. // The existing frontend calls the v2 endpoint, which stores projectCode rather than PKEY.
pageInfo.put("projectCode", project.getPkey()); pageInfo.put("projectCode", project.pkey());
pageInfo.put("projectType", project.getProjectType().getCode()); pageInfo.put("projectType", project.projectType().getCode());
pageInfo.put("LOGTITLE", title); pageInfo.put("LOGTITLE", title);
pageInfo.set("LOGCONTENT", normalizeContent(content)); pageInfo.set("LOGCONTENT", normalizeContent(content));
try { try {
@@ -64,7 +64,7 @@ public class LogService {
if (projectType == null || !hasKey) { if (projectType == null || !hasKey) {
throw BusinessException.badRequest("프로젝트 유형과 키는 함께 입력하거나 모두 생략해 주세요."); throw BusinessException.badRequest("프로젝트 유형과 키는 함께 입력하거나 모두 생략해 주세요.");
} }
return new ProjectRefDto(projectType, pkey).getPkey(); return new ProjectRefDto(projectType, pkey).pkey();
} }
private JsonNode normalizeContent(JsonNode content) { private JsonNode normalizeContent(JsonNode content) {

View File

@@ -26,31 +26,31 @@ public class ProjectService {
public List<ProjectListDto> list(ProjectLinkSearchDto search, RequestUserContext ctx) { public List<ProjectListDto> list(ProjectLinkSearchDto search, RequestUserContext ctx) {
requireIdentity(ctx); requireIdentity(ctx);
boolean hasKeyword = search.getKeyword() != null && !search.getKeyword().isEmpty(); boolean hasKeyword = search.keyword() != null && !search.keyword().isEmpty();
if (search.getProjectType() == null if (search.projectType() == null
&& search.getIntranetCode() == null && search.intranetCode() == null
&& search.getUserTeam() == null && search.userTeam() == null
&& !hasKeyword) { && !hasKeyword) {
return list(ctx); return list(ctx);
} }
if (search.getProjectType() == null if (search.projectType() == null
|| search.getIntranetCode() == null || search.intranetCode() == null
|| search.getUserTeam() == null) { || search.userTeam() == null) {
throw BusinessException.badRequest("연동 조회에는 projectType/intranetCode/userTeam을 함께 입력해 주세요."); throw BusinessException.badRequest("연동 조회에는 projectType/intranetCode/userTeam을 함께 입력해 주세요.");
} }
String intranetCode = search.getIntranetCode().split("_", -1)[0]; String intranetCode = search.intranetCode().split("_", -1)[0];
String keyword = search.getKeyword() == null ? "" : search.getKeyword(); String keyword = search.keyword() == null ? "" : search.keyword();
var rows = var rows =
projectRepository.linkedList( projectRepository.linkedList(
search.getProjectType(), search.projectType(),
intranetCode, intranetCode,
search.getUserTeam(), search.userTeam(),
keyword, keyword,
ctx.getUserRole(), ctx.getUserRole(),
ctx.getUserTeam(), ctx.getUserTeam(),
assignedPkeys(ctx)); assignedPkeys(ctx));
for (int index = 0; index < rows.size(); index++) { for (int index = 0; index < rows.size(); index++) {
rows.get(index).setProjectType(search.getProjectType()); rows.get(index).setProjectType(search.projectType());
rows.get(index).setRowNumber(Integer.toString(index + 1)); rows.get(index).setRowNumber(Integer.toString(index + 1));
} }
return rows; return rows;

View File

@@ -24,7 +24,7 @@ public class QuestionService {
public List<QuestionDto> list(ProjectRefDto project, Integer userRole) { public List<QuestionDto> list(ProjectRefDto project, Integer userRole) {
boolean profiles = boolean profiles =
project.getProjectType() == ProjectType.KIWI && Integer.valueOf(1001).equals(userRole); project.projectType() == ProjectType.KIWI && Integer.valueOf(1001).equals(userRole);
return organize(questionRepository.list(project, profiles)); return organize(questionRepository.list(project, profiles));
} }

View File

@@ -40,13 +40,13 @@ public class ShareLinkService {
@Transactional(transactionManager = "kartTransactionManager") @Transactional(transactionManager = "kartTransactionManager")
public ShareLinkDto create( public ShareLinkDto create(
ProjectRefDto project, ShareLinkRequestDto request, RequestUserContext ctx) { ProjectRefDto project, ShareLinkRequestDto request, RequestUserContext ctx) {
String path = allowedUrl(request.getRealUrl()); String path = allowedUrl(request.realUrl());
String title = requireProject(project); String title = requireProject(project);
ShareLinkRecordDto candidate = new ShareLinkRecordDto(); ShareLinkRecordDto candidate = new ShareLinkRecordDto();
candidate.setPkey(project.getPkey()); candidate.setPkey(project.pkey());
candidate.setProjectType(project.getProjectType().getCode()); candidate.setProjectType(project.projectType().getCode());
candidate.setRealUrl(path); candidate.setRealUrl(path);
candidate.setIsPageOnly("P".equals(request.getMode()) ? 1 : 0); candidate.setIsPageOnly("P".equals(request.mode()) ? 1 : 0);
candidate.setSkey(legacyProjectKeyService.encode(project)); candidate.setSkey(legacyProjectKeyService.encode(project));
candidate.setProjectTitle(title); candidate.setProjectTitle(title);
// Ordinary legacy users share REPORT ownership, preserving existing URL reuse. // Ordinary legacy users share REPORT ownership, preserving existing URL reuse.
@@ -76,8 +76,8 @@ public class ShareLinkService {
} }
var content = objectMapper.createObjectNode(); var content = objectMapper.createObjectNode();
content.put("REAL_URI", path); content.put("REAL_URI", path);
content.put("MODE", request.getMode()); content.put("MODE", request.mode());
content.put("COPY_URI", link.getUrl()); content.put("COPY_URI", link.url());
logService.writeSiteLog(project, "URL Copy", content, ctx); logService.writeSiteLog(project, "URL Copy", content, ctx);
return link; return link;
} }
@@ -90,7 +90,7 @@ public class ShareLinkService {
public ExternalLoginResponseDto login(String urlKey, String clientIp) { public ExternalLoginResponseDto login(String urlKey, String clientIp) {
ShareLinkRecordDto stored = record(urlKey); ShareLinkRecordDto stored = record(urlKey);
ShareLinkDto link = resolve(stored); ShareLinkDto link = resolve(stored);
String userId = KartConstant.EXTERNAL_USER_PREFIX + link.getUrlKey(); String userId = KartConstant.EXTERNAL_USER_PREFIX + link.urlKey();
JwtUserClaimsDto user = JwtUserClaimsDto user =
JwtUserClaimsDto.builder() JwtUserClaimsDto.builder()
.userId(userId) .userId(userId)
@@ -98,7 +98,7 @@ public class ShareLinkService {
.userTeam(KartConstant.EXTERNAL_TEAM) .userTeam(KartConstant.EXTERNAL_TEAM)
.userCmpn("") .userCmpn("")
.userRole( .userRole(
link.isPageOnly() link.pageOnly()
? KartConstant.EXTERNAL_PAGE_COPY_ROLE ? KartConstant.EXTERNAL_PAGE_COPY_ROLE
: KartConstant.EXTERNAL_URL_COPY_ROLE) : KartConstant.EXTERNAL_URL_COPY_ROLE)
.build(); .build();
@@ -177,8 +177,8 @@ public class ShareLinkService {
stored.getUrlKey(), stored.getUrlKey(),
absolute, absolute,
allowedUrl(stored.getRealUrl()), allowedUrl(stored.getRealUrl()),
project.getProjectType(), project.projectType(),
project.getPkey(), project.pkey(),
stored.getProjectTitle(), stored.getProjectTitle(),
stored.getIsPageOnly() == 1); stored.getIsPageOnly() == 1);
} }

View File

@@ -158,7 +158,7 @@ public class StatisticsService {
private List<QuestionDto> loadQuestions(ProjectRefDto project, RequestUserContext ctx) { private List<QuestionDto> loadQuestions(ProjectRefDto project, RequestUserContext ctx) {
boolean includeProfileQuestions = boolean includeProfileQuestions =
project.getProjectType() == ProjectType.KIWI project.projectType() == ProjectType.KIWI
&& Integer.valueOf(KartConstant.PROFILE_QUESTION_ROLE).equals(ctx.getUserRole()); && Integer.valueOf(KartConstant.PROFILE_QUESTION_ROLE).equals(ctx.getUserRole());
return questionService.organize(questionRepository.list(project, includeProfileQuestions)); return questionService.organize(questionRepository.list(project, includeProfileQuestions));
} }
@@ -200,7 +200,7 @@ public class StatisticsService {
List<StatisticsRequestDto> requests, List<StatisticsRequestDto> requests,
StatisticsRequestDto sharedRequest, StatisticsRequestDto sharedRequest,
List<QuestionDto> questions) { List<QuestionDto> questions) {
if (project.getProjectType() != ProjectType.KIWI) { if (project.projectType() != ProjectType.KIWI) {
return false; return false;
} }
return requests.stream().anyMatch(request -> isProfileId(request.getIndex())) return requests.stream().anyMatch(request -> isProfileId(request.getIndex()))

View File

@@ -13,6 +13,7 @@ import com.kri.kart.server.dto.statistics.SurveyResponseDto;
import com.kri.kart.server.service.statistics.LegacyFilterService; import com.kri.kart.server.service.statistics.LegacyFilterService;
import com.kri.kart.server.service.statistics.StatisticsFilterService; import com.kri.kart.server.service.statistics.StatisticsFilterService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@@ -29,17 +30,17 @@ public class DerivedComputationService {
private final StatisticsFilterService statisticsFilterService; private final StatisticsFilterService statisticsFilterService;
public DerivedDefinitionDto definition(DerivedSaveRequestDto request) { public DerivedDefinitionDto definition(DerivedSaveRequestDto request) {
JsonNode info = request.getVariableInfo(); JsonNode info = request.variableInfo();
if (!info.isObject() || info.isEmpty() || info.size() > 1000) { if (!info.isObject() || info.isEmpty() || info.size() > 1000) {
throw invalid(); throw invalid();
} }
info.fields().forEachRemaining(entry -> validateRule(entry.getKey(), entry.getValue())); info.fields().forEachRemaining(entry -> validateRule(entry.getKey(), entry.getValue()));
var question = objectMapper.createObjectNode(); var question = objectMapper.createObjectNode();
question.put("variable", request.getVariableId()); question.put("variable", request.variableId());
question.put("explain", ""); question.put("explain", "");
question.put("title", request.getVariableTitle()); question.put("title", request.variableTitle());
var dataset = question.putObject("dataset"); var dataset = question.putObject("dataset");
if (request.getVariableType().equals("num")) { if (request.variableType().equals("num")) {
dataset.putObject("open").putObject("1").put("label", "").put("option", "num"); dataset.putObject("open").putObject("1").put("label", "").put("option", "num");
question.put("qtype", "open"); question.put("qtype", "open");
} else { } else {
@@ -52,18 +53,42 @@ public class DerivedComputationService {
? Integer.toString(info.size()) ? Integer.toString(info.size())
: entry.getKey(), : entry.getKey(),
entry.getValue().deepCopy())); entry.getValue().deepCopy()));
dataset.set(request.getVariableType(), labels); dataset.set(request.variableType(), labels);
question.put("qtype", request.getVariableType()); question.put("qtype", request.variableType());
} }
var definition = new DerivedDefinitionDto(); var definition = new DerivedDefinitionDto();
definition.setQid(request.getVariableId()); definition.setQid(request.variableId());
definition.setDerivedJson(JsonUtil.toJson(objectMapper, info)); definition.setDerivedJson(JsonUtil.toJson(objectMapper, info));
definition.setQuestionJson(JsonUtil.toJson(objectMapper, question)); definition.setQuestionJson(JsonUtil.toJson(objectMapper, question));
return definition; return definition;
} }
/**
* A response key belongs to a derived variable when it equals the variable ID or starts with
* "{ID}_" (case-insensitive), matching the exported single/num/multi column names.
*/
public static boolean isDerivedKey(String key, Collection<String> derivedIds) {
String upperKey = key.toUpperCase(Locale.ROOT);
for (String derivedId : derivedIds) {
String upperId = derivedId.toUpperCase(Locale.ROOT);
if (upperKey.equals(upperId) || upperKey.startsWith(upperId + "_")) {
return true;
}
}
return false;
}
public List<ObjectNode> calculate( public List<ObjectNode> calculate(
DerivedDefinitionDto definition, List<QuestionDto> questions, List<DerivedDataDto> data) { DerivedDefinitionDto definition, List<QuestionDto> questions, List<DerivedDataDto> data) {
return calculate(definition, questions, data, List.of(definition.getQid()));
}
/** Raw DATA keys of any derived variable are ignored so derived values take precedence. */
public List<ObjectNode> calculate(
DerivedDefinitionDto definition,
List<QuestionDto> questions,
List<DerivedDataDto> data,
Collection<String> derivedIds) {
ObjectNode info = object(definition.getDerivedJson()); ObjectNode info = object(definition.getDerivedJson());
String type = object(definition.getQuestionJson()).path("qtype").asText(); String type = object(definition.getQuestionJson()).path("qtype").asText();
String qid = definition.getQid(); String qid = definition.getQid();
@@ -84,6 +109,7 @@ public class DerivedComputationService {
for (DerivedDataDto row : data) { for (DerivedDataDto row : data) {
Map<String, String> flat = new LinkedHashMap<>(); Map<String, String> flat = new LinkedHashMap<>();
flatten(object(row.getDatjson()), flat); flatten(object(row.getDatjson()), flat);
flat.keySet().removeIf(key -> isDerivedKey(key, derivedIds));
if (row.getDerivedJson() != null) { if (row.getDerivedJson() != null) {
ObjectNode derived = object(row.getDerivedJson()); ObjectNode derived = object(row.getDerivedJson());
derived.remove(qid); derived.remove(qid);

View File

@@ -56,43 +56,43 @@ public class QuotaComputationService {
}) })
.toList(); .toList();
List<StatisticsColumnDto> columns = new ArrayList<>(); List<StatisticsColumnDto> columns = new ArrayList<>();
columns.add(table.getColumns().get(0)); columns.add(table.columns().get(0));
table.getColumns().stream() table.columns().stream()
.filter(column -> !List.of("LABEL", "TOTAL").contains(column.getKind())) .filter(column -> !List.of("LABEL", "TOTAL").contains(column.kind()))
.forEach( .forEach(
column -> { column -> {
// Legacy quota removes the question-title header rows and retains choice labels only. // Legacy quota removes the question-title header rows and retains choice labels only.
List<String> labels = new ArrayList<>(); List<String> labels = new ArrayList<>();
for (int depth = 1; depth < column.getLabels().size(); depth += 2) { for (int depth = 1; depth < column.labels().size(); depth += 2) {
labels.add(column.getLabels().get(depth)); labels.add(column.labels().get(depth));
} }
columns.add(new StatisticsColumnDto(column.getColumnId(), column.getKind(), labels)); columns.add(new StatisticsColumnDto(column.columnId(), column.kind(), labels));
}); });
columns.add( columns.add(
table.getColumns().stream() table.columns().stream()
.filter(column -> "TOTAL".equals(column.getKind())) .filter(column -> "TOTAL".equals(column.kind()))
.findFirst() .findFirst()
.orElseThrow()); .orElseThrow());
List<StatisticsRowDto> headers = List<StatisticsRowDto> headers =
statisticsTableService.headers("", columns, "MERGED"); statisticsTableService.headers("", columns, "MERGED");
List<QuotaRowDto> rows = new ArrayList<>(); List<QuotaRowDto> rows = new ArrayList<>();
for (StatisticsRowDto row : table.getRows()) { for (StatisticsRowDto row : table.rows()) {
List<QuotaCellDto> cells = new ArrayList<>(); List<QuotaCellDto> cells = new ArrayList<>();
cells.add( cells.add(
QuotaCellDto.builder() QuotaCellDto.builder()
.columnIndex(0) .columnIndex(0)
.kind("LABEL") .kind("LABEL")
.textValue( .textValue(
"TOTAL".equals(row.getKind()) ? "Total" : row.getCells().get(0).getTextValue()) "TOTAL".equals(row.kind()) ? "Total" : row.cells().get(0).getTextValue())
.build()); .build());
long rowTargetSum = 0; long rowTargetSum = 0;
for (int columnIndex = 1; columnIndex < columns.size(); columnIndex++) { for (int columnIndex = 1; columnIndex < columns.size(); columnIndex++) {
String columnId = columns.get(columnIndex).getColumnId(); String columnId = columns.get(columnIndex).columnId();
int sourceColumn = 0; int sourceColumn = 0;
while (!table.getColumns().get(sourceColumn).getColumnId().equals(columnId)) { while (!table.columns().get(sourceColumn).columnId().equals(columnId)) {
sourceColumn++; sourceColumn++;
} }
Long complete = row.getCells().get(sourceColumn).getCount(); Long complete = row.cells().get(sourceColumn).getCount();
if (complete == null) { if (complete == null) {
throw BusinessException.validationError( throw BusinessException.validationError(
"QUOTA_STATISTIC_UNSUPPORTED", "통계량 문항은 기존 쿼터 집계에서 지원하지 않습니다."); "QUOTA_STATISTIC_UNSUPPORTED", "통계량 문항은 기존 쿼터 집계에서 지원하지 않습니다.");
@@ -104,31 +104,31 @@ public class QuotaComputationService {
cells.add(cell(columnIndex, complete, target)); cells.add(cell(columnIndex, complete, target));
} }
if (rowTargetSum != 0) { if (rowTargetSum != 0) {
rows.add(new QuotaRowDto(0, row.getRowId(), row.getKind(), cells)); rows.add(new QuotaRowDto(0, row.rowId(), row.kind(), cells));
} }
} }
QuotaRowDto total = QuotaRowDto total =
rows.stream().filter(row -> "TOTAL".equals(row.getKind())).findFirst().orElse(null); rows.stream().filter(row -> "TOTAL".equals(row.kind())).findFirst().orElse(null);
if (total != null) { if (total != null) {
List<QuotaCellDto> cells = new ArrayList<>(); List<QuotaCellDto> cells = new ArrayList<>();
cells.add(total.getCells().get(0)); cells.add(total.cells().get(0));
for (int columnIndex = 1; columnIndex < columns.size(); columnIndex++) { for (int columnIndex = 1; columnIndex < columns.size(); columnIndex++) {
long complete = 0; long complete = 0;
for (QuotaRowDto row : rows) { for (QuotaRowDto row : rows) {
if (!"TOTAL".equals(row.getKind())) { if (!"TOTAL".equals(row.kind())) {
complete += row.getCells().get(columnIndex).getComplete(); complete += row.cells().get(columnIndex).complete();
} }
} }
QuotaCellDto original = total.getCells().get(columnIndex); QuotaCellDto original = total.cells().get(columnIndex);
cells.add( cells.add(
cell( cell(
columnIndex, columnIndex,
complete, complete,
new Target(original.getTarget(), original.getIsUsed(), original.getQuotaId()))); new Target(original.target(), original.isUsed(), original.quotaId())));
} }
rows.remove(total); rows.remove(total);
if (!index.isEmpty()) { if (!index.isEmpty()) {
rows.add(new QuotaRowDto(0, total.getRowId(), "TOTAL", cells)); rows.add(new QuotaRowDto(0, total.rowId(), "TOTAL", cells));
} }
} }
List<QuotaRowDto> positionedRows = new ArrayList<>(); List<QuotaRowDto> positionedRows = new ArrayList<>();
@@ -136,7 +136,7 @@ public class QuotaComputationService {
QuotaRowDto row = rows.get(rowIndex); QuotaRowDto row = rows.get(rowIndex);
positionedRows.add( positionedRows.add(
new QuotaRowDto( new QuotaRowDto(
headers.size() + rowIndex, row.getRowId(), row.getKind(), row.getCells())); headers.size() + rowIndex, row.rowId(), row.kind(), row.cells()));
} }
return QuotaResultDto.builder() return QuotaResultDto.builder()
.quotaSetId(quotaSet.getId()) .quotaSetId(quotaSet.getId())
@@ -154,11 +154,11 @@ public class QuotaComputationService {
List<Entry> entries, StatisticsRowDto row, String index, String columnId, List<String> banners) { List<Entry> entries, StatisticsRowDto row, String index, String columnId, List<String> banners) {
List<Entry> matching = entries; List<Entry> matching = entries;
if (!index.isEmpty() if (!index.isEmpty()
&& StatisticsArithmetic.number(row.getRowId()) != null && StatisticsArithmetic.number(row.rowId()) != null
&& !"TOTAL".equals(row.getKind())) { && !"TOTAL".equals(row.kind())) {
matching = matching =
matching.stream() matching.stream()
.filter(entry -> value(entry.values(), index).equals(row.getRowId())) .filter(entry -> value(entry.values(), index).equals(row.rowId()))
.toList(); .toList();
} }
if (!"i".equals(columnId)) { if (!"i".equals(columnId)) {

View File

@@ -52,11 +52,11 @@ public class ExternalAccessInterceptor implements HandlerInterceptor {
String urlKey = userId.substring(KartConstant.EXTERNAL_USER_PREFIX.length()); String urlKey = userId.substring(KartConstant.EXTERNAL_USER_PREFIX.length());
ShareLinkDto link = ShareLinkDto link =
(ShareLinkDto) request.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE); (ShareLinkDto) request.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE);
if (link == null || !urlKey.equals(link.getUrlKey())) { if (link == null || !urlKey.equals(link.urlKey())) {
link = shareLinkService.lookup(urlKey); link = shareLinkService.lookup(urlKey);
} }
int expectedRole = int expectedRole =
link.isPageOnly() link.pageOnly()
? KartConstant.EXTERNAL_PAGE_COPY_ROLE ? KartConstant.EXTERNAL_PAGE_COPY_ROLE
: KartConstant.EXTERNAL_URL_COPY_ROLE; : KartConstant.EXTERNAL_URL_COPY_ROLE;
if (!Integer.valueOf(expectedRole).equals(claims.getUserRole())) { if (!Integer.valueOf(expectedRole).equals(claims.getUserRole())) {
@@ -66,14 +66,14 @@ public class ExternalAccessInterceptor implements HandlerInterceptor {
Map<String, String> variables = Map<String, String> variables =
(Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (variables == null if (variables == null
|| !link.getProjectType().getCode().toString().equals(variables.get("projectType")) || !link.projectType().getCode().toString().equals(variables.get("projectType"))
|| !link.getPkey().equals(variables.get("pkey"))) { || !link.pkey().equals(variables.get("pkey"))) {
// Visit body scope is checked in LogController after JSON binding. // Visit body scope is checked in LogController after JSON binding.
if (!"/api/v1/log/visit".equals(pattern) || !"POST".equals(request.getMethod())) { if (!"/api/v1/log/visit".equals(pattern) || !"POST".equals(request.getMethod())) {
throw denied(); throw denied();
} }
} }
String page = URI.create(link.getRealUrl()).getPath(); String page = URI.create(link.realUrl()).getPath();
boolean allowed = "/api/v1/log/visit".equals(pattern); boolean allowed = "/api/v1/log/visit".equals(pattern);
if ("GET".equals(request.getMethod())) { if ("GET".equals(request.getMethod())) {
allowed |= allowed |=
@@ -82,7 +82,7 @@ public class ExternalAccessInterceptor implements HandlerInterceptor {
"/api/v1/project/{projectType}/{pkey}/question/{qid}") "/api/v1/project/{projectType}/{pkey}/question/{qid}")
.contains(pattern); .contains(pattern);
allowed |= allowed |=
(!link.isPageOnly() || page.equals("/Report/Current")) (!link.pageOnly() || page.equals("/Report/Current"))
&& Set.of( && Set.of(
"/api/v1/project/{projectType}/{pkey}/progress/day", "/api/v1/project/{projectType}/{pkey}/progress/day",
"/api/v1/project/{projectType}/{pkey}/progress/type", "/api/v1/project/{projectType}/{pkey}/progress/type",
@@ -90,28 +90,28 @@ public class ExternalAccessInterceptor implements HandlerInterceptor {
"/api/v1/project/{projectType}/{pkey}/progress/screen") "/api/v1/project/{projectType}/{pkey}/progress/screen")
.contains(pattern); .contains(pattern);
allowed |= allowed |=
(!link.isPageOnly() || page.equals("/Report/Quota")) (!link.pageOnly() || page.equals("/Report/Quota"))
&& pattern.equals("/api/v1/quota/{projectType}/{pkey}/list"); && pattern.equals("/api/v1/quota/{projectType}/{pkey}/list");
if (pattern.equals("/api/v1/project/{projectType}/{pkey}/bookmark/list")) { if (pattern.equals("/api/v1/project/{projectType}/{pkey}/bookmark/list")) {
String bookmarkPage = request.getParameter("page"); String bookmarkPage = request.getParameter("page");
allowed |= allowed |=
Set.of("TABULATION", "CROSSTAB").contains(bookmarkPage == null ? "" : bookmarkPage) Set.of("TABULATION", "CROSSTAB").contains(bookmarkPage == null ? "" : bookmarkPage)
&& (!link.isPageOnly() && (!link.pageOnly()
|| (page.equals("/Report/Tabulation") && "TABULATION".equals(bookmarkPage)) || (page.equals("/Report/Tabulation") && "TABULATION".equals(bookmarkPage))
|| (page.equals("/Report/Crosstab") && "CROSSTAB".equals(bookmarkPage))); || (page.equals("/Report/Crosstab") && "CROSSTAB".equals(bookmarkPage)));
} }
} else if ("POST".equals(request.getMethod())) { } else if ("POST".equals(request.getMethod())) {
allowed |= allowed |=
(!link.isPageOnly() || Set.of("/Report/Tabulation", "/Report/Crosstab").contains(page)) (!link.pageOnly() || Set.of("/Report/Tabulation", "/Report/Crosstab").contains(page))
&& pattern.equals("/api/v1/project/{projectType}/{pkey}/export/excel/table"); && pattern.equals("/api/v1/project/{projectType}/{pkey}/export/excel/table");
allowed |= allowed |=
(!link.isPageOnly() || page.equals("/Report/Quota")) (!link.pageOnly() || page.equals("/Report/Quota"))
&& pattern.equals("/api/v1/quota/{projectType}/{pkey}/export/excel"); && pattern.equals("/api/v1/quota/{projectType}/{pkey}/export/excel");
allowed |= allowed |=
(!link.isPageOnly() || Set.of("/Report/Tabulation", "/Report/Crosstab").contains(page)) (!link.pageOnly() || Set.of("/Report/Tabulation", "/Report/Crosstab").contains(page))
&& pattern.equals("/api/v1/project/{projectType}/{pkey}/statistics/result"); && pattern.equals("/api/v1/project/{projectType}/{pkey}/statistics/result");
allowed |= allowed |=
(!link.isPageOnly() || page.equals("/Report/Quota")) (!link.pageOnly() || page.equals("/Report/Quota"))
&& pattern.equals("/api/v1/quota/{projectType}/{pkey}/{quotaOrder}/result"); && pattern.equals("/api/v1/quota/{projectType}/{pkey}/{quotaOrder}/result");
} }
if (!allowed) { if (!allowed) {

View File

@@ -25,7 +25,7 @@ public class LegacyProjectKeyService {
public String encode(ProjectRefDto project) { public String encode(ProjectRefDto project) {
String plain = String plain =
(project.getProjectType() == ProjectType.KIWI ? "|K|W|" : "") + project.getPkey(); (project.projectType() == ProjectType.KIWI ? "|K|W|" : "") + project.pkey();
byte[] cipher = transform(Cipher.ENCRYPT_MODE, plain.getBytes(StandardCharsets.UTF_8)); byte[] cipher = transform(Cipher.ENCRYPT_MODE, plain.getBytes(StandardCharsets.UTF_8));
return URLEncoder.encode(Base64.getEncoder().encodeToString(cipher), StandardCharsets.UTF_8); return URLEncoder.encode(Base64.getEncoder().encodeToString(cipher), StandardCharsets.UTF_8);
} }

View File

@@ -235,7 +235,7 @@ public class StatisticsAggregationService {
addScaleGroups(rows, columns, index, request); addScaleGroups(rows, columns, index, request);
} }
for (StatisticsValueGroupDto group : request.getValueGroups()) { for (StatisticsValueGroupDto group : request.getValueGroups()) {
addGroup(rows, columns, index, group.getLabel(), group.getValues(), request); addGroup(rows, columns, index, group.label(), group.values(), request);
} }
if ("scale".equals(type) && !isNps(index)) { if ("scale".equals(type) && !isNps(index)) {
addStatistic(rows, columns, index, KartConstant.MEAN, request); addStatistic(rows, columns, index, KartConstant.MEAN, request);
@@ -526,8 +526,8 @@ public class StatisticsAggregationService {
List<StatisticsCellDto> cells = new ArrayList<>(); List<StatisticsCellDto> cells = new ArrayList<>();
cells.add(StatisticsTableService.text(0, "NPS")); cells.add(StatisticsTableService.text(0, "NPS"));
for (int column = 1; column <= columns.size(); column++) { for (int column = 1; column <= columns.size(); column++) {
StatisticsCellDto promoters = rows.get(promotersRow).getCells().get(column); StatisticsCellDto promoters = rows.get(promotersRow).cells().get(column);
StatisticsCellDto detractors = rows.get(detractorsRow).getCells().get(column); StatisticsCellDto detractors = rows.get(detractorsRow).cells().get(column);
Double percent = Double percent =
promoters.getPercent() == null || detractors.getPercent() == null promoters.getPercent() == null || detractors.getPercent() == null
? null ? null

View File

@@ -57,14 +57,14 @@ public class StatisticsTableService {
flat flat
? 1 ? 1
: Math.max( : Math.max(
1, columns.stream().mapToInt(column -> column.getLabels().size()).max().orElse(1)); 1, columns.stream().mapToInt(column -> column.labels().size()).max().orElse(1));
List<List<StatisticsCellDto>> cells = new ArrayList<>(); List<List<StatisticsCellDto>> cells = new ArrayList<>();
for (int row = 0; row < height; row++) { for (int row = 0; row < height; row++) {
cells.add(new ArrayList<>()); cells.add(new ArrayList<>());
} }
cells.get(0).add(text(0, title).toBuilder().rowSpan(height).build()); cells.get(0).add(text(0, title).toBuilder().rowSpan(height).build());
for (int column = 1; column < columns.size(); column++) { for (int column = 1; column < columns.size(); column++) {
List<String> labels = columns.get(column).getLabels(); List<String> labels = columns.get(column).labels();
if (flat) { if (flat) {
cells.get(0).add(text(column, String.join(" - ", labels))); cells.get(0).add(text(column, String.join(" - ", labels)));
continue; continue;
@@ -105,8 +105,8 @@ public class StatisticsTableService {
if (previous == null || column <= 1) { if (previous == null || column <= 1) {
return false; return false;
} }
List<String> labels = columns.get(column).getLabels(); List<String> labels = columns.get(column).labels();
List<String> previousLabels = columns.get(column - 1).getLabels(); List<String> previousLabels = columns.get(column - 1).labels();
boolean stretches = row == Math.max(1, labels.size()) - 1 && height - row > 1; boolean stretches = row == Math.max(1, labels.size()) - 1 && height - row > 1;
return previous.getRowSpan() == 1 return previous.getRowSpan() == 1
&& !stretches && !stretches
@@ -122,7 +122,7 @@ public class StatisticsTableService {
StatisticsRowDto row = body.get(rowIndex); StatisticsRowDto row = body.get(rowIndex);
rows.add( rows.add(
new StatisticsRowDto( new StatisticsRowDto(
rowIndex + headerCount, row.getRowId(), row.getKind(), row.getCells())); rowIndex + headerCount, row.rowId(), row.kind(), row.cells()));
} }
return rows; return rows;
} }
@@ -136,11 +136,11 @@ public class StatisticsTableService {
for (int rowIndex = 0; rowIndex < columns.size(); rowIndex++) { for (int rowIndex = 0; rowIndex < columns.size(); rowIndex++) {
List<StatisticsCellDto> cells = new ArrayList<>(); List<StatisticsCellDto> cells = new ArrayList<>();
for (StatisticsRowDto row : source) { for (StatisticsRowDto row : source) {
for (StatisticsCellDto cell : row.getCells()) { for (StatisticsCellDto cell : row.cells()) {
if (cell.getColumnIndex() == rowIndex) { if (cell.getColumnIndex() == rowIndex) {
cells.add( cells.add(
cell.toBuilder() cell.toBuilder()
.columnIndex(row.getRowIndex()) .columnIndex(row.rowIndex())
.rowSpan(cell.getColSpan()) .rowSpan(cell.getColSpan())
.colSpan(cell.getRowSpan()) .colSpan(cell.getRowSpan())
.build()); .build());
@@ -151,15 +151,15 @@ public class StatisticsTableService {
transposed.add( transposed.add(
new StatisticsRowDto( new StatisticsRowDto(
rowIndex, rowIndex,
columns.get(rowIndex).getColumnId(), columns.get(rowIndex).columnId(),
rowIndex == 0 ? "HEADER" : columns.get(rowIndex).getKind(), rowIndex == 0 ? "HEADER" : columns.get(rowIndex).kind(),
cells)); cells));
} }
List<StatisticsColumnDto> transposedColumns = List<StatisticsColumnDto> transposedColumns =
source.stream() source.stream()
.map( .map(
row -> row ->
new StatisticsColumnDto(row.getRowId(), row.getKind(), List.of(row.getRowId()))) new StatisticsColumnDto(row.rowId(), row.kind(), List.of(row.rowId())))
.toList(); .toList();
List<StatisticsRowDto> headers = transposed.isEmpty() ? List.of() : List.of(transposed.get(0)); List<StatisticsRowDto> headers = transposed.isEmpty() ? List.of() : List.of(transposed.get(0));
List<StatisticsRowDto> rows = List<StatisticsRowDto> rows =

View File

@@ -30,9 +30,9 @@ public class StatisticsTextService {
public List<StatisticsWordDto> analyze( public List<StatisticsWordDto> analyze(
ProjectRefDto project, String qid, List<SurveyResponseDto> responses) { ProjectRefDto project, String qid, List<SurveyResponseDto> responses) {
List<String> texts = answerTexts(qid, responses); List<String> texts = answerTexts(qid, responses);
Set<String> selectedTags = new LinkedHashSet<>(nlpRepository.tags(project.getPkey(), qid)); Set<String> selectedTags = new LinkedHashSet<>(nlpRepository.tags(project.pkey(), qid));
List<NlpTokenDto> tokens = List<NlpTokenDto> tokens =
kiwiNlpService.tokenize(texts, nlpRepository.words(project.getPkey(), qid)); kiwiNlpService.tokenize(texts, nlpRepository.words(project.pkey(), qid));
// The same word with a different tag is counted separately, in first-appearance order. // The same word with a different tag is counted separately, in first-appearance order.
LinkedHashMap<NlpTokenDto, Long> counts = new LinkedHashMap<>(); LinkedHashMap<NlpTokenDto, Long> counts = new LinkedHashMap<>();
for (NlpTokenDto token : tokens) { for (NlpTokenDto token : tokens) {

View File

@@ -19,7 +19,7 @@ public class QuestionImportService {
public List<ImportQuestionDto> prepare(UploadTableDto table) { public List<ImportQuestionDto> prepare(UploadTableDto table) {
List<ImportQuestionDto> result = new ArrayList<>(); List<ImportQuestionDto> result = new ArrayList<>();
List<List<String>> rows = table.getRows(); List<List<String>> rows = table.rows();
int first = 0; int first = 0;
while (first < rows.size() && !rows.get(first).get(0).matches("[A-Za-z][A-Za-z0-9]*")) { while (first < rows.size() && !rows.get(first).get(0).matches("[A-Za-z][A-Za-z0-9]*")) {
first++; first++;
@@ -86,6 +86,17 @@ public class QuestionImportService {
labels.set(Integer.toString(labels.size() + 1), label); labels.set(Integer.toString(labels.size() + 1), label);
} }
} }
// User decision: O/N without input rows (none, attribute-only or blank titles) get one
// input with an empty label instead of failing.
if (itemType.equals("open") && labels.isEmpty()) {
labels.set(
"1",
objectMapper
.createObjectNode()
.put("label", "")
.put("option", type.equals("n") ? "num" : "all")
.put("must", "1"));
}
ObjectNode dataset = objectMapper.createObjectNode(); ObjectNode dataset = objectMapper.createObjectNode();
if (!labels.isEmpty()) { if (!labels.isEmpty()) {
dataset.set(itemType, labels); dataset.set(itemType, labels);

View File

@@ -6,10 +6,12 @@ import com.kri.common.feature.json.JsonUtil;
import com.kri.common.feature.web.BusinessException; import com.kri.common.feature.web.BusinessException;
import com.kri.kart.server.dto.upload.ImportResponseDto; import com.kri.kart.server.dto.upload.ImportResponseDto;
import com.kri.kart.server.dto.upload.UploadTableDto; import com.kri.kart.server.dto.upload.UploadTableDto;
import com.kri.kart.server.service.derived.DerivedComputationService;
import java.time.Duration; import java.time.Duration;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
@@ -24,13 +26,21 @@ public class ResponseImportService {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
public List<ImportResponseDto> prepare(UploadTableDto table, Set<String> multiQuestions) { public List<ImportResponseDto> prepare(UploadTableDto table, Set<String> multiQuestions) {
List<String> headers = table.getHeaders(); return prepare(table, multiQuestions, List.of());
}
/**
* Columns of stored derived variables are skipped; their values are regenerated after the upload.
*/
public List<ImportResponseDto> prepare(
UploadTableDto table, Set<String> multiQuestions, Collection<String> derivedIds) {
List<String> headers = table.headers();
for (String required : List.of("IDKEY", "Status", "start_date", "end_date")) { for (String required : List.of("IDKEY", "Status", "start_date", "end_date")) {
if (headers.stream().noneMatch(header -> header.equalsIgnoreCase(required))) { if (headers.stream().noneMatch(header -> header.equalsIgnoreCase(required))) {
throw BusinessException.badRequest("응답 파일의 고정 헤더를 확인해 주세요."); throw BusinessException.badRequest("응답 파일의 고정 헤더를 확인해 주세요.");
} }
} }
if (table.getRows().size() < 2) { if (table.rows().size() < 2) {
throw BusinessException.badRequest("별칭 행 다음에 업로드할 응답이 필요합니다."); throw BusinessException.badRequest("별칭 행 다음에 업로드할 응답이 필요합니다.");
} }
List<String> roots = List<String> roots =
@@ -41,8 +51,8 @@ public class ResponseImportService {
.toList(); .toList();
List<ImportResponseDto> result = new ArrayList<>(); List<ImportResponseDto> result = new ArrayList<>();
String now = DateTimeUtil.nowKstLocalDateTime().format(TIMESTAMP); String now = DateTimeUtil.nowKstLocalDateTime().format(TIMESTAMP);
for (int rowIndex = 1; rowIndex < table.getRows().size(); rowIndex++) { for (int rowIndex = 1; rowIndex < table.rows().size(); rowIndex++) {
var row = table.getRows().get(rowIndex); var row = table.rows().get(rowIndex);
String idkey = value(headers, row, "IDKEY"); String idkey = value(headers, row, "IDKEY");
String status = value(headers, row, "Status"); String status = value(headers, row, "Status");
String start = value(headers, row, "start_date"); String start = value(headers, row, "start_date");
@@ -74,6 +84,9 @@ public class ResponseImportService {
|| key.startsWith("T" + root + "_"))) { || key.startsWith("T" + root + "_"))) {
continue; continue;
} }
if (DerivedComputationService.isDerivedKey(key, derivedIds)) {
continue;
}
String cell = row.get(col).trim().replace(".00", ""); String cell = row.get(col).trim().replace(".00", "");
if (cell.isEmpty()) { if (cell.isEmpty()) {
continue; continue;

View File

@@ -22,7 +22,7 @@ public class UploadArchiveService {
} }
public String store(ProjectRefDto project, String type, String extension, MultipartFile file) { public String store(ProjectRefDto project, String type, String extension, MultipartFile file) {
String pkey = project.getPkey().replaceAll("[^A-Za-z0-9_-]", "_"); String pkey = project.pkey().replaceAll("[^A-Za-z0-9_-]", "_");
String name = String name =
type type
+ "_" + "_"

View File

@@ -6,4 +6,12 @@ kri:
url: jdbc:mysql://db-md87m.vpc-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8 url: jdbc:mysql://db-md87m.vpc-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8
username: kriit username: kriit
password: it#51304 password: it#51304
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
kart:
database:
konkiwi:
url: 'jdbc:sqlserver://mssql-7sq2n.vpc-cdb.ntruss.com;databaseName={konkiwi};encrypt=false'
username: 'kadmin'
password: 'it#51304'
maximum-pool-size: 5

View File

@@ -6,4 +6,12 @@ kri:
url: jdbc:mysql://db-md87m.vpc-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8 url: jdbc:mysql://db-md87m.vpc-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8
username: kriit username: kriit
password: it#51304 password: it#51304
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
kart:
database:
konkiwi:
url: 'jdbc:sqlserver://mssql-7sq2n.vpc-cdb.ntruss.com;databaseName={konkiwi};encrypt=false'
username: 'kadmin'
password: 'it#51304'
maximum-pool-size: 5

View File

@@ -33,6 +33,9 @@
<when test='authenticatedUserTeam == "M101"'>AND GKEY = #{authenticatedUserTeam}</when> <when test='authenticatedUserTeam == "M101"'>AND GKEY = #{authenticatedUserTeam}</when>
<otherwise><![CDATA[AND GKEY <> 'M101']]></otherwise> <otherwise><![CDATA[AND GKEY <> 'M101']]></otherwise>
</choose> </choose>
<if test='authenticatedUserTeam != null and authenticatedUserTeam.startsWith("R")'>
AND GKEY = #{authenticatedUserTeam}
</if>
</if> </if>
<include refid="assignmentVisibility"/> <include refid="assignmentVisibility"/>
</sql> </sql>
@@ -79,6 +82,8 @@
SELECT TOP(50) * FROM PROJECT WITH(NOLOCK) SELECT TOP(50) * FROM PROJECT WITH(NOLOCK)
WHERE JSON_VALUE(JSON_QUERY(PROJECTJSON, '$.must'), '$.status') != 1 WHERE JSON_VALUE(JSON_QUERY(PROJECTJSON, '$.must'), '$.status') != 1
AND JSON_VALUE(PROJECTJSON, '$.must.companytype') NOT IN ('4', '5') AND JSON_VALUE(PROJECTJSON, '$.must.companytype') NOT IN ('4', '5')
AND JSON_VALUE(PROJECTJSON, '$.must.title_inner') NOT LIKE '%사례비%'
AND JSON_VALUE(PROJECTJSON, '$.must.status') IN (2, 3)
<include refid="dinOwnerExclusion"/> <include refid="dinOwnerExclusion"/>
<include refid="summaryVisibility"/> <include refid="summaryVisibility"/>
ORDER BY create_date DESC ORDER BY create_date DESC