Compare commits
29 Commits
c4ea839df3
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 40ac7d2742 | |||
| ad82d6f692 | |||
| d16c5e6733 | |||
| 55d068a17f | |||
| 6e1d57414e | |||
| 9d1ffdf594 | |||
| fb76c9dcb3 | |||
| 7eb4d3bc9e | |||
| 667de46a72 | |||
| 47c598a61c | |||
| 5c70464928 | |||
| 215a5059e3 | |||
| d61d7cf08d | |||
| 9fa4070be2 | |||
| 71e94fbc47 | |||
| 32b3d374a3 | |||
| 3164b70245 | |||
| 9bf9cbe135 | |||
| 0c7c29dead | |||
| 0e78680571 | |||
| e4a99044ba | |||
| 4d4406ed2b | |||
| 79c9619733 | |||
| 8b61e61a25 | |||
| f5a9f864d8 | |||
| 04b87d8b69 | |||
| 37ebc1b6bb | |||
| a0ea7d861e | |||
| 486966fe73 |
@@ -21,6 +21,7 @@ Source: .agent/consumer-references/platform-capabilities.md
|
||||
- Common Web may register error handling, tracing/MDC, request-user resolution, enum conversion, and CORS behavior. Check for overlap before defining consumer-local equivalents.
|
||||
- Swagger support requires springdoc and defines the shared Bearer/API-key schemes and grouped paths.
|
||||
- When Swagger auto-configuration is active (`kri.swagger.enabled=true`, default), `RequestUserContext` controller arguments are ignored as request inputs globally, including their `authenticated`, `clientIp`, and `userRole` properties. Runtime argument resolution is unchanged.
|
||||
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
|
||||
- Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies.
|
||||
- HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers.
|
||||
- The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
## KART Server Repository Rules
|
||||
|
||||
- Java 17, Spring Boot 3.5.7, KriCommon `com.kri.common:starter:beta.1.6.9`.
|
||||
- Java 17, Spring Boot 3.5.7, KriCommon `com.kri.common:starter:beta.1.7.1`.
|
||||
- Use MyBatis with explicit KON, KONKIWI and kart (Report DB) SQL Server sessions and transaction managers. Do not infer a source from pkey alone.
|
||||
- ProjectType codes are 0=KON and 1=KIWI; reject unsupported types and legacy key markers in new project identifiers.
|
||||
- This API is for the new system. Legacy API compatibility is not required; shared database compatibility is required.
|
||||
@@ -30,6 +30,7 @@
|
||||
|
||||
- Follow Contact: inject com.kri.common.feature.web.RequestUserContext ctx into controller methods; use ctx.getUserRole() and ctx.getUserTeam() for authorization and pass them to the service as needed.
|
||||
- Use only the context resolved by common authentication, never role/team fields submitted in request DTOs.
|
||||
- Place Spring MVC interceptors under the interceptor package. Inject KriCommon RequestUserContextProvider to resolve request identity; keep project and share-link authorization policies in KART.
|
||||
- Do not introduce separate PrincipalKind/ProjectPermission/ReportPage enums or generic grant models for this purpose.
|
||||
- External authentication must still enforce its stored project/page scope and restrict access to report reads and aggregate Excel; role/team alone must not authorize access outside the link scope.
|
||||
|
||||
@@ -111,7 +112,7 @@
|
||||
- Follow existing question organization. Return N and percent together, including Total. Preserve repeated rank/matrix occurrences, original numeric missing/mean/statistic rules, scale/reverse/NPS, grouped values and TABULATION denominators. Frontend chooses PRTMODE presentation without requery.
|
||||
- Keep original empty-base semantics: ordinary cell/Total percentages are 0; undefined group/statistic values are null with '-' display. Use 15-significant-digit C# double-format behavior and midpoint-away rounding, validated by legacy fixtures.
|
||||
- StatisticsMapper uses survey sessions, parameterized complete/TEST/date conditions, original distinct derived/profile joins and selected storage-group projection. Filter data is private and separate from projected aggregation data. AST filters never inject user SQL.
|
||||
- User approved the latest Kiwi model after finding the original DLL was 0.15.2. Use matching official KiwiJava/model 0.24.0 CONG instead of pinning SBG. Model-result changes are allowed; preserve Report NLP dictionary/tag scopes, word scores 10/50/100, tag/length/SL selection and stable top-100 frequency logic. Add no new stopword rules.
|
||||
- User approved the latest Kiwi model after finding the original DLL was 0.15.2. Use matching official KiwiJava/model 0.24.0 CONG instead of pinning SBG. Model-result changes are allowed; preserve Report NLP dictionary/tag scopes, word scores 10/50/100, tag/length/SL selection and stable top-100 frequency logic. Stopwords exist only as the REPORT_NLP_WORD STOP rows described under Kiwi NLP accuracy; add no other stopword rules.
|
||||
- Configure kri.kart.nlp.model-directory as ./nlp_model/v0.24.0, install model separately, ignore runtime models in Git, and choose the platform-specific official jar at build time. Do not claim Ubuntu execution from Windows tests. Missing native/model infrastructure is explicit 503, not empty successful NLP output.
|
||||
- Per user decision, the legacy external-Referer condition is removed: every general statistics batch writes Get Report Data once through LogService. Quota results write QUOTA VIEW only, never Get Report Data. Do not add a separate logging endpoint.
|
||||
- Validate through original C# synthetic calculation fixtures, authenticated API/Swagger tests, source-bound MyBatis tests and opt-in actual native analysis with -PkiwiModelDirectory. Actual SQL Server equivalence and deployment performance remain separate checks.
|
||||
@@ -145,6 +146,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.
|
||||
- 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.
|
||||
- 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 +159,8 @@
|
||||
## 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.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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. 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.
|
||||
- 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.
|
||||
@@ -167,7 +169,7 @@
|
||||
|
||||
- Contact calls the legacy scoped project-list endpoint and skey-to-share sequence; KON/KON-KIWI survey.js calls respondent-derived recalculation at END. Preserve new-server-only migration scope: do not modify those consumer repositories automatically.
|
||||
- GET /project/list without search keeps existing screen-list behavior. With projectType/intranetCode/userTeam, use the legacy linked query: first underscore code segment, R-team exact GKEY else exclude M101, keyword overrides code with pkey/title LIKE, newest first. Do not mix ordinary-screen year/must-view/status/company/din-owner filters or KIWI title prefix into linked results. Query userTeam is not an authentication claim; additionally enforce the authenticated read visibility rules below, without adding ordinary-screen business filters.
|
||||
- POST /project/{projectType}/{pkey}/derived/respondent/{respondentId}/recalculate reuses current calculation in definition order, ensures the legacy empty derived row, scopes group clear/query/save to PKEY+IDKEY, reads actual completed responses only and uses the selected survey transaction. Preserve historical date values on no match and add no new SiteLog point.
|
||||
- POST /project/{projectType}/{pkey}/derived/respondent/{respondentId}/recalculate reuses current calculation in definition order, ensures the legacy empty derived row, scopes group clear/query/save to PKEY+IDKEY, reads non-TEST responses regardless of Status (user decision 2026-10-27, allowing calculation before completion status is saved) and uses the selected survey transaction. Whole-project recalculation retains Status = 10. Preserve historical date values on no match and add no new SiteLog point.
|
||||
- Local prefix search did not locate a PRJCT_/KRIC_SYS_ caller; do not claim production non-use or remove legacy registrations. Existing Common API Key auth covers new server-to-server calls; verified REPORT_URL covers CLIENT. Do not add unauthenticated system-name/prefix-to-JWT exchange or trust request-supplied identity. Incoming service-code kart-server API Key registration is separate from the outgoing Intranet key.
|
||||
- Existing browser survey hooks need a server-side proxy/API Key integration at later cutover. Caller conversion, real API Key registration/traffic, shared DB checks, general authorization and deployment remain separate work.
|
||||
|
||||
@@ -180,8 +182,19 @@
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
- Scope is these read conditions only. Do not add generic per-project/mutation/owner authorization, change original aggregations/Excel, or weaken External scope. Validate actual bound mapper SQL and H2 results on both sources, empty assignments, precise id routing, trusted JWT/API Key context versus forged query fields; no shared DB execution.
|
||||
|
||||
## Kiwi NLP accuracy (user decisions 2026-11-10)
|
||||
|
||||
- The legacy C# report services are retired; REPORT_NLP_WORD/TAG are no longer read by them.
|
||||
- KiwiNlpService builds with BuildOption.default_ and analyzes with Match.allWithNormalizing | oovChrModel plus basicTypoSetWithContinual typo correction (threshold 2.5). Do not revert to AnalyzeOption(0).
|
||||
- User dictionary: register each (text, tag) once with its highest scope score, because Kiwi keeps the last duplicate score and the query has no order. Trim/uppercase tags. Log only registered/skipped/rejected counts, never words.
|
||||
- Statistics options: wordMergeMode 1=ALL, 2=NOUN (default; NNG/NNP/NNB/NR/NP/SL/SH), 3=NONE sums the same text across tags, keeping the most frequent tag (first on ties) and first-appearance order. compoundNounMaxTokens 1-5 (default 3; 1 disables) joins noun prefixes/suffixes and merges NNG/NNP/SL runs attached within one word when they contain a Korean noun; NNP if any part is NNP; longer runs stay separate.
|
||||
- Synonyms (user decision 2026-11-11, replacing the separate REPORT_NLP_SYNONYM table): a REPORT_NLP_WORD row with SOURCE_TEXT (NVARCHAR(128), nullable; WORD_TEXT is NVARCHAR(128)) replaces SOURCE_TEXT with WORD_TEXT/WORD_TAG. WORD_TEXT always means the result word. Scope priority question > project > ALL uses the 100/50/10 scores. The column must exist before deployment. Sources are pre-analyzed (score 200, above every user word) after registering the target as a word with score 0 unless a plain row for the same target already registered it with its scope score, because Kiwi rejects a target morpheme missing from its dictionary such as LG/NNP; a failing row is skipped, never a 503; a spaced source also covers its spaceless form and replaces whole token runs only when no noun of the same word continues the run.
|
||||
- Stopwords (불용어): REPORT_NLP_WORD rows with WORD_TAG STOP (case-insensitive) are never registered in Kiwi. Any scope excludes the final word (after synonyms and compound merging) for every tag, comparing trimmed, space-collapsed text case-insensitively; SOURCE_TEXT is ignored on STOP rows.
|
||||
- User dictionary words and synonym targets take precedence over everything: they are never merged with neighbors.
|
||||
- The original analyze(project, qid, responses) and tokenize(texts, dictionary) overloads keep the previous behavior (synonym rows ignored; no stopwords or merging). Only the statistics API uses the new options.
|
||||
|
||||
@@ -246,6 +246,8 @@ When implementation is complete, report in Korean:
|
||||
- For HTTP/2 header safety and original upstream error propagation, use the shared HTTP/bypass features documented in the routed platform-capabilities reference instead of implementing consumer-local header filters and raw-response exception handlers.
|
||||
- Response customizers may call `requireSuccess()`; its upstream exception propagates unchanged. Response charset parsing ignores charset-like text inside other quoted header parameters.
|
||||
- When Swagger auto-configuration is active, `RequestUserContext` controller arguments are excluded from request input documentation; server-side authentication and client IP injection remain unchanged.
|
||||
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
|
||||
- ExcelMapper's Path-based readStreaming and readHeaderStreaming use PackageAccess.READ, preserving source bytes, size, and modification time, including repeated reads and callback failures. Read-only files are supported, and file handles are released on success or failure; option validation, exception handling, and SAX streaming remain unchanged.
|
||||
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.
|
||||
|
||||
### Required Shared References
|
||||
|
||||
12
README.md
12
README.md
@@ -148,13 +148,19 @@ ProjectMapper는 list/summary/mustViewPkeys를 유지하고 ProgressMapper/Progr
|
||||
|
||||
필터는 `filter`의 AST로 입력한다. 그룹 AND/OR/NOT는 `children`, 조건 EQ/NE/GT/GE/LT/LE/IN/NOT_IN/BETWEEN/IS_ANSWERED/IS_UNANSWERED는 `dimensionId`, `reference=QID|VARIABLE`, `values`를 사용한다. JSON 숫자는 수치 비교, 문자열은 기존 SQL collation처럼 대소문자 무시 비교다. 부정 조건은 일치 응답이 하나라도 있으면 제외하고 해당 키가 없는 응답은 포함하는 기존 NOT EXISTS 의미를 유지한다. IS_ANSWERED는 기존 IS NOT NULL 의미여서 빈 문자열도 포함한다. 필터 문자열을 SQL에 삽입하지 않는다. 필터 깊이는 32, 그룹당 자식은 128까지 허용한다.
|
||||
|
||||
주관식 문자열은 `indexes=["QID_입력칸"]`으로 같은 API를 호출한다. `type=TEXT_ANALYSIS`와 `words[{text,tag,count}]`를 반환하며 원문·IDKEY와 기존의 가짜 제목 데이터 행을 노출하지 않는다. 기존 REPORT_NLP_TAG/WORD의 전체·프로젝트·문항 범위 및 사전 점수 10/50/100, SL 포함·품사/길이 조건, 같은 단어의 품사별 별도 빈도와 빈도 내림차순/동률 최초 등장 순서/상위 100개를 유지한다. 문장별 분리는 토큰을 빠뜨리지 않으므로 결과를 전체 토큰 빈도로 집계한다. 별도의 불용어 규칙을 추가하지 않는다.
|
||||
주관식 문자열은 `indexes=["QID_입력칸"]`으로 같은 API를 호출한다. `type=TEXT_ANALYSIS`와 `words[{text,tag,count}]`를 반환하며 원문·IDKEY와 기존의 가짜 제목 데이터 행을 노출하지 않는다. 기존 REPORT_NLP_TAG/WORD의 전체·프로젝트·문항 범위 및 사전 점수 10/50/100, SL 포함·품사/길이 조건, 빈도 내림차순/동률 최초 등장 순서/상위 100개를 유지한다. 문장별 분리는 토큰을 빠뜨리지 않으므로 결과를 전체 토큰 빈도로 집계한다.
|
||||
|
||||
사용자 결정에 따라 최신 공식 KiwiJava·모델 **0.24.0**을 사용한다. 기존 DLL은 실제 실행에서 0.15.2로 확인되었으며 기존 모델은 Java 0.20.4에서도 로딩되지 않았다. 최신 모델 적용에 따른 형태소 결과 변화는 허용하되 Report DB 사전·품사 선택·빈도 집계 규칙은 유지한다. 0.24.0의 CONG 모델, default/typo dictionary 로딩, 이형태 통합 비활성, 오타 교정 비활성, match=0을 사용한다. 모델은 `kri.kart.nlp.model-directory`(기본 `./nlp_model/v0.24.0`)에 별도로 설치한다. `scripts/setup-kiwi-model.ps1`은 공식 모델 다운로드·SHA-256 검증 후 비어 있는 폴더에만 설치한다. 모델은 Git에서 제외한다. Kiwi 라이브러리/모델이 없거나 분석에 실패하면 해당 문항에 status=503, code=KIWI_NLP_UNAVAILABLE인 error 이벤트를 반환하고 다음 문항을 계속한다.
|
||||
텍스트 분석 요청 옵션: `wordMergeMode`는 같은 글자의 품사별 빈도 합산 방식으로 1=모두 합치기, 2=명사 계열(NNG·NNP·NNB·NR·NP·SL·SH)만 합치기(기본값), 3=합치지 않기이다. 합친 단어는 가장 많이 나온 품사(동률이면 먼저 나온 품사)를 사용한다. `compoundNounMaxTokens`(1~5, 기본값 3, 1이면 끔)는 명사 접두사·접미사를 붙이고, 한 어절 안에서 공백 없이 붙은 NNG·NNP·SL 토큰(한글 명사 1개 이상 포함)을 복합명사 하나로 합친다. 하나라도 NNP면 NNP이고, 상한을 넘는 묶음은 합치지 않는다. 사용자 사전 단어와 치환 결과는 합치지 않는다.
|
||||
|
||||
불용어: REPORT_NLP_WORD에서 WORD_TAG가 `STOP`인 행은 불용어이며 Kiwi 사전에 등록하지 않는다. 치환·복합명사 합치기 후의 최종 단어를 품사와 관계없이 제외하며, 앞뒤·연속 공백과 대소문자를 구분하지 않는다. 전체·프로젝트·문항 중 어느 범위에 있어도 적용한다. 그 밖의 불용어 규칙은 두지 않는다.
|
||||
|
||||
치환: REPORT_NLP_WORD에서 `SOURCE_TEXT`가 있는 행은 `SOURCE_TEXT`를 `WORD_TEXT`/`WORD_TAG`로 바꿔 집계한다(예: SOURCE_TEXT 엘지 → WORD_TEXT LG). `WORD_TEXT`는 모든 행에서 결과에 나오는 단어이며, 치환 행의 `WORD_TEXT`는 점수 0으로만 등록한다(같은 단어의 일반 행이 있으면 그 범위 점수 유지). 우선순위는 문항 > 프로젝트 > 전체이고 사용자 사전보다 우선한다. 띄어 쓴 원표기는 붙여 쓴 형태도 함께 처리하며, 같은 어절의 명사가 이어지면 치환하지 않는다. 짧은 원표기는 긴 단어 안에서도 바뀌므로(엘지전자 → LG + 전자) 필요하면 긴 표기 행을 함께 둔다. `SOURCE_TEXT` 컬럼(NVARCHAR(128), NULL 허용)이 없는 DB에서는 사전 조회가 실패하므로 컬럼 추가 후 배포한다.
|
||||
|
||||
사용자 결정에 따라 최신 공식 KiwiJava·모델 **0.24.0**을 사용한다. 기존 DLL은 실제 실행에서 0.15.2로 확인되었으며 기존 모델은 Java 0.20.4에서도 로딩되지 않았다. 최신 모델 적용에 따른 형태소 결과 변화는 허용하되 Report DB 사전·품사 선택·빈도 집계 규칙은 유지한다. 0.24.0의 CONG 모델과 기본 빌드 옵션(default·typo·multi-word dictionary, 이형태 통합), `Match.allWithNormalizing | oovChrModel`, 오타 교정(basicTypoSetWithContinual, 기준값 2.5)을 사용한다. 같은 사용자 사전 단어는 범위 중 가장 높은 점수로 한 번만 등록한다. 모델은 `kri.kart.nlp.model-directory`(기본 `./nlp_model/v0.24.0`)에 별도로 설치한다. `scripts/setup-kiwi-model.ps1`은 공식 모델 다운로드·SHA-256 검증 후 비어 있는 폴더에만 설치한다. 모델은 Git에서 제외한다. Kiwi 라이브러리/모델이 없거나 분석에 실패하면 해당 문항에 status=503, code=KIWI_NLP_UNAVAILABLE인 error 이벤트를 반환하고 다음 문항을 계속한다.
|
||||
|
||||
Gradle은 Windows에서 win-x64, Linux에서 lnx-x86-64 또는 lnx-aarch64 JAR을 선택한다. Windows에서 Linux 배포물을 만들 때 `./gradlew.bat bootJar -PkiwiPlatform=lnx-x86-64`로 명시한다. 배포 JAR과 JVM 플랫폼이 일치해야 하고 모델도 운영에 별도로 배치한다. Kiwi 및 모델의 라이선스는 공식 저장소의 LGPL-2.1 조건을 확인한다: https://github.com/bab2min/Kiwi/tree/v0.24.0/bindings/java .
|
||||
|
||||
검증: 원본 C# Report.cs를 실행한 합성 비교 기준 25개, 필터/좌표/조회 분리/인증·Swagger/API와 실제 Windows Kiwi 0.24.0 분석을 테스트한다. 네이티브 검증은 `./gradlew.bat test '-PkiwiModelDirectory=nlp_model/v0.24.0'`로 실행한다. 이 속성이 없으면 해당 네이티브 테스트 1개만 생략한다. `build/phase5-openapi.json`은 API 테스트에서 생성된다. 실제 SQL Server 결과, Ubuntu 네이티브 실행·운영 성능은 별도 검수 대상이며 합성 테스트 통과로 운영 동등성을 주장하지 않는다.
|
||||
검증: 원본 C# Report.cs를 실행한 합성 비교 기준 25개, 필터/좌표/조회 분리/인증·Swagger/API와 실제 Windows Kiwi 0.24.0 분석을 테스트한다. 네이티브 검증은 `./gradlew.bat test '-PkiwiModelDirectory=nlp_model/v0.24.0'`로 실행한다. 이 속성이 없으면 실제 모델을 사용하는 네이티브 테스트만 생략한다. `build/phase5-openapi.json`은 API 테스트에서 생성된다. 실제 SQL Server 결과, Ubuntu 네이티브 실행·운영 성능은 별도 검수 대상이며 합성 테스트 통과로 운영 동등성을 주장하지 않는다.
|
||||
|
||||
### 배열 집계와 NDJSON 스트리밍
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ configurations.configureEach {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.kri.common:starter:beta.1.6.9'
|
||||
implementation 'com.kri.common:starter:beta.1.7.1'
|
||||
implementation 'org.apache.poi:poi-ooxml:5.5.1'
|
||||
implementation "kr.pe.bab2min:kiwi-java:${kiwiVersion}:${kiwiPlatform}@jar"
|
||||
|
||||
|
||||
245
docs/statistics-flow.md
Normal file
245
docs/statistics-flow.md
Normal file
@@ -0,0 +1,245 @@
|
||||
# 통계 데이터와 계산 흐름
|
||||
|
||||
현재 구현은 **문항과 응답을 요청당 한 번 준비하고, 요청한 문항별로 응답을 선택해 계산한 뒤 결과를 순서대로 전송**한다.
|
||||
|
||||
- 기준: 2026-10-23 소스 코드. 실제 DB 결과를 비교한 문서는 아니다.
|
||||
- 대상 API: `POST /api/v1/project/{projectType}/{pkey}/statistics/result`
|
||||
- `index`: 집계할 문항. 예: 만족도.
|
||||
- `banner`: 응답을 나누는 기준. 예: 성별, 연령대.
|
||||
- 그림의 `클래스.메서드()`는 실제 구현 이름이다. 같은 클래스의 연속 작업은 한 상자에 묶었다.
|
||||
- 1번은 간략 버전, 2번은 상세 버전이다. 상세 버전은 큰 그림 하나가 길어지지 않도록 단계별로 나눴다.
|
||||
|
||||
## 1. 간략 버전
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
REQ["화면에서 집계 요청<br/>StatisticsController.result()"]
|
||||
QUESTIONS[("KON 또는 KONKIWI<br/>문항 정의")]
|
||||
LOAD["문항과 응답을 한 번 준비<br/>StatisticsService.prepare()"]
|
||||
RESPONSES[("KON 또는 KONKIWI<br/>원래 응답 + 저장된 파생 응답<br/>필요한 경우 KIWI 프로필 응답")]
|
||||
FILTER["응답 JSON을 Map으로 변환하고 필터 적용<br/>StatisticsDataService.normalize()<br/>StatisticsFilterService.compile()로 만든 조건 사용"]
|
||||
CALC["요청한 문항별로 대상 응답 선택<br/>StatisticsService.calculate()"]
|
||||
TYPE{"주관식 문자 문항인가?<br/>StatisticsService.isOpenText()"}
|
||||
TABLE["전체·배너별 N / % / 통계량 계산<br/>StatisticsAggregationService.aggregate()"]
|
||||
LAYOUT["표 머리글·병합·전치 적용<br/>StatisticsTableService.table()"]
|
||||
NLP["형태소 분석과 단어 빈도 계산<br/>StatisticsTextService.analyze()"]
|
||||
DICT[("Report DB: NLP 사전·품사 설정<br/>로컬 파일: Kiwi 모델")]
|
||||
OUT["문항별 result 또는 error 전송<br/>StatisticsService.stream()<br/>StatisticsStreamService.send()"]
|
||||
END["마지막 complete 전송<br/>전체 수·성공 수·실패 수"]
|
||||
|
||||
REQ --> LOAD
|
||||
QUESTIONS --> LOAD
|
||||
RESPONSES --> LOAD
|
||||
LOAD --> FILTER --> CALC --> TYPE
|
||||
TYPE -->|아니오| TABLE --> LAYOUT --> OUT
|
||||
TYPE -->|예| NLP --> OUT
|
||||
DICT --> NLP
|
||||
OUT -->|다음 문항| CALC
|
||||
OUT -->|모든 문항 처리 후| END
|
||||
```
|
||||
|
||||
예를 들어 **“30대 응답자 중 성별에 따른 만족도”**를 요청하면, 나이로 응답자를 걸러 낸 다음 만족도 응답을 성별로 나눠 N·%·평균 등을 계산한다.
|
||||
|
||||
## 2. 상세 버전
|
||||
|
||||
### 2-1. 공통 준비: 어디서 데이터를 가져오는가
|
||||
|
||||
이 단계는 스트림을 반환하기 전에 실행한다. 문항 목록과 합집합으로 선택한 응답 데이터는 요청당 한 번 조회한다. 다만 텍스트 분석용 사전·품사 설정은 이후 텍스트 문항마다 별도로 조회한다.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
API["StatisticsController.result()<br/>StatisticsBatchRequestDto.requests()<br/>indexes를 개별 요청 목록으로 변환"]
|
||||
PREP["StatisticsService.prepare()<br/>validate(): 모드·index·날짜 확인"]
|
||||
QLOAD["StatisticsService.loadQuestions()<br/>QuestionRepository.list()<br/>QuestionMapper.list()"]
|
||||
SESSION["Repository가 SurveySessionProvider.mapper() 호출<br/>forProject(): 0=KON / 1=KONKIWI"]
|
||||
QDB[("선택한 설문 DB<br/>QUESTION + DERIVED_VARIABLE<br/>KIWI이며 role=1001이면 프로필 문항 포함")]
|
||||
ORGANIZE["QuestionService.organize()<br/>expandOpen() / expandRank() / expandAttributes()<br/>입력칸·순위·속성별 문항으로 확장"]
|
||||
VALID["StatisticsService.validateDimensions()<br/>StatisticsDimensionService.resolve()<br/>모든 index와 banner의 문항 정의 확인"]
|
||||
COMPILE["StatisticsFilterService.compile()<br/>필터 구조를 응답자 판정 함수로 변환"]
|
||||
ROOTS["StatisticsService.loadResponses()<br/>storageRoots() / toStorageRoot()<br/>모든 요청의 index·banner 루트 합집합 생성"]
|
||||
RAW[("선택한 설문 DB<br/>DATA.DATJSON: 원래 응답<br/>DERIVED_DATA.DATJSON: 저장된 파생 응답")]
|
||||
PROFILE[("KIWI_SURVEY.dbo.V_PROFILE<br/>P_DATJSON: 프로필 응답")]
|
||||
QUERY["StatisticsRepository.data()<br/>StatisticsMapper.data()<br/>완료·조사 유형·날짜 조건으로 조회하고 JSON 결합"]
|
||||
DAT["StatisticsDataDto.dat<br/>집계용: 선택한 루트가 들어 있는 저장 그룹"]
|
||||
FDAT["StatisticsDataDto.filterDat<br/>필터용: 전체 응답 그룹<br/>필터가 없으면 null"]
|
||||
NORMAL["StatisticsDataService.normalize() → flatten()<br/>JSON 키를 대문자로 통일하고 Map으로 변환<br/>SurveyResponseDto 생성"]
|
||||
APPLY["StatisticsService.loadResponses()의 stream().filter(filter)<br/>판정 함수는 response.filterValues() 사용<br/>조건을 통과한 응답만 남김"]
|
||||
BATCH["StatisticsBatchDto 생성<br/>project / requests / questions / responses"]
|
||||
AUDIT["StatisticsService.prepare() → LogService.writeSiteLog()<br/>Get Report Data를 배치당 한 번 기록 시도<br/>그 후 Controller가 스트림 반환"]
|
||||
|
||||
API --> PREP --> QLOAD
|
||||
SESSION -. "문항 조회와 응답 조회에 각각 적용" .-> QLOAD
|
||||
SESSION -.-> QUERY
|
||||
QDB --> QLOAD --> ORGANIZE --> VALID --> COMPILE --> ROOTS
|
||||
ROOTS --> QUERY
|
||||
RAW --> QUERY
|
||||
PROFILE -. "needsProfileResponses()가 참조 여부 확인" .-> QUERY
|
||||
QUERY --> DAT --> NORMAL
|
||||
QUERY --> FDAT --> NORMAL
|
||||
COMPILE -. "판정 함수" .-> APPLY
|
||||
NORMAL --> APPLY --> BATCH --> AUDIT
|
||||
ORGANIZE -. "questions" .-> BATCH
|
||||
```
|
||||
|
||||
**SQL에서 거르는 조건** — [StatisticsMapper.xml](../src/main/resources/mybatis/mapper/StatisticsMapper.xml)의 `data`:
|
||||
|
||||
| 조건 | 실제 처리 |
|
||||
|---|---|
|
||||
| 프로젝트 | `DATA.PKEY = pkey` |
|
||||
| 완료 상태 | 모든 dataScope에서 `Status = 10` |
|
||||
| `ACTUAL` | `SURVEY_TYPE <> 'TEST'` |
|
||||
| `TEST` | `SURVEY_TYPE = 'TEST'` |
|
||||
| `ALL` | 조사 유형 제한 없음. 완료 조건은 유지 |
|
||||
| 날짜 | `FN_LAST_TIME(survey_date)`를 날짜로 변환해 시작일·종료일 포함 비교. 시작일만 있으면 그 하루 |
|
||||
| 파생 응답 | `DERIVED_DATA`를 `PKEY + IDKEY`로 LEFT JOIN. 이 요청에서 파생값을 재계산하지 않음 |
|
||||
| 프로필 응답 | KIWI이며 index·banner·filter에서 PF/PS 문항을 참조하면 `V_PROFILE` JOIN |
|
||||
|
||||
**집계용 데이터와 필터용 데이터를 분리하는 이유:** 만족도만 집계해도 나이로 필터링할 수 있어야 하기 때문이다.
|
||||
|
||||
| 데이터 | 사용하는 곳 | 의미 |
|
||||
|---|---|---|
|
||||
| `dat` → `SurveyResponseDto.values()` | 문항별 응답 선택, N·%·통계량, 텍스트 분석 | 선택한 저장 그룹의 응답. 요청한 키만 잘라 내는 방식은 아니므로 같은 그룹의 다른 키도 포함될 수 있음 |
|
||||
| `filterDat` → `SurveyResponseDto.filterValues()` | `StatisticsFilterService.compileCondition()`이 만든 판정 함수 | 전체 응답을 보고 필터 판단. 필터가 없으면 normalize 단계에서 `values`를 함께 사용 |
|
||||
|
||||
루트는 저장된 응답 그룹을 찾는 기준이다. `toStorageRoot()`는 대문자로 바꾸고 `#A`를 제거한 뒤 첫 `_` 앞부분을 사용한다. 예를 들어 `q1_2#a`는 `Q1`이 된다. TABULATION 모드에서는 index 대신 `INDEX` 루트를 사용한다.
|
||||
|
||||
### 2-2. 문항별 계산: 어떤 응답으로 N·%를 만드는가
|
||||
|
||||
준비한 배치를 `StatisticsStreamService.stream()`이 비동기 작업에 넘긴다. `writeEvents()` → `StatisticsService.stream()` 순서로 들어가며, 아래 계산을 indexes의 입력 순서대로 실행한다. 같은 index가 반복되어도 해당 위치마다 처리한다.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
BATCH["공통 준비 결과<br/>StatisticsBatchDto"]
|
||||
LOOP["StatisticsService.stream()<br/>이번 위치의 요청 선택 → calculate()"]
|
||||
PICK["StatisticsService.withinStorageRoots()<br/>이번 index·banner의 루트에 해당하는 키가<br/>하나라도 있는 응답자만 선택"]
|
||||
DIM["StatisticsDimensionService.resolve()<br/>문항 ID → 기본 키·보기·속성·순위 범위<br/>숫자 문항 보기는 실제 응답에서 구성"]
|
||||
TYPE{"StatisticsService.isOpenText()<br/>text 문항이며 #A가 아닌가?"}
|
||||
TEXT["2-3의 텍스트 분석으로 이동<br/>StatisticsService.textAnalysis()"]
|
||||
AGG["StatisticsAggregationService.aggregate()<br/>columns()로 열별 응답 목록 생성"]
|
||||
TOTAL["StatisticsSelectionService.total() / cases()<br/>전체 응답 목록과 보기별 응답 목록"]
|
||||
BANNER["StatisticsAggregationService.addBanner()<br/>StatisticsSelectionService.bannerTotal() / bannerCases()<br/>배너 값별로 목록 분리, 중첩 배너는 재귀 처리"]
|
||||
MODE{"집계 모드"}
|
||||
NORMAL["StatisticsAggregationService<br/>totalRow() / addChoiceRows()<br/>countCell() / percentBase()<br/>N=목록 크기, %=N÷분모×100"]
|
||||
SUMMARY["StatisticsAggregationService.addSummaryRows()<br/>숫자: 평균·중앙값·표준편차 등<br/>척도: Top/Mid/Bottom·NPS 또는 평균<br/>요청한 사용자 값 그룹 추가"]
|
||||
CROSS["StatisticsAggregationService.bannerCrossTable()<br/>crossCount() / overlapCount(): 배너 간 겹침<br/>crossBase() / groupBase(): 분모 결정"]
|
||||
TABLE["StatisticsTableService.table()<br/>headers(): 머리글과 병합 정보 생성<br/>필요하면 transpose(): 행·열 교환<br/>StatisticsResponseDto, type=TABLE"]
|
||||
EVENT["StatisticsService.resultEvent() / errorEvent()<br/>문항 계산 오류는 해당 위치의 error로 변환"]
|
||||
SEND["StatisticsStreamService.send()<br/>JSON 한 줄 + 줄바꿈 전송"]
|
||||
DONE["StatisticsService.completeEvent()<br/>total / succeeded / failed"]
|
||||
|
||||
BATCH --> LOOP --> PICK --> DIM --> TYPE
|
||||
TYPE -->|예| TEXT --> EVENT
|
||||
TYPE -->|아니오| AGG --> TOTAL --> BANNER --> MODE
|
||||
MODE -->|STANDARD 또는 TABULATION_0| NORMAL --> SUMMARY --> TABLE
|
||||
MODE -->|TABULATION_1| CROSS --> TABLE
|
||||
TABLE --> EVENT --> SEND
|
||||
SEND -->|다음 위치| LOOP
|
||||
SEND -->|모두 처리함| DONE
|
||||
```
|
||||
|
||||
`withinStorageRoots()`는 **응답자를 고르는 단계**다. 응답자의 Map에서 다른 키를 삭제하는 단계는 아니다. 전체 배치를 한 번에 조회한 영향으로 특정 문항의 대상자가 늘어나지 않도록 다시 제한한다.
|
||||
|
||||
계산 도중 연결이 끊기거나 취소되면 반복과 전송을 중단한다. 공통 준비 단계의 오류는 스트림 시작 전 HTTP 오류이며, 문항별 계산 오류와 구분된다.
|
||||
|
||||
**N과 분모가 만들어지는 위치:**
|
||||
|
||||
| 항목 | 실제 클래스·메서드 | 계산 의미 |
|
||||
|---|---|---|
|
||||
| 전체 사례수 | `StatisticsSelectionService.total()` | 해당 문항에 응답한 목록 구성 |
|
||||
| 보기별 N | `StatisticsSelectionService.cases()` | 해당 보기를 선택한 목록의 크기 |
|
||||
| 배너별 사례수와 N | `bannerTotal()` / `bannerCases()` | 상위 단계 목록을 배너의 보기 조건으로 다시 선택 |
|
||||
| 일반 비율 | `StatisticsAggregationService.countCell()` | 분모가 0이면 0%, 아니면 N ÷ 분모 × 100 |
|
||||
| 일반 표의 Total 비율 | `totalRow()` | 해당 열의 보기별 비율 합. 복수응답에서는 100%를 넘을 수 있음 |
|
||||
| 평균 | `mean()` | 보기 값 × 사례수의 합 ÷ 결측 사례를 뺀 분모. 역척도 처리 포함 |
|
||||
| 나머지 숫자 통계 | `numericValues()` → `calculate()` | 응답 숫자 목록으로 Median·SD·Max·Min·Mode·선택적 Sum 계산 |
|
||||
| 척도 그룹과 NPS | `addScaleGroups()` / `addGroup()` / `addNpsRow()` | 그룹에 해당하는 보기 사례 합산. NPS는 Promoters % − Detractors % |
|
||||
| 반올림·표시 문자열 | `StatisticsArithmetic.round()` / `display()` | 계산값과 화면 표시 문자열 구성 |
|
||||
|
||||
순위·속성 응답 선택은 `StatisticsSelectionService.select()`가 여러 슬롯을 순회해 목록에 추가한다. **같은 응답자가 여러 슬롯에 들어가면 여러 번 집계될 수 있으므로 N이 항상 중복 없는 사람 수인 것은 아니다.** 속성 전체 문항의 요약은 `columns()`에서 요청 배너 대신 해당 문항의 `#A` 배너를 사용한다.
|
||||
|
||||
**모드별 차이:**
|
||||
|
||||
| 모드 | 표 구성 | 분모 결정 메서드와 규칙 |
|
||||
|---|---|---|
|
||||
| `STANDARD` | 집계 문항의 보기를 행으로, 배너를 열로 구성 | `percentBase()`: 해당 열의 전체 응답 목록 크기 |
|
||||
| `TABULATION_0` | 빈 index로 전체 표본을 놓고 배너 구성비 계산 | `percentBase()`: Total 열은 자체 사례수, 배너 열은 형제 열 사례수의 합. 형제가 없으면 Total 사례수. 형제 판정은 실제 열 ID의 마지막 한 자리 숫자 규칙을 유지 |
|
||||
| `TABULATION_1` | 배너를 행과 열 양쪽에 놓고 교차 계산 | `crossBase()`: Total 열은 행의 형제 열들을 합친 고유 IDKEY 수, 나머지 열은 해당 열의 사례수 |
|
||||
|
||||
`TABULATION_1`의 `overlapCount()`는 같은 IDKEY의 좌우 목록 쌍을 센다. 모든 교차 셀이 고유 응답자 교집합 크기와 같다고 가정하면 안 된다. 빈 분모의 일반 빈도 셀은 0%이며, 정의되지 않는 그룹 비율·통계량은 null과 `-` 표시를 사용한다.
|
||||
|
||||
### 2-3. 텍스트 분석: 어떤 사전으로 단어를 세는가
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
INPUT["StatisticsService.textAnalysis()<br/>StatisticsTextService.analyze()"]
|
||||
TEXT["StatisticsTextService.answerTexts()<br/>해당 QID와 QID_ 하위 키의 문자열 수집<br/>HTML 문자 복원"]
|
||||
DICT[("Report DB<br/>REPORT_NLP_WORD (STOP 행 = 불용어, SOURCE_TEXT 행 = 치환)<br/>REPORT_NLP_TAG")]
|
||||
REPO["NlpRepository.words() / tags()<br/>NlpMapper.words() / tags()<br/>kartSqlSessionTemplate 사용"]
|
||||
MODEL[("로컬 Kiwi 모델 파일<br/>kri.kart.nlp.model-directory")]
|
||||
TOKEN["KiwiNlpService.tokenize()<br/>응답 문자열 + 사용자 사전 + 치환 → 형태소 목록<br/>오타 교정·구어체 정규화<br/>compoundNounMaxTokens에 따라 복합명사 합치기"]
|
||||
FILTER["StatisticsTextService.analyze() / isCounted()<br/>STOP 불용어 제외<br/>선택 품사 중 명사 또는 2글자 이상<br/>SL은 선택 품사·길이와 관계없이 포함"]
|
||||
COUNT["StatisticsTextService.analyze() / merge()<br/>단어+품사별 빈도 합산<br/>wordMergeMode에 따라 같은 글자 합산<br/>빈도 내림차순, 동률은 첫 등장 순서<br/>상위 100개 선택"]
|
||||
OUT["StatisticsResponseDto, type=TEXT_ANALYSIS<br/>words: 단어·품사·빈도<br/>문항별 result 이벤트로 반환"]
|
||||
|
||||
INPUT --> TEXT --> TOKEN
|
||||
DICT --> REPO
|
||||
REPO -->|사전 단어·치환| TOKEN
|
||||
MODEL --> TOKEN
|
||||
TOKEN --> FILTER --> COUNT --> OUT
|
||||
REPO -->|선택 품사·불용어| FILTER
|
||||
```
|
||||
|
||||
사전은 전체 공통(`PKEY=ALL`), 프로젝트 공통(`QID=ALL`), 해당 문항 범위를 합쳐 읽는다. 사용자 단어의 점수는 각각 10·50·100이며, 같은 단어는 가장 높은 점수로 한 번만 등록한다. 이 점수는 형태소 분석 사전에 사용하는 값이며 최종 빈도에 곱하는 통계 가중치가 아니다. 모델이나 native 실행 환경이 없으면 오류를 반환한다.
|
||||
|
||||
텍스트 분석 처리 순서는 다음과 같다.
|
||||
|
||||
1. **치환**: `REPORT_NLP_WORD`에서 `SOURCE_TEXT`가 있는 행은 `SOURCE_TEXT`를 `WORD_TEXT`/`WORD_TAG`로 바꾼다. 우선순위는 문항 > 프로젝트 > 전체이고, 사용자 사전보다 우선한다.
|
||||
2. **복합명사 합치기**: `compoundNounMaxTokens`(기본 3)에 따라 한 어절 안에서 붙은 명사를 합친다. 사용자 사전 단어와 치환 결과는 합치지 않는다.
|
||||
3. **불용어 제외**: `REPORT_NLP_WORD`에서 WORD_TAG가 `STOP`인 단어를 품사와 관계없이 제외한다. 대소문자와 공백 차이는 무시한다.
|
||||
4. **품사 합산**: `wordMergeMode`(기본 2=명사 계열)에 따라 같은 글자의 품사별 빈도를 합친다.
|
||||
|
||||
기존 `analyze(project, qid, responses)`와 `tokenize(texts, dictionary)` 오버로드는 치환·불용어·합치기를 적용하지 않는 이전 동작을 유지하며, 통계 API만 새 옵션을 사용한다.
|
||||
|
||||
### 2-4. 쿼터는 어디서 갈라지는가
|
||||
|
||||
일반 통계 스트림과 별도인 `POST /api/v1/quota/{projectType}/{pkey}/{quotaOrder}/result`는 저장된 설정으로 집계한 뒤 목표 수와 결합한다. 단일 JSON 응답이다.
|
||||
|
||||
| 순서 | 실제 클래스·메서드 | 데이터 처리 |
|
||||
|---|---|---|
|
||||
| 1 | `QuotaService.result()` → `QuotaRepository.quotaSet()` → `QuotaMapper.quotaSet()` | 선택한 설문 DB의 `QUOTASET`에서 설정 조회 |
|
||||
| 2 | `QuotaService.result()` → `LogService.writeSiteLog()` | 설정을 찾은 뒤 `QUOTA VIEW` 기록 시도 |
|
||||
| 3 | `QuotaService.result()` / `LegacyFilterService.parse()` | 첫 ROW를 index로, COL을 배너로 구성. 저장된 FILTER는 AST로 해석. SQL로 실행하지 않음 |
|
||||
| 4 | `StatisticsService.prepareQuota()` | 2-1의 공통 준비 재사용. 빈 STANDARD index 허용. `Get Report Data`는 기록하지 않음 |
|
||||
| 5 | `StatisticsAggregationService.aggregate()` | 사례수 표 계산. 소계 없이 집계하며 일반 통계의 `stream()` / `calculate()`를 경유하지 않음 |
|
||||
| 6 | `QuotaRepository.quotaEntries()` → `QuotaMapper.quotaEntries()` | 같은 설문 DB의 `QUOTA`에서 목표 수와 설정 조회 |
|
||||
| 7 | `QuotaComputationService.compute()` | 계산된 사례수와 `ORI_CNT` 목표 수 결합. 0 목표 행 처리·Total 재계산·달성률 및 표시 상태 구성 |
|
||||
|
||||
## 3. 소스 바로가기
|
||||
|
||||
링크는 이 문서 기준 상대 경로다. private 메서드도 흐름 설명에 포함했다.
|
||||
|
||||
| 소스 | 먼저 볼 메서드 |
|
||||
|---|---|
|
||||
| [StatisticsController.java](../src/main/java/com/kri/kart/server/controller/StatisticsController.java) | `result()` |
|
||||
| [StatisticsBatchRequestDto.java](../src/main/java/com/kri/kart/server/dto/statistics/StatisticsBatchRequestDto.java) | `requests()` |
|
||||
| [StatisticsService.java](../src/main/java/com/kri/kart/server/service/StatisticsService.java) | `prepare()` → `loadQuestions()` / `loadResponses()`, `stream()` → `calculate()` |
|
||||
| [SurveySessionProvider.java](../src/main/java/com/kri/kart/server/persistence/SurveySessionProvider.java) | `mapper()` / `forProject()` |
|
||||
| [QuestionService.java](../src/main/java/com/kri/kart/server/service/QuestionService.java) | `organize()` / `expandOpen()` / `expandRank()` / `expandAttributes()` |
|
||||
| [QuestionRepository.java](../src/main/java/com/kri/kart/server/persistence/repository/QuestionRepository.java) / [QuestionMapper.xml](../src/main/resources/mybatis/mapper/QuestionMapper.xml) | `list()` / statement `list` |
|
||||
| [StatisticsRepository.java](../src/main/java/com/kri/kart/server/persistence/repository/StatisticsRepository.java) / [StatisticsMapper.xml](../src/main/resources/mybatis/mapper/StatisticsMapper.xml) | `data()` / statement `data` |
|
||||
| [StatisticsDataService.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsDataService.java) | `normalize()` / `flatten()` |
|
||||
| [StatisticsFilterService.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsFilterService.java) | `compile()` / `compileGroup()` / `compileCondition()` |
|
||||
| [StatisticsDimensionService.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsDimensionService.java) | `resolve()` / `choices()` / `answeredChoices()` |
|
||||
| [StatisticsSelectionService.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsSelectionService.java) | `total()` / `cases()` / `bannerTotal()` / `bannerCases()` / `select()` |
|
||||
| [StatisticsAggregationService.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsAggregationService.java) | `aggregate()` / `columns()` / `addBanner()` / `percentBase()` / `bannerCrossTable()` |
|
||||
| [StatisticsArithmetic.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsArithmetic.java) | `round()` / `display()` |
|
||||
| [StatisticsTableService.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsTableService.java) | `table()` / `headers()` / `transpose()` |
|
||||
| [StatisticsTextService.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsTextService.java) | `analyze()` / `answerTexts()` / `isCounted()` |
|
||||
| [KiwiNlpService.java](../src/main/java/com/kri/kart/server/service/statistics/KiwiNlpService.java) | `tokenize()` |
|
||||
| [NlpRepository.java](../src/main/java/com/kri/kart/server/persistence/repository/NlpRepository.java) / [NlpMapper.xml](../src/main/resources/mybatis/mapper/NlpMapper.xml) | `words()` / `tags()` |
|
||||
| [StatisticsStreamService.java](../src/main/java/com/kri/kart/server/service/statistics/StatisticsStreamService.java) | `stream()` / `writeEvents()` / `send()` |
|
||||
| [QuotaService.java](../src/main/java/com/kri/kart/server/service/QuotaService.java) | `result()` |
|
||||
| [QuotaRepository.java](../src/main/java/com/kri/kart/server/persistence/repository/QuotaRepository.java) / [QuotaMapper.xml](../src/main/resources/mybatis/mapper/QuotaMapper.xml) | `quotaSet()` / `quotaEntries()` |
|
||||
| [QuotaComputationService.java](../src/main/java/com/kri/kart/server/service/quota/QuotaComputationService.java) | `compute()` |
|
||||
|
||||
Mermaid 지원 Markdown 미리보기에서 다이어그램을 볼 수 있다. 문서의 화살표는 주요 처리·데이터 전달 관계를 나타내며 모든 화살표가 직접적인 Java 메서드 호출을 의미하지는 않는다.
|
||||
@@ -3,3 +3,6 @@
|
||||
org.gradle.jvmargs=-Xmx2g
|
||||
org.gradle.parallel=true
|
||||
org.gradle.caching=true
|
||||
|
||||
# Enabled parallel sync for Gradle 9.4+
|
||||
org.gradle.tooling.parallel=true
|
||||
|
||||
@@ -100,6 +100,8 @@ public final class KartConstant {
|
||||
// StatisticsTextService
|
||||
public static final int TOP_WORD_LIMIT = 100;
|
||||
public static final String FOREIGN_WORD_TAG = "SL";
|
||||
// 불용어: REPORT_NLP_WORD rows with this WORD_TAG are excluded from word counts.
|
||||
public static final String STOPWORD_TAG = "STOP";
|
||||
|
||||
// StatisticsController
|
||||
public static final String CROSSTAB_PAGE = "/Report/Crosstab";
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.kri.kart.server.common.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
import com.kri.common.feature.enums.CodeEnum;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Getter(onMethod_ = @JsonValue)
|
||||
@RequiredArgsConstructor
|
||||
@Schema(description = "같은 단어의 품사별 빈도 합산: 1=모두 합치기, 2=명사 계열만 합치기, 3=합치지 않기")
|
||||
public enum WordMergeMode implements CodeEnum<Integer> {
|
||||
ALL(1),
|
||||
NOUN(2),
|
||||
NONE(3);
|
||||
|
||||
private final Integer code;
|
||||
|
||||
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
|
||||
public static WordMergeMode fromCode(Integer code) {
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
for (WordMergeMode s : values()) {
|
||||
if (s.code.equals(code)) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unknown WordMergeMode code: " + code);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.mybatis.spring.SqlSessionFactoryBean;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -19,6 +20,13 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
@EnableConfigurationProperties(KartDatabaseProperties.class)
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class KartMyBatisConfig {
|
||||
private final long leakDetectionThreshold;
|
||||
|
||||
public KartMyBatisConfig(
|
||||
@Value("${spring.datasource.hikari.leak-detection-threshold:0}") long leakDetectionThreshold) {
|
||||
this.leakDetectionThreshold = leakDetectionThreshold;
|
||||
}
|
||||
|
||||
@Bean(destroyMethod = "close")
|
||||
public HikariDataSource konDataSource(KartDatabaseProperties properties, Validator validator) {
|
||||
return dataSource("kon", properties.getKon(), validator);
|
||||
@@ -53,6 +61,7 @@ public class KartMyBatisConfig {
|
||||
dataSource.setMaximumPoolSize(source.getMaximumPoolSize());
|
||||
dataSource.setMinimumIdle(0);
|
||||
dataSource.setConnectionTimeout(10000);
|
||||
dataSource.setLeakDetectionThreshold(leakDetectionThreshold);
|
||||
dataSource.setInitializationFailTimeout(-1);
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContextProvider;
|
||||
import com.kri.kart.server.interceptor.ProjectAccessInterceptor;
|
||||
import com.kri.kart.server.service.ProjectService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class ProjectAccessConfig implements WebMvcConfigurer {
|
||||
private final RequestUserContextProvider requestUserContextProvider;
|
||||
private final ProjectService projectService;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new ProjectAccessInterceptor(requestUserContextProvider, projectService))
|
||||
.addPathPatterns("/api/v1/**")
|
||||
.order(1);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContextProvider;
|
||||
import com.kri.kart.server.interceptor.ExternalAccessInterceptor;
|
||||
import com.kri.kart.server.service.ShareLinkService;
|
||||
import com.kri.kart.server.service.share.ExternalAccessInterceptor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
@@ -14,10 +15,13 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class ShareLinkConfig implements WebMvcConfigurer {
|
||||
private final RequestUserContextProvider requestUserContextProvider;
|
||||
private final ShareLinkService shareLinkService;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new ExternalAccessInterceptor(shareLinkService)).addPathPatterns("/**");
|
||||
registry.addInterceptor(new ExternalAccessInterceptor(requestUserContextProvider, shareLinkService))
|
||||
.addPathPatterns("/**")
|
||||
.order(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.dto.auth.LoginRequestDto;
|
||||
import com.kri.kart.server.dto.auth.LoginResponseDto;
|
||||
@@ -7,6 +8,10 @@ import com.kri.kart.server.service.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.CurrentSecurityContext;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -19,6 +24,12 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class AuthController {
|
||||
private final AuthService authService;
|
||||
|
||||
@GetMapping("/my-info")
|
||||
public ResponseEntity<JwtUserClaimsDto> myInfo(
|
||||
@CurrentSecurityContext(expression = "authentication.details") JwtUserClaimsDto user) {
|
||||
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(user);
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public LoginResponseDto login(
|
||||
@Valid @RequestBody LoginRequestDto request, RequestUserContext ctx) {
|
||||
|
||||
@@ -14,6 +14,9 @@ import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
@@ -93,18 +96,33 @@ public class ExportController {
|
||||
@PostMapping(
|
||||
value = "/project/{projectType}/{pkey}/export/data",
|
||||
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
|
||||
public ResponseEntity<byte[]> data(
|
||||
public void data(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @RequestBody RawDataExportRequestDto request,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return download(
|
||||
exportService.data(new ProjectRefDto(projectType, pkey), ctx.getUserRole(), request));
|
||||
@Parameter(hidden = true) RequestUserContext ctx, HttpServletResponse response) throws IOException {
|
||||
ProjectRefDto project = new ProjectRefDto(projectType, pkey);
|
||||
try (var file = exportService.prepareData(project, ctx.getUserRole(), request)) {
|
||||
String fileName = FileUtil.extractFileNameFromPath(file.fileName())
|
||||
.replaceAll("[\\p{Cntrl}\\\\/:*?\"<>|]", "_");
|
||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
|
||||
ContentDisposition.attachment().filename(fileName, StandardCharsets.UTF_8).build().toString());
|
||||
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store");
|
||||
response.setContentLengthLong(Files.size(file.path()));
|
||||
Files.copy(file.path(), response.getOutputStream());
|
||||
} catch (IOException | RuntimeException error) {
|
||||
// Before any file bytes are committed, preserve the normal JSON error response.
|
||||
if (!response.isCommitted()) {
|
||||
response.reset();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private ResponseEntity<byte[]> download(ExportFileDto file) {
|
||||
String fileName =
|
||||
FileUtil.extractFileNameFromPath(file.getFileName())
|
||||
FileUtil.extractFileNameFromPath(file.fileName())
|
||||
.replaceAll("[\\p{Cntrl}\\\\/:*?\"<>|]", "_");
|
||||
String disposition =
|
||||
ContentDisposition.attachment()
|
||||
@@ -115,6 +133,6 @@ public class ExportController {
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, disposition)
|
||||
.header(HttpHeaders.CACHE_CONTROL, "no-store")
|
||||
.body(file.getContent());
|
||||
.body(file.content());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.common.consts.KartConstant;
|
||||
import com.kri.kart.server.dto.log.VisitLogRequestDto;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.share.ShareLinkDto;
|
||||
import com.kri.kart.server.service.LogService;
|
||||
import com.kri.kart.server.service.ProjectService;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
@@ -23,6 +25,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class LogController {
|
||||
private final LogService logService;
|
||||
private final ProjectService projectService;
|
||||
|
||||
@PostMapping(value = "/visit", produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
public String visit(
|
||||
@@ -32,12 +35,18 @@ public class LogController {
|
||||
ShareLinkDto link =
|
||||
(ShareLinkDto) servletRequest.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE);
|
||||
if (link != null
|
||||
&& (link.getProjectType() != request.getProjectType()
|
||||
|| !link.getPkey().equals(request.getPkey()))) {
|
||||
&& (link.projectType() != request.projectType()
|
||||
|| !link.pkey().equals(request.pkey()))) {
|
||||
throw BusinessException.forbidden("EXTERNAL_SCOPE_DENIED", "공유 프로젝트의 방문 로그만 기록할 수 있습니다.");
|
||||
}
|
||||
if (link == null && (request.projectType() != null || request.pkey() != null)) {
|
||||
if (request.projectType() == null || request.pkey() == null) {
|
||||
throw BusinessException.badRequest("projectType과 pkey를 함께 입력해 주세요.");
|
||||
}
|
||||
projectService.requireAccess(new ProjectRefDto(request.projectType(), request.pkey()), ctx);
|
||||
}
|
||||
logService.writeVisitLog(
|
||||
request.getProjectType(), request.getPkey(), request.getLogContent(), ctx);
|
||||
request.projectType(), request.pkey(), request.logContent(), ctx);
|
||||
return "PASS";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.kri.kart.server.dto.project.ProgressDayDto;
|
||||
import com.kri.kart.server.dto.project.ProgressScreenDto;
|
||||
import com.kri.kart.server.dto.project.ProgressSearchDto;
|
||||
import com.kri.kart.server.dto.project.ProgressTypeDto;
|
||||
import com.kri.kart.server.dto.project.ProjectAccessDto;
|
||||
import com.kri.kart.server.dto.project.ProjectLinkSearchDto;
|
||||
import com.kri.kart.server.dto.project.ProjectListDto;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
@@ -15,6 +16,7 @@ import com.kri.kart.server.dto.project.ProjectSummaryDto;
|
||||
import com.kri.kart.server.service.CustomProgressService;
|
||||
import com.kri.kart.server.service.ProgressService;
|
||||
import com.kri.kart.server.service.ProjectService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -35,6 +37,14 @@ public class ProjectController {
|
||||
private final ProgressService progressService;
|
||||
private final CustomProgressService customProgressService;
|
||||
|
||||
@GetMapping("/{projectType}/{pkey}/access")
|
||||
@Operation(summary = "프로젝트 접근 권한 확인", description = "접근 가능하면 allowed=true, 권한이 없으면 403을 반환합니다.")
|
||||
public ProjectAccessDto access(
|
||||
@PathVariable ProjectType projectType, @PathVariable String pkey, RequestUserContext ctx) {
|
||||
// The project interceptor applies the same authorization as every project-scoped route.
|
||||
return new ProjectAccessDto(true);
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
public List<ProjectListDto> list(
|
||||
@Valid @ParameterObject @ModelAttribute ProjectLinkSearchDto search, RequestUserContext ctx) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.share.ShareLinkDto;
|
||||
import com.kri.kart.server.dto.share.ShareLinkRequestDto;
|
||||
import com.kri.kart.server.service.ProjectService;
|
||||
import com.kri.kart.server.service.ShareLinkService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import jakarta.validation.Valid;
|
||||
@@ -21,6 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class ShareLinkController {
|
||||
private final ShareLinkService shareLinkService;
|
||||
private final ProjectService projectService;
|
||||
|
||||
@PostMapping("/api/v1/project/{projectType}/{pkey}/share")
|
||||
@Operation(summary = "공유 링크 발급 또는 재사용")
|
||||
@@ -34,7 +36,9 @@ public class ShareLinkController {
|
||||
|
||||
@GetMapping("/api/v1/share/{urlKey}")
|
||||
@Operation(summary = "공유 링크 정보 조회", description = "내부 인증 필요. 랜딩 횟수를 증가시키지 않는다.")
|
||||
public ShareLinkDto lookup(@PathVariable String urlKey) {
|
||||
return shareLinkService.lookup(urlKey);
|
||||
public ShareLinkDto lookup(@PathVariable String urlKey, RequestUserContext ctx) {
|
||||
ShareLinkDto link = shareLinkService.lookup(urlKey);
|
||||
projectService.requireAccess(new ProjectRefDto(link.projectType(), link.pkey()), ctx);
|
||||
return link;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ public class StatisticsController {
|
||||
ShareLinkDto link =
|
||||
(ShareLinkDto) servletRequest.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE);
|
||||
return link != null
|
||||
&& link.isPageOnly()
|
||||
&& URI.create(link.getRealUrl()).getPath().equals(KartConstant.CROSSTAB_PAGE);
|
||||
&& link.pageOnly()
|
||||
&& URI.create(link.realUrl()).getPath().equals(KartConstant.CROSSTAB_PAGE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,11 @@ package com.kri.kart.server.dto.auth;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Schema(description = "로그인 요청")
|
||||
public class LoginRequestDto {
|
||||
@NotBlank private String userId;
|
||||
public record LoginRequestDto(
|
||||
@NotBlank String userId,
|
||||
|
||||
@NotBlank
|
||||
@Schema(accessMode = Schema.AccessMode.WRITE_ONLY)
|
||||
private String userPw;
|
||||
}
|
||||
String userPw) {}
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
package com.kri.kart.server.dto.auth;
|
||||
|
||||
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class LoginResponseDto {
|
||||
private final String accessToken;
|
||||
private final JwtUserClaimsDto user;
|
||||
private final String memberRedirect;
|
||||
}
|
||||
public record LoginResponseDto(
|
||||
String accessToken,
|
||||
JwtUserClaimsDto user,
|
||||
String memberRedirect) {}
|
||||
|
||||
@@ -5,30 +5,25 @@ import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class BookmarkSaveRequestDto {
|
||||
public interface Create {}
|
||||
|
||||
public record BookmarkSaveRequestDto(
|
||||
@Schema(description = "생성 시 필수. 수정 시 페이지는 변경하지 않음")
|
||||
@NotNull(groups = Create.class)
|
||||
@Pattern(regexp = "TABULATION|CROSSTAB")
|
||||
private String bookmarkPage;
|
||||
String bookmarkPage,
|
||||
|
||||
@NotNull
|
||||
private String bookmarkTitle;
|
||||
String bookmarkTitle,
|
||||
@NotNull
|
||||
private String bookmarkInfo;
|
||||
String bookmarkInfo,
|
||||
|
||||
@Schema(description = "기존 북마크 설정 JSON 문자열. 저장 시 원문 유지")
|
||||
@NotNull
|
||||
private String bookmarkJson;
|
||||
String bookmarkJson,
|
||||
|
||||
@NotNull
|
||||
@Min(0)
|
||||
@Max(1)
|
||||
private Integer isOpen;
|
||||
Integer isOpen) {
|
||||
public interface Create {}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
package com.kri.kart.server.dto.derived;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class DerivedCalculationDto {
|
||||
int variableCount;
|
||||
int matchedRespondents;
|
||||
}
|
||||
public record DerivedCalculationDto(
|
||||
int variableCount,
|
||||
int matchedRespondents) {}
|
||||
|
||||
@@ -5,24 +5,19 @@ import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class DerivedSaveRequestDto {
|
||||
public record DerivedSaveRequestDto(
|
||||
@NotBlank
|
||||
@Size(max = 128)
|
||||
@Pattern(regexp = "[A-Za-z][A-Za-z0-9_]*")
|
||||
private String variableId;
|
||||
String variableId,
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 4000)
|
||||
private String variableTitle;
|
||||
String variableTitle,
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "single|multi|scale|num")
|
||||
private String variableType;
|
||||
String variableType,
|
||||
|
||||
@NotNull private JsonNode variableInfo;
|
||||
}
|
||||
@NotNull JsonNode variableInfo) {}
|
||||
|
||||
@@ -5,16 +5,11 @@ import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class AggregateExcelRequestDto {
|
||||
public record AggregateExcelRequestDto(
|
||||
@Valid
|
||||
@NotEmpty
|
||||
@Size(max = 1000)
|
||||
private List<@NotNull AggregateExcelTableDto> tables;
|
||||
List<@NotNull AggregateExcelTableDto> tables,
|
||||
|
||||
private boolean turn;
|
||||
}
|
||||
boolean turn) {}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public class ExportFileDto {
|
||||
private final String fileName;
|
||||
private final byte[] content;
|
||||
}
|
||||
public record ExportFileDto(
|
||||
String fileName,
|
||||
byte[] content) {}
|
||||
|
||||
@@ -1,24 +1,19 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import com.kri.common.feature.excel.ExcelColumn;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class ExportGuideDto {
|
||||
public record ExportGuideDto(
|
||||
@ExcelColumn(header = "문항 타입", order = 0)
|
||||
private String questionType;
|
||||
String questionType,
|
||||
|
||||
@ExcelColumn(header = "문항 / 보기번호", order = 1)
|
||||
private String variable;
|
||||
String variable,
|
||||
|
||||
@ExcelColumn(header = "내용", order = 2)
|
||||
private String content;
|
||||
String content,
|
||||
|
||||
@ExcelColumn(header = "VALUE LABEL", order = 3)
|
||||
private String valueLabel;
|
||||
String valueLabel,
|
||||
|
||||
@ExcelColumn(header = "VARIABLE LABEL", order = 4)
|
||||
private String variableLabel;
|
||||
}
|
||||
String variableLabel) {}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Completed download file owned by the caller until close. */
|
||||
public record ExportTempFileDto(String fileName, Path path) implements AutoCloseable {
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
Files.deleteIfExists(path);
|
||||
}
|
||||
}
|
||||
@@ -5,20 +5,15 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Schema(description = "화면 방문 로그. 프로젝트 정보는 둘 다 생략하거나 함께 지정한다.")
|
||||
public class VisitLogRequestDto {
|
||||
private ProjectType projectType;
|
||||
public record VisitLogRequestDto(
|
||||
ProjectType projectType,
|
||||
|
||||
@Size(max = 20)
|
||||
@Pattern(regexp = "^[^|]*$")
|
||||
private String pkey;
|
||||
String pkey,
|
||||
|
||||
@NotBlank
|
||||
@Schema(description = "방문한 화면 URL 또는 페이지 정보")
|
||||
private String logContent;
|
||||
}
|
||||
String logContent) {}
|
||||
|
||||
@@ -2,19 +2,14 @@ package com.kri.kart.server.dto.project;
|
||||
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import java.time.LocalDate;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProgressSearchDto {
|
||||
public record ProgressSearchDto(
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
private LocalDate startDate;
|
||||
LocalDate startDate,
|
||||
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
private LocalDate endDate;
|
||||
|
||||
LocalDate endDate) {
|
||||
public void validateRange() {
|
||||
if ((startDate == null) != (endDate == null)
|
||||
|| (startDate != null && startDate.isAfter(endDate))) {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.kri.kart.server.dto.project;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@Schema(description = "프로젝트 접근 권한 확인 결과")
|
||||
public record ProjectAccessDto(boolean allowed) {}
|
||||
@@ -3,21 +3,16 @@ package com.kri.kart.server.dto.project;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProjectLinkSearchDto {
|
||||
private ProjectType projectType;
|
||||
public record ProjectLinkSearchDto(
|
||||
ProjectType projectType,
|
||||
|
||||
@Size(max = 128)
|
||||
@Schema(description = "서비스 연동 조회용 인트라넷 프로젝트 코드. 첫 _ 앞 부분으로 검색")
|
||||
private String intranetCode;
|
||||
String intranetCode,
|
||||
|
||||
@Size(max = 32)
|
||||
private String userTeam;
|
||||
String userTeam,
|
||||
|
||||
@Size(max = 512)
|
||||
private String keyword;
|
||||
}
|
||||
String keyword) {}
|
||||
|
||||
@@ -3,26 +3,19 @@ package com.kri.kart.server.dto.project;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.Objects;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@EqualsAndHashCode
|
||||
@Schema(description = "프로젝트 유형과 프로젝트 키")
|
||||
public final class ProjectRefDto {
|
||||
public record ProjectRefDto(
|
||||
@Schema(description = "프로젝트 유형: 0=KON, 1=KIWI")
|
||||
private final ProjectType projectType;
|
||||
ProjectType projectType,
|
||||
|
||||
@Schema(description = "프로젝트 키", maxLength = 20)
|
||||
private final String pkey;
|
||||
|
||||
public ProjectRefDto(ProjectType projectType, String pkey) {
|
||||
String pkey) {
|
||||
public ProjectRefDto {
|
||||
Objects.requireNonNull(projectType, "Project type is required");
|
||||
if (pkey == null || pkey.isBlank() || pkey.length() > 20 || pkey.contains("|")) {
|
||||
throw new IllegalArgumentException(
|
||||
"Project key must be nonblank, at most 20 UTF-16 units, without legacy markers");
|
||||
}
|
||||
this.projectType = projectType;
|
||||
this.pkey = pkey;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.kri.kart.server.dto.quota;
|
||||
|
||||
import com.kri.kart.server.dto.statistics.StatisticsFilterDto;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Internal quota interpretation; condition validation remains lazy to preserve failure order. */
|
||||
public record PreparedQuotaDto(
|
||||
String index, List<List<String>> banners, StatisticsFilterDto filter) {
|
||||
|
||||
public record Entry(Long target, String isUsed, Long quotaId, Function<String, String> value) {}
|
||||
|
||||
public record Condition(String dimension, String choice) {}
|
||||
}
|
||||
@@ -1,20 +1,17 @@
|
||||
package com.kri.kart.server.dto.quota;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
public class QuotaCellDto {
|
||||
private int columnIndex;
|
||||
private String kind;
|
||||
private String textValue;
|
||||
private Long complete;
|
||||
private Long target;
|
||||
private Double achievementPercent;
|
||||
private String achievementState;
|
||||
private String achievementDisplayText;
|
||||
private String displayText;
|
||||
private String isUsed;
|
||||
private Long quotaId;
|
||||
}
|
||||
public record QuotaCellDto(
|
||||
int columnIndex,
|
||||
String kind,
|
||||
String textValue,
|
||||
Long complete,
|
||||
Long target,
|
||||
Double achievementPercent,
|
||||
String achievementState,
|
||||
String achievementDisplayText,
|
||||
String displayText,
|
||||
String isUsed,
|
||||
Long quotaId) {}
|
||||
|
||||
@@ -4,17 +4,14 @@ import com.kri.kart.server.dto.statistics.StatisticsColumnDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsRowDto;
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
public class QuotaResultDto {
|
||||
private Long quotaSetId;
|
||||
private Integer quotaOrder;
|
||||
private String title;
|
||||
private String index;
|
||||
private List<List<String>> banners;
|
||||
private List<StatisticsColumnDto> columns;
|
||||
private List<StatisticsRowDto> headerRows;
|
||||
private List<QuotaRowDto> rows;
|
||||
}
|
||||
public record QuotaResultDto(
|
||||
Long quotaSetId,
|
||||
Integer quotaOrder,
|
||||
String title,
|
||||
String index,
|
||||
List<List<String>> banners,
|
||||
List<StatisticsColumnDto> columns,
|
||||
List<StatisticsRowDto> headerRows,
|
||||
List<QuotaRowDto> rows) {}
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
package com.kri.kart.server.dto.quota;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class QuotaRowDto {
|
||||
private int rowIndex;
|
||||
private String rowId;
|
||||
private String kind;
|
||||
private List<QuotaCellDto> cells;
|
||||
}
|
||||
public record QuotaRowDto(
|
||||
int rowIndex,
|
||||
String rowId,
|
||||
String kind,
|
||||
List<QuotaCellDto> cells) {}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package com.kri.kart.server.dto.share;
|
||||
|
||||
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class ExternalLoginResponseDto {
|
||||
String accessToken;
|
||||
JwtUserClaimsDto user;
|
||||
ShareLinkDto link;
|
||||
}
|
||||
public record ExternalLoginResponseDto(
|
||||
String accessToken,
|
||||
JwtUserClaimsDto user,
|
||||
ShareLinkDto link) {}
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
package com.kri.kart.server.dto.share;
|
||||
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class ShareLinkDto {
|
||||
String urlKey;
|
||||
String url;
|
||||
String realUrl;
|
||||
ProjectType projectType;
|
||||
String pkey;
|
||||
String projectTitle;
|
||||
boolean pageOnly;
|
||||
}
|
||||
public record ShareLinkDto(
|
||||
String urlKey,
|
||||
String url,
|
||||
String realUrl,
|
||||
ProjectType projectType,
|
||||
String pkey,
|
||||
String projectTitle,
|
||||
boolean pageOnly) {}
|
||||
|
||||
@@ -3,17 +3,12 @@ package com.kri.kart.server.dto.share;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ShareLinkRequestDto {
|
||||
public record ShareLinkRequestDto(
|
||||
@NotBlank
|
||||
@Size(max = 4096)
|
||||
private String realUrl;
|
||||
String realUrl,
|
||||
|
||||
@NotBlank
|
||||
@Pattern(regexp = "P|U")
|
||||
private String mode;
|
||||
}
|
||||
String mode) {}
|
||||
|
||||
@@ -3,10 +3,15 @@ package com.kri.kart.server.dto.statistics;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* REPORT_NLP_WORD row. WORD_TAG STOP marks a 불용어 (stopword); a row with SOURCE_TEXT is a synonym
|
||||
* that replaces SOURCE_TEXT with WORD_TEXT/WORD_TAG; any other row is a Kiwi user word.
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class NlpDictionaryWordDto {
|
||||
private String wordText;
|
||||
private String wordTag;
|
||||
private Integer wordScore;
|
||||
private String sourceText;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/** Text-analysis replacement such as 엘지전자 → LG전자, with 1=ALL, 2=project, 3=question scope. */
|
||||
@Getter
|
||||
@Setter
|
||||
public class NlpSynonymDto {
|
||||
private String sourceText;
|
||||
private String targetText;
|
||||
private String targetTag;
|
||||
private Integer scopeRank;
|
||||
}
|
||||
@@ -1,13 +1,8 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class StatisticsColumnDto {
|
||||
private final String columnId;
|
||||
private final String kind;
|
||||
private final List<String> labels;
|
||||
}
|
||||
public record StatisticsColumnDto(
|
||||
String columnId,
|
||||
String kind,
|
||||
List<String> labels) {}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.kri.kart.server.common.enums.WordMergeMode;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
@@ -55,4 +56,13 @@ public class StatisticsOptionsDto {
|
||||
private boolean showNumericSum;
|
||||
|
||||
@Valid @NotNull private List<StatisticsValueGroupDto> valueGroups = new ArrayList<>();
|
||||
|
||||
@NotNull
|
||||
@Schema(description = "텍스트 분석에서 같은 단어의 품사별 빈도 합산 방식. 생략하면 2(명사 계열만 합치기)")
|
||||
private WordMergeMode wordMergeMode = WordMergeMode.NOUN;
|
||||
|
||||
@Min(1)
|
||||
@Max(5)
|
||||
@Schema(description = "텍스트 분석에서 공백 없이 붙은 명사를 합칠 최대 토큰 수. 1이면 합치지 않음. 생략하면 3")
|
||||
private int compoundNounMaxTokens = 3;
|
||||
}
|
||||
|
||||
@@ -2,17 +2,14 @@ package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
public class StatisticsResponseDto {
|
||||
private String type;
|
||||
private String questionId;
|
||||
private String title;
|
||||
private List<StatisticsColumnDto> columns;
|
||||
private List<StatisticsRowDto> headerRows;
|
||||
private List<StatisticsRowDto> rows;
|
||||
private List<StatisticsWordDto> words;
|
||||
private StatisticsRequestDto appliedOptions;
|
||||
}
|
||||
public record StatisticsResponseDto(
|
||||
String type,
|
||||
String questionId,
|
||||
String title,
|
||||
List<StatisticsColumnDto> columns,
|
||||
List<StatisticsRowDto> headerRows,
|
||||
List<StatisticsRowDto> rows,
|
||||
List<StatisticsWordDto> words,
|
||||
StatisticsRequestDto appliedOptions) {}
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class StatisticsRowDto {
|
||||
private final int rowIndex;
|
||||
private final String rowId;
|
||||
private final String kind;
|
||||
private final List<StatisticsCellDto> cells;
|
||||
}
|
||||
public record StatisticsRowDto(
|
||||
int rowIndex,
|
||||
String rowId,
|
||||
String kind,
|
||||
List<StatisticsCellDto> cells) {}
|
||||
|
||||
@@ -3,21 +3,18 @@ package com.kri.kart.server.dto.statistics;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
@Schema(description = "NDJSON 한 줄 이벤트. result/error는 문항별, complete는 스트림 완료")
|
||||
public class StatisticsStreamEventDto {
|
||||
private String type;
|
||||
private Integer position;
|
||||
private String index;
|
||||
private StatisticsResponseDto result;
|
||||
private Integer status;
|
||||
private String code;
|
||||
private String message;
|
||||
private Integer total;
|
||||
private Integer succeeded;
|
||||
private Integer failed;
|
||||
}
|
||||
public record StatisticsStreamEventDto(
|
||||
String type,
|
||||
Integer position,
|
||||
String index,
|
||||
StatisticsResponseDto result,
|
||||
Integer status,
|
||||
String code,
|
||||
String message,
|
||||
Integer total,
|
||||
Integer succeeded,
|
||||
Integer failed) {}
|
||||
|
||||
@@ -3,13 +3,8 @@ package com.kri.kart.server.dto.statistics;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class StatisticsValueGroupDto {
|
||||
@NotBlank private String label;
|
||||
public record StatisticsValueGroupDto(
|
||||
@NotBlank String label,
|
||||
|
||||
@NotEmpty private List<@NotBlank String> values;
|
||||
}
|
||||
@NotEmpty List<@NotBlank String> values) {}
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class StatisticsWordDto {
|
||||
private final String text;
|
||||
private final String tag;
|
||||
private final long count;
|
||||
}
|
||||
public record StatisticsWordDto(
|
||||
String text,
|
||||
String tag,
|
||||
long count) {}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
package com.kri.kart.server.dto.upload;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class ImportQuestionDto {
|
||||
String qid;
|
||||
int qOrder;
|
||||
String questionJson;
|
||||
String qinfo;
|
||||
String linfo;
|
||||
}
|
||||
public record ImportQuestionDto(
|
||||
String qid,
|
||||
int qOrder,
|
||||
String questionJson,
|
||||
String qinfo,
|
||||
String linfo) {}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
package com.kri.kart.server.dto.upload;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class ImportResponseDto {
|
||||
String idkey;
|
||||
String status;
|
||||
String pageName;
|
||||
String datjson;
|
||||
String surveyDate;
|
||||
}
|
||||
public record ImportResponseDto(
|
||||
String idkey,
|
||||
String status,
|
||||
String pageName,
|
||||
String datjson,
|
||||
String surveyDate) {}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package com.kri.kart.server.dto.upload;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class ImportResultDto {
|
||||
int processedRows;
|
||||
int affectedRows;
|
||||
int removedRows;
|
||||
int archivedRows;
|
||||
}
|
||||
public record ImportResultDto(
|
||||
int processedRows,
|
||||
int affectedRows,
|
||||
int removedRows,
|
||||
int archivedRows) {}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
package com.kri.kart.server.dto.upload;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class UploadTableDto {
|
||||
List<String> headers;
|
||||
List<List<String>> rows;
|
||||
}
|
||||
public record UploadTableDto(
|
||||
List<String> headers,
|
||||
List<List<String>> rows) {}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
package com.kri.kart.server.service.share;
|
||||
package com.kri.kart.server.interceptor;
|
||||
|
||||
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.common.feature.web.RequestUserContextProvider;
|
||||
import com.kri.kart.server.common.consts.KartConstant;
|
||||
import com.kri.kart.server.dto.share.ShareLinkDto;
|
||||
import com.kri.kart.server.service.ShareLinkService;
|
||||
@@ -11,14 +12,13 @@ import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
/** 공용 인증이 검증한 identity와 REPORT_URL을 사용한다. 일반 사용자 역할 제한과는 별개다. */
|
||||
@RequiredArgsConstructor
|
||||
public class ExternalAccessInterceptor implements HandlerInterceptor {
|
||||
private final RequestUserContextProvider requestUserContextProvider;
|
||||
private final ShareLinkService shareLinkService;
|
||||
|
||||
@Override
|
||||
@@ -31,17 +31,12 @@ public class ExternalAccessInterceptor implements HandlerInterceptor {
|
||||
// A new link or credential login may replace a previous external identity.
|
||||
return true;
|
||||
}
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null
|
||||
|| !authentication.isAuthenticated()
|
||||
|| !(authentication.getDetails() instanceof JwtUserClaimsDto claims)) {
|
||||
return true;
|
||||
}
|
||||
String userId = claims.getUserId();
|
||||
RequestUserContext ctx = requestUserContextProvider.resolve(request);
|
||||
String userId = ctx.getUserId();
|
||||
boolean externalRole =
|
||||
Integer.valueOf(KartConstant.EXTERNAL_URL_COPY_ROLE).equals(claims.getUserRole())
|
||||
|| Integer.valueOf(KartConstant.EXTERNAL_PAGE_COPY_ROLE).equals(claims.getUserRole());
|
||||
boolean externalTeam = KartConstant.EXTERNAL_TEAM.equals(claims.getUserTeam());
|
||||
Integer.valueOf(KartConstant.EXTERNAL_URL_COPY_ROLE).equals(ctx.getUserRole())
|
||||
|| Integer.valueOf(KartConstant.EXTERNAL_PAGE_COPY_ROLE).equals(ctx.getUserRole());
|
||||
boolean externalTeam = KartConstant.EXTERNAL_TEAM.equals(ctx.getUserTeam());
|
||||
boolean externalId = userId != null && userId.startsWith(KartConstant.EXTERNAL_USER_PREFIX);
|
||||
if (!externalRole && !externalTeam && !externalId) {
|
||||
return true;
|
||||
@@ -52,37 +47,41 @@ public class ExternalAccessInterceptor implements HandlerInterceptor {
|
||||
String urlKey = userId.substring(KartConstant.EXTERNAL_USER_PREFIX.length());
|
||||
ShareLinkDto link =
|
||||
(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);
|
||||
}
|
||||
int expectedRole =
|
||||
link.isPageOnly()
|
||||
link.pageOnly()
|
||||
? KartConstant.EXTERNAL_PAGE_COPY_ROLE
|
||||
: KartConstant.EXTERNAL_URL_COPY_ROLE;
|
||||
if (!Integer.valueOf(expectedRole).equals(claims.getUserRole())) {
|
||||
if (!Integer.valueOf(expectedRole).equals(ctx.getUserRole())) {
|
||||
throw denied();
|
||||
}
|
||||
if ("GET".equals(request.getMethod()) && "/api/v1/auth/my-info".equals(pattern)) {
|
||||
return true;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> variables =
|
||||
(Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
|
||||
if (variables == null
|
||||
|| !link.getProjectType().getCode().toString().equals(variables.get("projectType"))
|
||||
|| !link.getPkey().equals(variables.get("pkey"))) {
|
||||
|| !link.projectType().getCode().toString().equals(variables.get("projectType"))
|
||||
|| !link.pkey().equals(variables.get("pkey"))) {
|
||||
// Visit body scope is checked in LogController after JSON binding.
|
||||
if (!"/api/v1/log/visit".equals(pattern) || !"POST".equals(request.getMethod())) {
|
||||
throw denied();
|
||||
}
|
||||
}
|
||||
String page = URI.create(link.getRealUrl()).getPath();
|
||||
String page = URI.create(link.realUrl()).getPath();
|
||||
boolean allowed = "/api/v1/log/visit".equals(pattern);
|
||||
if ("GET".equals(request.getMethod())) {
|
||||
allowed |= pattern.equals("/api/v1/project/{projectType}/{pkey}/access");
|
||||
allowed |=
|
||||
Set.of(
|
||||
"/api/v1/project/{projectType}/{pkey}/question/list",
|
||||
"/api/v1/project/{projectType}/{pkey}/question/{qid}")
|
||||
.contains(pattern);
|
||||
allowed |=
|
||||
(!link.isPageOnly() || page.equals("/Report/Current"))
|
||||
(!link.pageOnly() || page.equals("/Report/Current"))
|
||||
&& Set.of(
|
||||
"/api/v1/project/{projectType}/{pkey}/progress/day",
|
||||
"/api/v1/project/{projectType}/{pkey}/progress/type",
|
||||
@@ -90,28 +89,28 @@ public class ExternalAccessInterceptor implements HandlerInterceptor {
|
||||
"/api/v1/project/{projectType}/{pkey}/progress/screen")
|
||||
.contains(pattern);
|
||||
allowed |=
|
||||
(!link.isPageOnly() || page.equals("/Report/Quota"))
|
||||
(!link.pageOnly() || page.equals("/Report/Quota"))
|
||||
&& pattern.equals("/api/v1/quota/{projectType}/{pkey}/list");
|
||||
if (pattern.equals("/api/v1/project/{projectType}/{pkey}/bookmark/list")) {
|
||||
String bookmarkPage = request.getParameter("page");
|
||||
allowed |=
|
||||
Set.of("TABULATION", "CROSSTAB").contains(bookmarkPage == null ? "" : bookmarkPage)
|
||||
&& (!link.isPageOnly()
|
||||
&& (!link.pageOnly()
|
||||
|| (page.equals("/Report/Tabulation") && "TABULATION".equals(bookmarkPage))
|
||||
|| (page.equals("/Report/Crosstab") && "CROSSTAB".equals(bookmarkPage)));
|
||||
}
|
||||
} else if ("POST".equals(request.getMethod())) {
|
||||
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");
|
||||
allowed |=
|
||||
(!link.isPageOnly() || page.equals("/Report/Quota"))
|
||||
(!link.pageOnly() || page.equals("/Report/Quota"))
|
||||
&& pattern.equals("/api/v1/quota/{projectType}/{pkey}/export/excel");
|
||||
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");
|
||||
allowed |=
|
||||
(!link.isPageOnly() || page.equals("/Report/Quota"))
|
||||
(!link.pageOnly() || page.equals("/Report/Quota"))
|
||||
&& pattern.equals("/api/v1/quota/{projectType}/{pkey}/{quotaOrder}/result");
|
||||
}
|
||||
if (!allowed) {
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.kri.kart.server.interceptor;
|
||||
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.common.feature.web.RequestUserContextProvider;
|
||||
import com.kri.kart.server.common.consts.KartConstant;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.service.ProjectService;
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class ProjectAccessInterceptor implements HandlerInterceptor {
|
||||
private final RequestUserContextProvider requestUserContextProvider;
|
||||
private final ProjectService projectService;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(
|
||||
HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
// ExternalAccessInterceptor has already checked the stored project/page/API scope.
|
||||
if (request.getDispatcherType() == DispatcherType.ASYNC
|
||||
|| request.getAttribute(KartConstant.REQUEST_LINK_ATTRIBUTE) != null) {
|
||||
return true;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> variables =
|
||||
(Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
|
||||
if (variables == null
|
||||
|| !variables.containsKey("projectType")
|
||||
|| !variables.containsKey("pkey")) {
|
||||
return true;
|
||||
}
|
||||
RequestUserContext ctx = requestUserContextProvider.resolve(request);
|
||||
if (!ctx.isAuthenticated()) {
|
||||
throw unauthenticated();
|
||||
}
|
||||
ProjectRefDto project;
|
||||
try {
|
||||
project = new ProjectRefDto(
|
||||
ProjectType.fromCode(Integer.valueOf(variables.get("projectType"))),
|
||||
variables.get("pkey"));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw BusinessException.badRequest("projectType 또는 pkey가 올바르지 않습니다.");
|
||||
}
|
||||
projectService.requireAccess(project, ctx);
|
||||
return true;
|
||||
}
|
||||
|
||||
private BusinessException unauthenticated() {
|
||||
return BusinessException.unauthorized("PROJECT_IDENTITY_REQUIRED", "프로젝트 접근 인증 정보가 필요합니다.");
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ public class SurveySessionProvider {
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -14,6 +14,8 @@ public interface DerivedMapper {
|
||||
|
||||
String lockProject(@Param("pkey") String pkey);
|
||||
|
||||
boolean projectExists(@Param("pkey") String pkey);
|
||||
|
||||
List<DerivedDefinitionDto> definitions(@Param("pkey") String pkey);
|
||||
|
||||
DerivedDefinitionDto find(@Param("pkey") String pkey, @Param("qid") String qid);
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.kri.kart.server.dto.export.ExportTitleDto;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.session.ResultHandler;
|
||||
|
||||
public interface ExportMapper {
|
||||
String additionalColumns(@Param("pkey") String pkey);
|
||||
@@ -19,10 +20,11 @@ public interface ExportMapper {
|
||||
|
||||
String surveyType(@Param("pkey") String pkey);
|
||||
|
||||
List<ExportDataDto> data(
|
||||
void data(
|
||||
@Param("pkey") String pkey,
|
||||
@Param("type") String type,
|
||||
@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate,
|
||||
@Param("includeInterviewer") Boolean includeInterviewer);
|
||||
@Param("includeInterviewer") Boolean includeInterviewer,
|
||||
ResultHandler<ExportDataDto> handler);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,12 @@ import java.util.List;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
public interface ProjectMapper {
|
||||
boolean hasAccess(
|
||||
@Param("pkey") String pkey,
|
||||
@Param("userRole") Integer userRole,
|
||||
@Param("authenticatedUserTeam") String authenticatedUserTeam,
|
||||
@Param("assignedPkeys") List<String> assignedPkeys);
|
||||
|
||||
List<ProjectListDto> list(
|
||||
@Param("userRole") Integer userRole,
|
||||
@Param("authenticatedUserTeam") String authenticatedUserTeam,
|
||||
|
||||
@@ -22,12 +22,12 @@ public class BookmarkRepository {
|
||||
|
||||
public List<BookmarkDto> list(ProjectRefDto project, String page, String userId) {
|
||||
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
|
||||
.list(project.getPkey(), page, userId);
|
||||
.list(project.pkey(), page, userId);
|
||||
}
|
||||
|
||||
public BookmarkDto find(ProjectRefDto project, String bookmarkId) {
|
||||
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
|
||||
.find(project.getPkey(), bookmarkId);
|
||||
.find(project.pkey(), bookmarkId);
|
||||
}
|
||||
|
||||
public int create(
|
||||
@@ -37,22 +37,22 @@ public class BookmarkRepository {
|
||||
String userTeam,
|
||||
String userId) {
|
||||
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
|
||||
.create(project.getPkey(), bookmarkId, request, userTeam, userId);
|
||||
.create(project.pkey(), bookmarkId, request, userTeam, userId);
|
||||
}
|
||||
|
||||
public int update(
|
||||
ProjectRefDto project, String bookmarkId, BookmarkSaveRequestDto request, String userId) {
|
||||
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) {
|
||||
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
|
||||
.shiftOrderAfterDelete(project.getPkey(), bookmarkId, userId);
|
||||
.shiftOrderAfterDelete(project.pkey(), bookmarkId, userId);
|
||||
}
|
||||
|
||||
public int delete(ProjectRefDto project, String bookmarkId, String userId) {
|
||||
return kartSqlSessionTemplate.getMapper(BookmarkMapper.class)
|
||||
.delete(project.getPkey(), bookmarkId, userId);
|
||||
.delete(project.pkey(), bookmarkId, userId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,27 +19,31 @@ public class DerivedRepository {
|
||||
|
||||
public List<QuestionDto> list(ProjectRefDto project, Integer userRole, String userTeam) {
|
||||
return surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.list(project.getPkey(), userRole, userTeam);
|
||||
.list(project.pkey(), userRole, userTeam);
|
||||
}
|
||||
|
||||
public String lockProject(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.lockProject(project.getPkey());
|
||||
.lockProject(project.pkey());
|
||||
}
|
||||
|
||||
public boolean projectExists(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, DerivedMapper.class).projectExists(project.pkey());
|
||||
}
|
||||
|
||||
public List<DerivedDefinitionDto> definitions(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.definitions(project.getPkey());
|
||||
.definitions(project.pkey());
|
||||
}
|
||||
|
||||
public DerivedDefinitionDto find(ProjectRefDto project, String qid) {
|
||||
return surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.find(project.getPkey(), qid);
|
||||
.find(project.pkey(), qid);
|
||||
}
|
||||
|
||||
public boolean duplicate(ProjectRefDto project, String qid, String originId) {
|
||||
return surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.duplicate(project.getPkey(), qid, originId == null ? "" : originId)
|
||||
.duplicate(project.pkey(), qid, originId == null ? "" : originId)
|
||||
> 0;
|
||||
}
|
||||
|
||||
@@ -52,14 +56,14 @@ public class DerivedRepository {
|
||||
var derivedMapper = surveySessionProvider.mapper(project, DerivedMapper.class);
|
||||
return originId == null
|
||||
? derivedMapper.create(
|
||||
project.getPkey(),
|
||||
project.pkey(),
|
||||
definition.getQid(),
|
||||
definition.getQuestionJson(),
|
||||
definition.getDerivedJson(),
|
||||
userTeam,
|
||||
userId)
|
||||
: derivedMapper.update(
|
||||
project.getPkey(),
|
||||
project.pkey(),
|
||||
definition.getQid(),
|
||||
definition.getQuestionJson(),
|
||||
definition.getDerivedJson(),
|
||||
@@ -70,41 +74,41 @@ public class DerivedRepository {
|
||||
|
||||
public void shiftOrder(ProjectRefDto project, String qid) {
|
||||
surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.shiftOrder(project.getPkey(), qid);
|
||||
.shiftOrder(project.pkey(), qid);
|
||||
}
|
||||
|
||||
public int delete(ProjectRefDto project, String qid) {
|
||||
return surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.delete(project.getPkey(), qid);
|
||||
.delete(project.pkey(), qid);
|
||||
}
|
||||
|
||||
public void clearData(ProjectRefDto project, String qid) {
|
||||
surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.clearData(project.getPkey(), "$.\"" + qid + "\"");
|
||||
.clearData(project.pkey(), "$.\"" + qid + "\"");
|
||||
}
|
||||
|
||||
public List<DerivedDataDto> responses(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.responses(project.getPkey());
|
||||
.responses(project.pkey());
|
||||
}
|
||||
|
||||
public void ensureRespondent(ProjectRefDto project, String idkey) {
|
||||
surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.ensureRespondent(project.getPkey(), idkey);
|
||||
.ensureRespondent(project.pkey(), idkey);
|
||||
}
|
||||
|
||||
public void clearRespondentData(ProjectRefDto project, String qid, String idkey) {
|
||||
surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.clearRespondentData(project.getPkey(), "$.\"" + qid + "\"", idkey);
|
||||
.clearRespondentData(project.pkey(), "$.\"" + qid + "\"", idkey);
|
||||
}
|
||||
|
||||
public List<DerivedDataDto> respondentResponses(ProjectRefDto project, String idkey) {
|
||||
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) {
|
||||
surveySessionProvider.mapper(project, DerivedMapper.class)
|
||||
.saveData(project.getPkey(), "$.\"" + qid + "\"", idkey, groupJson);
|
||||
.saveData(project.pkey(), "$.\"" + qid + "\"", idkey, groupJson);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.persistence.SurveySessionProvider;
|
||||
import com.kri.kart.server.persistence.mapper.ExportMapper;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Repository;
|
||||
@@ -21,35 +22,35 @@ public class ExportRepository {
|
||||
|
||||
public String additionalColumns(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ExportMapper.class)
|
||||
.additionalColumns(project.getPkey());
|
||||
.additionalColumns(project.pkey());
|
||||
}
|
||||
|
||||
public List<ExportDerivedHeaderDto> derivedHeaders(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ExportMapper.class)
|
||||
.derivedHeaders(project.getPkey());
|
||||
.derivedHeaders(project.pkey());
|
||||
}
|
||||
|
||||
public List<ExportHeaderDto> questionHeaders(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ExportMapper.class)
|
||||
.questionHeaders(project.getPkey());
|
||||
.questionHeaders(project.pkey());
|
||||
}
|
||||
|
||||
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) {
|
||||
return surveySessionProvider.mapper(project, ExportMapper.class).surveyType(project.getPkey());
|
||||
return surveySessionProvider.mapper(project, ExportMapper.class).surveyType(project.pkey());
|
||||
}
|
||||
|
||||
public List<ExportDataDto> data(
|
||||
ProjectRefDto project, RawDataExportRequestDto request, boolean includeInterviewer) {
|
||||
return surveySessionProvider.mapper(project, ExportMapper.class)
|
||||
public void data(
|
||||
ProjectRefDto project, RawDataExportRequestDto request, boolean includeInterviewer, Consumer<ExportDataDto> consumer) {
|
||||
surveySessionProvider.mapper(project, ExportMapper.class)
|
||||
.data(
|
||||
project.getPkey(),
|
||||
project.pkey(),
|
||||
request.getType(),
|
||||
request.getStartDate(),
|
||||
request.getEndDate() == null ? request.getStartDate() : request.getEndDate(),
|
||||
includeInterviewer);
|
||||
includeInterviewer, context -> consumer.accept(context.getResultObject()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,65 +16,65 @@ public class ImportRepository {
|
||||
private final SurveySessionProvider surveySessionProvider;
|
||||
|
||||
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) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class).resetTitles(project.getPkey());
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class).resetTitles(project.pkey());
|
||||
}
|
||||
|
||||
public int deleteQuestions(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.deleteQuestions(project.getPkey());
|
||||
.deleteQuestions(project.pkey());
|
||||
}
|
||||
|
||||
public int deleteOptions(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.deleteOptions(project.getPkey());
|
||||
.deleteOptions(project.pkey());
|
||||
}
|
||||
|
||||
public int deleteQuotaSets(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.deleteQuotaSets(project.getPkey());
|
||||
.deleteQuotaSets(project.pkey());
|
||||
}
|
||||
|
||||
public int deleteQuotas(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.deleteQuotas(project.getPkey());
|
||||
.deleteQuotas(project.pkey());
|
||||
}
|
||||
|
||||
public int resetStructure(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.resetStructure(project.getPkey());
|
||||
.resetStructure(project.pkey());
|
||||
}
|
||||
|
||||
public int deleteUploaded(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.deleteUploaded(project.getPkey());
|
||||
.deleteUploaded(project.pkey());
|
||||
}
|
||||
|
||||
public int archiveCompleted(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.archiveCompleted(project.getPkey());
|
||||
.archiveCompleted(project.pkey());
|
||||
}
|
||||
|
||||
public int title(ProjectRefDto project, String qid, String explain) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.title(project.getPkey(), qid, explain);
|
||||
.title(project.pkey(), qid, explain);
|
||||
}
|
||||
|
||||
public int question(ProjectRefDto project, ImportQuestionDto question) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.question(project.getPkey(), question);
|
||||
.question(project.pkey(), question);
|
||||
}
|
||||
|
||||
public int structure(ProjectRefDto project, ImportQuestionDto question) {
|
||||
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) {
|
||||
return surveySessionProvider.mapper(project, ImportMapper.class)
|
||||
.response(project.getPkey(), response);
|
||||
.response(project.pkey(), response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,31 +22,31 @@ public class ProgressRepository {
|
||||
|
||||
public List<ProgressDayDto> daily(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ProgressMapper.class)
|
||||
.daily(project.getPkey());
|
||||
.daily(project.pkey());
|
||||
}
|
||||
|
||||
public List<ProgressTypeDto> type(ProjectRefDto project, ProgressSearchDto search) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
return surveySessionProvider.mapper(project, ProgressMapper.class)
|
||||
.reportUrls(project.getPkey());
|
||||
.reportUrls(project.pkey());
|
||||
}
|
||||
|
||||
public List<CustomProgressDto> appendFiles(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ProgressMapper.class)
|
||||
.appendFiles(project.getPkey());
|
||||
.appendFiles(project.pkey());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.kri.kart.server.persistence.repository;
|
||||
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.project.ProjectListDto;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.project.ProjectSummaryDto;
|
||||
import com.kri.kart.server.persistence.SurveySessionProvider;
|
||||
import com.kri.kart.server.persistence.mapper.ProjectMapper;
|
||||
@@ -24,6 +25,12 @@ public class ProjectRepository {
|
||||
this.kartSqlSessionTemplate = kartSqlSessionTemplate;
|
||||
}
|
||||
|
||||
public boolean hasAccess(
|
||||
ProjectRefDto project, Integer userRole, String userTeam, List<String> assignedPkeys) {
|
||||
return surveySessionProvider.mapper(project, ProjectMapper.class)
|
||||
.hasAccess(project.pkey(), userRole, userTeam, assignedPkeys);
|
||||
}
|
||||
|
||||
public List<String> findMustViewPkeys(ProjectType type) {
|
||||
return kartSqlSessionTemplate.getMapper(ProjectMapper.class).mustViewPkeys(type.getCode());
|
||||
}
|
||||
|
||||
@@ -17,6 +17,6 @@ public class QuestionRepository {
|
||||
|
||||
public List<QuestionDto> list(ProjectRefDto project, boolean includeProfiles) {
|
||||
return surveySessionProvider.mapper(project, QuestionMapper.class)
|
||||
.list(project.getPkey(), includeProfiles);
|
||||
.list(project.pkey(), includeProfiles);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,16 +18,16 @@ public class QuotaRepository {
|
||||
|
||||
public List<QuotaSetDto> quotaSets(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, QuotaMapper.class)
|
||||
.quotaSets(project.getPkey());
|
||||
.quotaSets(project.pkey());
|
||||
}
|
||||
|
||||
public QuotaSetDto quotaSet(ProjectRefDto project, int quotaOrder) {
|
||||
return surveySessionProvider.mapper(project, QuotaMapper.class)
|
||||
.quotaSet(project.getPkey(), quotaOrder);
|
||||
.quotaSet(project.pkey(), quotaOrder);
|
||||
}
|
||||
|
||||
public List<QuotaEntryDto> quotaEntries(ProjectRefDto project, int quotaOrder) {
|
||||
return surveySessionProvider.mapper(project, QuotaMapper.class)
|
||||
.quotaEntries(project.getPkey(), quotaOrder);
|
||||
.quotaEntries(project.pkey(), quotaOrder);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ public class ShareLinkRepository {
|
||||
|
||||
public String projectTitle(ProjectRefDto project) {
|
||||
return surveySessionProvider.mapper(project, ShareLinkMapper.class)
|
||||
.projectTitle(project.getPkey());
|
||||
.projectTitle(project.pkey());
|
||||
}
|
||||
|
||||
public ShareLinkRecordDto reusable(ShareLinkRecordDto link) {
|
||||
|
||||
@@ -23,7 +23,7 @@ public class StatisticsRepository {
|
||||
List<String> selectedRoots) {
|
||||
return surveySessionProvider.mapper(project, StatisticsMapper.class)
|
||||
.data(
|
||||
project.getPkey(),
|
||||
project.pkey(),
|
||||
request.getDataScope(),
|
||||
request.getStartDate(),
|
||||
request.getEndDate() == null ? request.getStartDate() : request.getEndDate(),
|
||||
|
||||
@@ -58,12 +58,12 @@ public class AggregateExcelService {
|
||||
private ExportFileDto export(
|
||||
ProjectRefDto project, AggregateExcelRequestDto request, boolean quota) {
|
||||
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);
|
||||
var output = new ByteArrayOutputStream()) {
|
||||
if (quota) {
|
||||
for (int i = 0; i < request.getTables().size(); i++) {
|
||||
var table = request.getTables().get(i);
|
||||
for (int i = 0; i < request.tables().size(); i++) {
|
||||
var table = request.tables().get(i);
|
||||
Sheet sheet =
|
||||
i == 0 ? workbook.getSheetAt(0) : workbook.createSheet(clean(table.getHead()));
|
||||
CellStyle base = baseStyle(workbook, 9, false);
|
||||
@@ -82,7 +82,7 @@ public class AggregateExcelService {
|
||||
initializeSheet(contents, contentsStyle);
|
||||
initializeSheet(tables, bodyStyle);
|
||||
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);
|
||||
}
|
||||
rectangle(
|
||||
@@ -93,7 +93,7 @@ public class AggregateExcelService {
|
||||
cell.setCellValue("목차");
|
||||
});
|
||||
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(
|
||||
contents,
|
||||
area,
|
||||
@@ -113,8 +113,8 @@ public class AggregateExcelService {
|
||||
});
|
||||
border(contents, area, BorderStyle.THIN);
|
||||
int nextRow = 1;
|
||||
for (int i = 0; i < request.getTables().size(); i++) {
|
||||
var item = request.getTables().get(i);
|
||||
for (int i = 0; i < request.tables().size(); i++) {
|
||||
var item = request.tables().get(i);
|
||||
cell(contents, i + 5, 1).setCellValue(title(item));
|
||||
var link = cell(contents, i + 5, 2);
|
||||
link.setCellValue("Go");
|
||||
@@ -127,7 +127,7 @@ public class AggregateExcelService {
|
||||
font.setUnderline(org.apache.poi.ss.usermodel.Font.U_SINGLE);
|
||||
font.setColor(org.apache.poi.ss.usermodel.IndexedColors.BLUE.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);
|
||||
contents.createFreezePane(0, 4);
|
||||
@@ -137,7 +137,7 @@ public class AggregateExcelService {
|
||||
"["
|
||||
+ (quota ? "QUOTA" : "REPORT")
|
||||
+ "]"
|
||||
+ project.getPkey()
|
||||
+ project.pkey()
|
||||
+ "_"
|
||||
+ DateTimeUtil.nowKstLocalDateTime().format(TIMESTAMP)
|
||||
+ ".xlsx",
|
||||
@@ -445,7 +445,7 @@ public class AggregateExcelService {
|
||||
|
||||
private void validate(AggregateExcelRequestDto request) {
|
||||
long total = 0;
|
||||
for (var table : request.getTables()) {
|
||||
for (var table : request.tables()) {
|
||||
var keys = new ArrayList<>(table.getBody().get(0).keySet());
|
||||
if (keys.size() < 2 || keys.size() > 1024) {
|
||||
throw invalid();
|
||||
|
||||
@@ -37,13 +37,13 @@ public class BookmarkService {
|
||||
@Transactional(transactionManager = "kartTransactionManager")
|
||||
public String create(
|
||||
ProjectRefDto project, BookmarkSaveRequestDto request, RequestUserContext ctx) {
|
||||
if (!StringUtil.hasText(request.getBookmarkPage())) {
|
||||
if (!StringUtil.hasText(request.bookmarkPage())) {
|
||||
throw BusinessException.badRequest("생성할 북마크 페이지를 입력해 주세요.");
|
||||
}
|
||||
String bookmarkId =
|
||||
project.getPkey()
|
||||
project.pkey()
|
||||
+ "_"
|
||||
+ request.getBookmarkPage().charAt(0)
|
||||
+ request.bookmarkPage().charAt(0)
|
||||
+ "_"
|
||||
+ DateTimeUtil.nowKstLocalDateTime().format(ID_TIMESTAMP);
|
||||
bookmarkRepository.create(project, bookmarkId, request, ctx.getUserTeam(), ctx.getUserId());
|
||||
@@ -100,10 +100,10 @@ public class BookmarkService {
|
||||
private ObjectNode snapshot(String bookmarkId, BookmarkSaveRequestDto request) {
|
||||
return snapshot(
|
||||
bookmarkId,
|
||||
request.getBookmarkTitle(),
|
||||
request.getBookmarkInfo(),
|
||||
request.getBookmarkJson(),
|
||||
request.getIsOpen());
|
||||
request.bookmarkTitle(),
|
||||
request.bookmarkInfo(),
|
||||
request.bookmarkJson(),
|
||||
request.isOpen());
|
||||
}
|
||||
|
||||
private ObjectNode snapshot(BookmarkDto bookmark) {
|
||||
|
||||
@@ -6,11 +6,15 @@ import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.derived.DerivedCalculationDto;
|
||||
import com.kri.kart.server.dto.derived.DerivedDataDto;
|
||||
import com.kri.kart.server.dto.derived.DerivedDefinitionDto;
|
||||
import com.kri.kart.server.dto.derived.DerivedSaveRequestDto;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.question.QuestionDto;
|
||||
import com.kri.kart.server.persistence.repository.DerivedRepository;
|
||||
import com.kri.kart.server.service.derived.DerivedComputationService;
|
||||
import com.kri.kart.server.service.derived.DerivedRecalculationGuard;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
@@ -28,6 +32,7 @@ public class DerivedManagementService {
|
||||
private final DerivedComputationService derivedComputationService;
|
||||
private final LogService logService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final DerivedRecalculationGuard derivedRecalculationGuard;
|
||||
private final PlatformTransactionManager konTransactionManager;
|
||||
private final PlatformTransactionManager konkiwiTransactionManager;
|
||||
|
||||
@@ -37,6 +42,7 @@ public class DerivedManagementService {
|
||||
DerivedComputationService derivedComputationService,
|
||||
LogService logService,
|
||||
ObjectMapper objectMapper,
|
||||
DerivedRecalculationGuard derivedRecalculationGuard,
|
||||
@Qualifier("konTransactionManager") PlatformTransactionManager konTransactionManager,
|
||||
@Qualifier("konkiwiTransactionManager")
|
||||
PlatformTransactionManager konkiwiTransactionManager) {
|
||||
@@ -45,6 +51,7 @@ public class DerivedManagementService {
|
||||
this.derivedComputationService = derivedComputationService;
|
||||
this.logService = logService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.derivedRecalculationGuard = derivedRecalculationGuard;
|
||||
this.konTransactionManager = konTransactionManager;
|
||||
this.konkiwiTransactionManager = konkiwiTransactionManager;
|
||||
}
|
||||
@@ -55,7 +62,7 @@ public class DerivedManagementService {
|
||||
DerivedSaveRequestDto request,
|
||||
RequestUserContext ctx) {
|
||||
requireRole(ctx);
|
||||
validateId(request.getVariableId());
|
||||
validateId(request.variableId());
|
||||
if (originId != null) {
|
||||
validateId(originId);
|
||||
}
|
||||
@@ -68,7 +75,9 @@ public class DerivedManagementService {
|
||||
if (original != null) {
|
||||
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입니다.");
|
||||
}
|
||||
if (derivedRepository.save(
|
||||
@@ -79,7 +88,7 @@ public class DerivedManagementService {
|
||||
if (original != null && !original.getQid().equals(definition.getQid())) {
|
||||
derivedRepository.clearData(project, original.getQid());
|
||||
}
|
||||
calculate(project, definition);
|
||||
calculate(project, definition, null, derivedIds(derivedRepository.definitions(project)));
|
||||
var content = objectMapper.createObjectNode();
|
||||
content.set("NEW", objectMapper.valueToTree(definition));
|
||||
if (original != null) {
|
||||
@@ -129,9 +138,11 @@ public class DerivedManagementService {
|
||||
qid == null
|
||||
? derivedRepository.definitions(project)
|
||||
: List.of(requireDefinition(project, qid));
|
||||
var derivedIds =
|
||||
derivedIds(qid == null ? definitions : derivedRepository.definitions(project));
|
||||
int matched = 0;
|
||||
for (var definition : definitions) {
|
||||
matched += calculate(project, definition);
|
||||
matched += calculate(project, definition, null, derivedIds);
|
||||
}
|
||||
if (qid == null) {
|
||||
logService.writeSiteLog(
|
||||
@@ -148,27 +159,100 @@ public class DerivedManagementService {
|
||||
if (idkey == null || idkey.isBlank() || idkey.length() > 512) {
|
||||
throw BusinessException.badRequest("응답자 ID를 확인해 주세요.");
|
||||
}
|
||||
return derivedRecalculationGuard.execute(project, idkey, () -> {
|
||||
if (!derivedRepository.projectExists(project)) {
|
||||
throw BusinessException.notFound("PROJECT_NOT_FOUND", "프로젝트를 찾을 수 없습니다.");
|
||||
}
|
||||
List<DerivedDefinitionDto> definitions = derivedRepository.definitions(project);
|
||||
List<String> derivedIds = derivedIds(definitions);
|
||||
List<QuestionDto> questions = definitions.isEmpty() ? List.of() : questionService.list(project, 1001);
|
||||
List<DerivedDataDto> data = definitions.isEmpty() ? List.of()
|
||||
: derivedRepository.respondentResponses(project, idkey);
|
||||
if (data.size() > 1) {
|
||||
// Legacy joins can return multiple rows for one ID. Preserve their database reread
|
||||
// semantics rather than assuming uniqueness or collapsing results in memory.
|
||||
return transaction(project, () -> {
|
||||
derivedRepository.ensureRespondent(project, idkey);
|
||||
int matched = 0;
|
||||
for (DerivedDefinitionDto definition : definitions) {
|
||||
matched += calculate(project, definition, idkey, derivedIds, questions);
|
||||
}
|
||||
return new DerivedCalculationDto(definitions.size(), matched);
|
||||
});
|
||||
}
|
||||
definitions.forEach(definition -> validateId(definition.getQid()));
|
||||
var results = derivedComputationService.calculateRespondent(definitions, questions, data, derivedIds);
|
||||
List<RespondentWrite> writes = new ArrayList<>();
|
||||
int matched = 0;
|
||||
for (int variable = 0; variable < definitions.size(); variable++) {
|
||||
List<String> groups = new ArrayList<>();
|
||||
for (var group : results.get(variable)) {
|
||||
groups.add(group.isEmpty() ? null : JsonUtil.toJson(objectMapper, group));
|
||||
if (!group.isEmpty()) {
|
||||
matched++;
|
||||
}
|
||||
}
|
||||
writes.add(new RespondentWrite(definitions.get(variable).getQid(), groups));
|
||||
}
|
||||
int matchedRespondents = matched;
|
||||
return transaction(project, () -> {
|
||||
// Keep the original empty-row contract even when there are no definitions or responses.
|
||||
derivedRepository.ensureRespondent(project, idkey);
|
||||
for (RespondentWrite write : writes) {
|
||||
if (write.groups().isEmpty()) {
|
||||
derivedRepository.clearRespondentData(project, write.qid(), idkey);
|
||||
} else {
|
||||
for (String group : write.groups()) {
|
||||
// JSON_MODIFY updates only this variable on the current row; never replace DATJSON.
|
||||
derivedRepository.saveData(project, write.qid(), idkey, group);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new DerivedCalculationDto(definitions.size(), matchedRespondents);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private record RespondentWrite(String qid, List<String> groups) {}
|
||||
|
||||
/** Stored derived variable IDs; uploaded response columns with these IDs are not imported. */
|
||||
public List<String> derivedIds(ProjectRefDto project) {
|
||||
return derivedIds(derivedRepository.definitions(project));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
() -> {
|
||||
requireProject(project);
|
||||
// Legacy creates an empty DERIVED_DATA row even if there is no eligible completed
|
||||
// response.
|
||||
derivedRepository.ensureRespondent(project, idkey);
|
||||
var definitions = derivedRepository.definitions(project);
|
||||
var derivedIds = derivedIds(definitions);
|
||||
int matched = 0;
|
||||
for (var definition : definitions) {
|
||||
matched += calculate(project, definition, idkey);
|
||||
matched += calculate(project, definition, null, derivedIds);
|
||||
}
|
||||
return new DerivedCalculationDto(definitions.size(), matched);
|
||||
});
|
||||
}
|
||||
|
||||
private int calculate(ProjectRefDto project, DerivedDefinitionDto definition) {
|
||||
return calculate(project, definition, null);
|
||||
private List<String> derivedIds(List<DerivedDefinitionDto> definitions) {
|
||||
return definitions.stream().map(DerivedDefinitionDto::getQid).toList();
|
||||
}
|
||||
|
||||
private int calculate(ProjectRefDto project, DerivedDefinitionDto definition, String idkey) {
|
||||
private int calculate(
|
||||
ProjectRefDto project,
|
||||
DerivedDefinitionDto definition,
|
||||
String idkey,
|
||||
List<String> derivedIds) {
|
||||
return calculate(project, definition, idkey, derivedIds, null);
|
||||
}
|
||||
|
||||
private int calculate(
|
||||
ProjectRefDto project, DerivedDefinitionDto definition, String idkey,
|
||||
List<String> derivedIds, List<QuestionDto> questions) {
|
||||
validateId(definition.getQid());
|
||||
if (idkey == null) {
|
||||
derivedRepository.clearData(project, definition.getQid());
|
||||
@@ -181,7 +265,8 @@ public class DerivedManagementService {
|
||||
: derivedRepository.respondentResponses(project, idkey);
|
||||
var results =
|
||||
derivedComputationService.calculate(
|
||||
definition, questionService.list(project, idkey == null ? 0 : 1001), data);
|
||||
definition, questions == null ? questionService.list(project, idkey == null ? 0 : 1001) : questions,
|
||||
data, derivedIds);
|
||||
int matched = 0;
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
var group = results.get(i);
|
||||
@@ -235,7 +320,7 @@ public class DerivedManagementService {
|
||||
private <T> T transaction(ProjectRefDto project, Supplier<T> action) {
|
||||
var transactionTemplate =
|
||||
new TransactionTemplate(
|
||||
project.getProjectType() == ProjectType.KON
|
||||
project.projectType() == ProjectType.KON
|
||||
? konTransactionManager
|
||||
: konkiwiTransactionManager);
|
||||
return Objects.requireNonNull(transactionTemplate.execute(status -> action.get()));
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.kri.kart.server.common.consts.KartConstant;
|
||||
import com.kri.kart.server.dto.export.ExportDataDto;
|
||||
import com.kri.kart.server.dto.export.ExportDerivedHeaderDto;
|
||||
import com.kri.kart.server.dto.export.ExportFileDto;
|
||||
import com.kri.kart.server.dto.export.ExportTempFileDto;
|
||||
import com.kri.kart.server.dto.export.ExportGuideDto;
|
||||
import com.kri.kart.server.dto.export.ExportHeaderDto;
|
||||
import com.kri.kart.server.dto.export.ExportTitleDto;
|
||||
@@ -20,6 +21,7 @@ import com.kri.kart.server.persistence.repository.ExportRepository;
|
||||
import com.kri.kart.server.persistence.repository.QuestionRepository;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -128,8 +130,26 @@ public class ExportService {
|
||||
return rows;
|
||||
}
|
||||
|
||||
public ExportFileDto data(
|
||||
ProjectRefDto project, Integer userRole, RawDataExportRequestDto request) {
|
||||
public ExportTempFileDto prepareData(
|
||||
ProjectRefDto project, Integer userRole, RawDataExportRequestDto request) throws IOException {
|
||||
Path path = Files.createTempFile("kart-data-export-", ".xlsx");
|
||||
try {
|
||||
try (OutputStream output = Files.newOutputStream(path)) {
|
||||
data(project, userRole, request, output);
|
||||
}
|
||||
return new ExportTempFileDto(dataFileName(project), path);
|
||||
} catch (IOException | RuntimeException | Error error) {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException cleanupError) {
|
||||
error.addSuppressed(cleanupError);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
void data(
|
||||
ProjectRefDto project, Integer userRole, RawDataExportRequestDto request, OutputStream output) throws IOException {
|
||||
if (!List.of("COMPLETE", "INCOMPLETE").contains(Objects.toString(request.getType(), ""))
|
||||
|| (request.getStartDate() == null && request.getEndDate() != null)
|
||||
|| (request.getStartDate() != null
|
||||
@@ -138,37 +158,49 @@ public class ExportService {
|
||||
throw BusinessException.badRequest("다운로드 유형과 날짜 범위를 확인해 주세요.");
|
||||
}
|
||||
Map<String, String> headers = headers(project, userRole);
|
||||
List<Map<String, String>> rows = new ArrayList<>();
|
||||
rows.add(headers); // Row 1 contains storage keys, row 2 contains variable aliases.
|
||||
boolean includeInterviewer = "2".equals(exportRepository.surveyType(project));
|
||||
for (ExportDataDto response : exportRepository.data(project, request, includeInterviewer)) {
|
||||
String dat = response.getDat();
|
||||
if (dat == null || dat.isEmpty()) {
|
||||
continue; // SQL STUFF returns NULL when all response groups are empty.
|
||||
try (var workbook = ExcelMapper.createStreamingWorkbook(100)) {
|
||||
try (var writer = ExcelMapper.openStreamingMapWriter(workbook, new ArrayList<>(headers.keySet()), "DATA", 1)) {
|
||||
writer.append(headers);
|
||||
exportRepository.data(project, request, includeInterviewer, response -> {
|
||||
String dat = response.getDat();
|
||||
if (dat == null || dat.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
JsonNode values = jsonObject(dat.replaceAll("\\\\U\\d*", ""));
|
||||
Map<String, String> row = new LinkedHashMap<>();
|
||||
for (String key : headers.keySet()) {
|
||||
String value = responseValue(response, values, key, includeInterviewer);
|
||||
if (value != null && !value.isEmpty()) {
|
||||
row.put(key, value);
|
||||
}
|
||||
}
|
||||
writer.append(row);
|
||||
});
|
||||
}
|
||||
// Preserve legacy ReplaceUnicodeEmpty after SQL UPPER/FOR XML serialization.
|
||||
JsonNode values = jsonObject(dat.replaceAll("\\\\U\\d*", ""));
|
||||
Map<String, String> row = new LinkedHashMap<>();
|
||||
for (String key : headers.keySet()) {
|
||||
row.put(key, responseValue(response, values, key, includeInterviewer));
|
||||
// Metadata is bounded by the questionnaire; respondent rows are never accumulated.
|
||||
try (var writer = ExcelMapper.openStreamingMapWriter(workbook,
|
||||
List.of("문항 타입", "문항 / 보기번호", "내용", "VALUE LABEL", "VARIABLE LABEL"), "GUIDE", 1)) {
|
||||
for (ExportGuideDto guide : guideRows(project)) {
|
||||
Map<String, String> row = new LinkedHashMap<>();
|
||||
row.put("문항 타입", guide.questionType());
|
||||
row.put("문항 / 보기번호", guide.variable());
|
||||
row.put("내용", guide.content());
|
||||
row.put("VALUE LABEL", guide.valueLabel());
|
||||
row.put("VARIABLE LABEL", guide.variableLabel());
|
||||
row.values().removeIf(value -> value == null || value.isEmpty());
|
||||
writer.append(row);
|
||||
}
|
||||
}
|
||||
rows.add(row);
|
||||
}
|
||||
Workbook workbook = ExcelMapper.writeFromMapList(rows, "DATA");
|
||||
try {
|
||||
ExcelMapper.appendSheetToWorkbook(
|
||||
workbook, guideRows(project), ExportGuideDto.class, "GUIDE", 1);
|
||||
return file("DATA", project, workbook);
|
||||
} catch (RuntimeException exception) {
|
||||
try {
|
||||
workbook.close();
|
||||
} catch (IOException closeException) {
|
||||
exception.addSuppressed(closeException);
|
||||
}
|
||||
throw exception;
|
||||
workbook.write(output);
|
||||
}
|
||||
}
|
||||
|
||||
public String dataFileName(ProjectRefDto project) {
|
||||
return "[DATA]" + project.pkey() + "_"
|
||||
+ DateTimeUtil.nowKstLocalDateTime().format(FILE_TIMESTAMP) + ".xlsx";
|
||||
}
|
||||
|
||||
private String responseValue(
|
||||
ExportDataDto response, JsonNode values, String key, boolean includeInterviewer) {
|
||||
// Fixed SQL columns take precedence; IDKEY remains the value embedded in DAT.
|
||||
@@ -326,7 +358,7 @@ public class ExportService {
|
||||
"["
|
||||
+ prefix
|
||||
+ "]"
|
||||
+ project.getPkey()
|
||||
+ project.pkey()
|
||||
+ "_"
|
||||
+ DateTimeUtil.nowKstLocalDateTime().format(FILE_TIMESTAMP)
|
||||
+ ".xlsx";
|
||||
|
||||
@@ -33,6 +33,7 @@ public class ImportService {
|
||||
private final QuestionImportService questionImportService;
|
||||
private final ResponseImportService responseImportService;
|
||||
private final UploadArchiveService uploadArchiveService;
|
||||
private final DerivedManagementService derivedManagementService;
|
||||
private final LogService logService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final PlatformTransactionManager konTransactionManager;
|
||||
@@ -45,6 +46,7 @@ public class ImportService {
|
||||
QuestionImportService questionImportService,
|
||||
ResponseImportService responseImportService,
|
||||
UploadArchiveService uploadArchiveService,
|
||||
DerivedManagementService derivedManagementService,
|
||||
LogService logService,
|
||||
ObjectMapper objectMapper,
|
||||
@Qualifier("konTransactionManager") PlatformTransactionManager konTransactionManager,
|
||||
@@ -56,6 +58,7 @@ public class ImportService {
|
||||
this.questionImportService = questionImportService;
|
||||
this.responseImportService = responseImportService;
|
||||
this.uploadArchiveService = uploadArchiveService;
|
||||
this.derivedManagementService = derivedManagementService;
|
||||
this.logService = logService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.konTransactionManager = konTransactionManager;
|
||||
@@ -72,10 +75,10 @@ public class ImportService {
|
||||
requireProject(project);
|
||||
importRepository.resetTitles(project);
|
||||
int affected = 0;
|
||||
for (var row : table.getRows()) {
|
||||
for (var row : table.rows()) {
|
||||
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()))
|
||||
.map(question -> question.getQid().split("_", -1)[0])
|
||||
.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 archived = importRepository.archiveCompleted(project);
|
||||
for (var response : responses) {
|
||||
requireOne(importRepository.response(project, response));
|
||||
}
|
||||
derivedManagementService.recalculateAfterImport(project);
|
||||
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) {
|
||||
var manager =
|
||||
project.getProjectType() == ProjectType.KON
|
||||
project.projectType() == ProjectType.KON
|
||||
? konTransactionManager
|
||||
: konkiwiTransactionManager;
|
||||
return Objects.requireNonNull(new TransactionTemplate(manager).execute(status -> action.get()));
|
||||
|
||||
@@ -44,8 +44,8 @@ public class LogService {
|
||||
ProjectRefDto project, String title, JsonNode content, RequestUserContext ctx) {
|
||||
var pageInfo = objectMapper.createObjectNode();
|
||||
// The existing frontend calls the v2 endpoint, which stores projectCode rather than PKEY.
|
||||
pageInfo.put("projectCode", project.getPkey());
|
||||
pageInfo.put("projectType", project.getProjectType().getCode());
|
||||
pageInfo.put("projectCode", project.pkey());
|
||||
pageInfo.put("projectType", project.projectType().getCode());
|
||||
pageInfo.put("LOGTITLE", title);
|
||||
pageInfo.set("LOGCONTENT", normalizeContent(content));
|
||||
try {
|
||||
@@ -64,7 +64,7 @@ public class LogService {
|
||||
if (projectType == null || !hasKey) {
|
||||
throw BusinessException.badRequest("프로젝트 유형과 키는 함께 입력하거나 모두 생략해 주세요.");
|
||||
}
|
||||
return new ProjectRefDto(projectType, pkey).getPkey();
|
||||
return new ProjectRefDto(projectType, pkey).pkey();
|
||||
}
|
||||
|
||||
private JsonNode normalizeContent(JsonNode content) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.common.external.intranet.IntranetExtensionApiClient;
|
||||
import com.kri.kart.server.dto.project.ProjectLinkSearchDto;
|
||||
import com.kri.kart.server.dto.project.ProjectListDto;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.project.ProjectSummaryDto;
|
||||
import com.kri.kart.server.persistence.repository.ProjectRepository;
|
||||
import java.util.ArrayList;
|
||||
@@ -26,31 +27,31 @@ public class ProjectService {
|
||||
|
||||
public List<ProjectListDto> list(ProjectLinkSearchDto search, RequestUserContext ctx) {
|
||||
requireIdentity(ctx);
|
||||
boolean hasKeyword = search.getKeyword() != null && !search.getKeyword().isEmpty();
|
||||
if (search.getProjectType() == null
|
||||
&& search.getIntranetCode() == null
|
||||
&& search.getUserTeam() == null
|
||||
boolean hasKeyword = search.keyword() != null && !search.keyword().isEmpty();
|
||||
if (search.projectType() == null
|
||||
&& search.intranetCode() == null
|
||||
&& search.userTeam() == null
|
||||
&& !hasKeyword) {
|
||||
return list(ctx);
|
||||
}
|
||||
if (search.getProjectType() == null
|
||||
|| search.getIntranetCode() == null
|
||||
|| search.getUserTeam() == null) {
|
||||
if (search.projectType() == null
|
||||
|| search.intranetCode() == null
|
||||
|| search.userTeam() == null) {
|
||||
throw BusinessException.badRequest("연동 조회에는 projectType/intranetCode/userTeam을 함께 입력해 주세요.");
|
||||
}
|
||||
String intranetCode = search.getIntranetCode().split("_", -1)[0];
|
||||
String keyword = search.getKeyword() == null ? "" : search.getKeyword();
|
||||
String intranetCode = search.intranetCode().split("_", -1)[0];
|
||||
String keyword = search.keyword() == null ? "" : search.keyword();
|
||||
var rows =
|
||||
projectRepository.linkedList(
|
||||
search.getProjectType(),
|
||||
search.projectType(),
|
||||
intranetCode,
|
||||
search.getUserTeam(),
|
||||
search.userTeam(),
|
||||
keyword,
|
||||
ctx.getUserRole(),
|
||||
ctx.getUserTeam(),
|
||||
assignedPkeys(ctx));
|
||||
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));
|
||||
}
|
||||
return rows;
|
||||
@@ -112,6 +113,17 @@ public class ProjectService {
|
||||
return selected;
|
||||
}
|
||||
|
||||
public void requireAccess(ProjectRefDto project, RequestUserContext ctx) {
|
||||
requireIdentity(ctx);
|
||||
if (StringUtil.normalizeBlank(ctx.getUserId()) == null) {
|
||||
throw BusinessException.unauthorized("PROJECT_IDENTITY_REQUIRED", "프로젝트 접근 인증 정보가 부족합니다.");
|
||||
}
|
||||
if (!projectRepository.hasAccess(
|
||||
project, ctx.getUserRole(), ctx.getUserTeam(), assignedPkeys(ctx))) {
|
||||
throw BusinessException.forbidden("PROJECT_ACCESS_DENIED", "프로젝트에 접근할 권한이 없습니다.");
|
||||
}
|
||||
}
|
||||
|
||||
private void requireIdentity(RequestUserContext ctx) {
|
||||
if (ctx.getUserRole() == null
|
||||
|| (!Integer.valueOf(1001).equals(ctx.getUserRole())
|
||||
|
||||
@@ -24,7 +24,7 @@ public class QuestionService {
|
||||
|
||||
public List<QuestionDto> list(ProjectRefDto project, Integer userRole) {
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package com.kri.kart.server.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kri.common.feature.json.JsonUtil;
|
||||
import com.kri.common.feature.util.StringUtil;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.quota.PreparedQuotaDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaResultDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaResultRequestDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaSetDto;
|
||||
@@ -15,14 +13,11 @@ import com.kri.kart.server.dto.statistics.StatisticsRequestDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsResponseDto;
|
||||
import com.kri.kart.server.persistence.repository.QuotaRepository;
|
||||
import com.kri.kart.server.service.quota.QuotaComputationService;
|
||||
import com.kri.kart.server.service.statistics.LegacyFilterService;
|
||||
import com.kri.kart.server.service.quota.QuotaPreparationService;
|
||||
import com.kri.kart.server.service.statistics.StatisticsAggregationService;
|
||||
import com.kri.kart.server.service.statistics.StatisticsDimension;
|
||||
import com.kri.kart.server.service.statistics.StatisticsDimensionService;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -35,7 +30,7 @@ public class QuotaService {
|
||||
private final StatisticsService statisticsService;
|
||||
private final StatisticsAggregationService statisticsAggregationService;
|
||||
private final StatisticsDimensionService statisticsDimensionService;
|
||||
private final LegacyFilterService legacyFilterService;
|
||||
private final QuotaPreparationService quotaPreparationService;
|
||||
private final QuotaComputationService quotaComputationService;
|
||||
private final LogService logService;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -57,44 +52,14 @@ public class QuotaService {
|
||||
content.put("QSTITLE", quotaSet.getQsTitle());
|
||||
content.put("QSJSON", quotaSet.getQsJson());
|
||||
logService.writeSiteLog(project, "QUOTA VIEW", content, ctx);
|
||||
JsonNode settings;
|
||||
try {
|
||||
settings = JsonUtil.fromJson(objectMapper, quotaSet.getQsJson(), JsonNode.class);
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw invalidSettings();
|
||||
}
|
||||
if (settings == null
|
||||
|| !settings.isObject()
|
||||
|| !settings.path("ROW").isArray()
|
||||
|| !settings.path("COL").isArray()) {
|
||||
throw invalidSettings();
|
||||
}
|
||||
String index =
|
||||
settings.path("ROW").isEmpty() ? "" : dimension(settings.path("ROW").get(0), true);
|
||||
List<String> columns = new ArrayList<>();
|
||||
for (JsonNode column : settings.path("COL")) {
|
||||
columns.add(dimension(column, false));
|
||||
}
|
||||
List<List<String>> banners =
|
||||
columns.isEmpty()
|
||||
? List.of()
|
||||
: Arrays.stream(String.join("|", columns).split(",", -1))
|
||||
.map(group -> Arrays.stream(group.split("\\|", -1)).map(String::trim).toList())
|
||||
.toList();
|
||||
if (banners.stream()
|
||||
.anyMatch(
|
||||
group ->
|
||||
group.isEmpty() || group.size() > 5 || group.stream().anyMatch(String::isEmpty))) {
|
||||
throw invalidSettings();
|
||||
}
|
||||
PreparedQuotaDto settings =
|
||||
quotaPreparationService.settings(quotaSet.getQsJson());
|
||||
String index = settings.index();
|
||||
List<List<String>> banners = settings.banners();
|
||||
StatisticsRequestDto statisticsRequest = new StatisticsRequestDto();
|
||||
statisticsRequest.setIndex(index);
|
||||
statisticsRequest.setBanners(banners);
|
||||
try {
|
||||
statisticsRequest.setFilter(legacyFilterService.parse(settings.get("FILTER")));
|
||||
} catch (BusinessException exception) {
|
||||
throw BusinessException.validationError("QUOTA_FILTER_INVALID", "저장된 쿼터 필터 형식을 확인해 주세요.");
|
||||
}
|
||||
statisticsRequest.setFilter(settings.filter());
|
||||
statisticsRequest.setDataScope(request.getDataScope());
|
||||
statisticsRequest.setStartDate(request.getStartDate());
|
||||
statisticsRequest.setEndDate(request.getEndDate());
|
||||
@@ -105,7 +70,7 @@ public class QuotaService {
|
||||
StatisticsDimension indexDimension =
|
||||
statisticsDimensionService.resolve(
|
||||
index, statisticsBatch.questions(), statisticsBatch.responses());
|
||||
if ("text".equals(indexDimension.getQuestion().getQtype())
|
||||
if ("text".equals(indexDimension.getQuestionType())
|
||||
&& !indexDimension.isAttributeProjection()) {
|
||||
throw BusinessException.validationError(
|
||||
"QUOTA_TEXT_UNSUPPORTED", "주관식 문자 문항은 쿼터 완료수 표로 집계할 수 없습니다.");
|
||||
@@ -121,26 +86,8 @@ public class QuotaService {
|
||||
matchIndex,
|
||||
banners,
|
||||
table,
|
||||
quotaRepository.quotaEntries(project, quotaOrder));
|
||||
quotaPreparationService.entries(quotaRepository.quotaEntries(project, quotaOrder)));
|
||||
return result;
|
||||
}
|
||||
|
||||
private String dimension(JsonNode value, boolean allowEmpty) {
|
||||
if (!value.isTextual()) {
|
||||
throw invalidSettings();
|
||||
}
|
||||
String dimension = StringUtil.normalizeBlank(value.asText());
|
||||
if (dimension == null) {
|
||||
if (allowEmpty) {
|
||||
return "";
|
||||
}
|
||||
throw invalidSettings();
|
||||
}
|
||||
return dimension.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private BusinessException invalidSettings() {
|
||||
return BusinessException.validationError(
|
||||
"QUOTA_CONFIGURATION_INVALID", "저장된 쿼터 ROW/COL 설정을 확인해 주세요.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,13 +40,13 @@ public class ShareLinkService {
|
||||
@Transactional(transactionManager = "kartTransactionManager")
|
||||
public ShareLinkDto create(
|
||||
ProjectRefDto project, ShareLinkRequestDto request, RequestUserContext ctx) {
|
||||
String path = allowedUrl(request.getRealUrl());
|
||||
String path = allowedUrl(request.realUrl());
|
||||
String title = requireProject(project);
|
||||
ShareLinkRecordDto candidate = new ShareLinkRecordDto();
|
||||
candidate.setPkey(project.getPkey());
|
||||
candidate.setProjectType(project.getProjectType().getCode());
|
||||
candidate.setPkey(project.pkey());
|
||||
candidate.setProjectType(project.projectType().getCode());
|
||||
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.setProjectTitle(title);
|
||||
// Ordinary legacy users share REPORT ownership, preserving existing URL reuse.
|
||||
@@ -76,8 +76,8 @@ public class ShareLinkService {
|
||||
}
|
||||
var content = objectMapper.createObjectNode();
|
||||
content.put("REAL_URI", path);
|
||||
content.put("MODE", request.getMode());
|
||||
content.put("COPY_URI", link.getUrl());
|
||||
content.put("MODE", request.mode());
|
||||
content.put("COPY_URI", link.url());
|
||||
logService.writeSiteLog(project, "URL Copy", content, ctx);
|
||||
return link;
|
||||
}
|
||||
@@ -90,7 +90,7 @@ public class ShareLinkService {
|
||||
public ExternalLoginResponseDto login(String urlKey, String clientIp) {
|
||||
ShareLinkRecordDto stored = record(urlKey);
|
||||
ShareLinkDto link = resolve(stored);
|
||||
String userId = KartConstant.EXTERNAL_USER_PREFIX + link.getUrlKey();
|
||||
String userId = KartConstant.EXTERNAL_USER_PREFIX + link.urlKey();
|
||||
JwtUserClaimsDto user =
|
||||
JwtUserClaimsDto.builder()
|
||||
.userId(userId)
|
||||
@@ -98,7 +98,7 @@ public class ShareLinkService {
|
||||
.userTeam(KartConstant.EXTERNAL_TEAM)
|
||||
.userCmpn("")
|
||||
.userRole(
|
||||
link.isPageOnly()
|
||||
link.pageOnly()
|
||||
? KartConstant.EXTERNAL_PAGE_COPY_ROLE
|
||||
: KartConstant.EXTERNAL_URL_COPY_ROLE)
|
||||
.build();
|
||||
@@ -177,8 +177,8 @@ public class ShareLinkService {
|
||||
stored.getUrlKey(),
|
||||
absolute,
|
||||
allowedUrl(stored.getRealUrl()),
|
||||
project.getProjectType(),
|
||||
project.getPkey(),
|
||||
project.projectType(),
|
||||
project.pkey(),
|
||||
stored.getProjectTitle(),
|
||||
stored.getIsPageOnly() == 1);
|
||||
}
|
||||
|
||||
@@ -22,12 +22,10 @@ import com.kri.kart.server.service.statistics.StatisticsDataService;
|
||||
import com.kri.kart.server.service.statistics.StatisticsDimension;
|
||||
import com.kri.kart.server.service.statistics.StatisticsDimensionService;
|
||||
import com.kri.kart.server.service.statistics.StatisticsFilterService;
|
||||
import com.kri.kart.server.service.statistics.StatisticsSourceService;
|
||||
import com.kri.kart.server.service.statistics.StatisticsTextService;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Predicate;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -43,6 +41,7 @@ public class StatisticsService {
|
||||
private final QuestionRepository questionRepository;
|
||||
private final QuestionService questionService;
|
||||
private final StatisticsDataService statisticsDataService;
|
||||
private final StatisticsSourceService statisticsSourceService;
|
||||
private final StatisticsDimensionService statisticsDimensionService;
|
||||
private final StatisticsFilterService statisticsFilterService;
|
||||
private final StatisticsAggregationService statisticsAggregationService;
|
||||
@@ -158,7 +157,7 @@ public class StatisticsService {
|
||||
|
||||
private List<QuestionDto> loadQuestions(ProjectRefDto project, RequestUserContext ctx) {
|
||||
boolean includeProfileQuestions =
|
||||
project.getProjectType() == ProjectType.KIWI
|
||||
project.projectType() == ProjectType.KIWI
|
||||
&& Integer.valueOf(KartConstant.PROFILE_QUESTION_ROLE).equals(ctx.getUserRole());
|
||||
return questionService.organize(questionRepository.list(project, includeProfileQuestions));
|
||||
}
|
||||
@@ -188,7 +187,7 @@ public class StatisticsService {
|
||||
needsProfileResponses(project, requests, sharedRequest, questions);
|
||||
// Query the union of all storage roots once; calculate() narrows it again for each index.
|
||||
List<String> storageRoots =
|
||||
requests.stream().flatMap(request -> storageRoots(request).stream()).distinct().toList();
|
||||
requests.stream().flatMap(request -> statisticsSourceService.storageRoots(request).stream()).distinct().toList();
|
||||
List<StatisticsDataDto> data =
|
||||
statisticsRepository.data(project, sharedRequest, includeProfileResponses, storageRoots);
|
||||
return statisticsDataService.normalize(data).stream().filter(filter).toList();
|
||||
@@ -200,11 +199,11 @@ public class StatisticsService {
|
||||
List<StatisticsRequestDto> requests,
|
||||
StatisticsRequestDto sharedRequest,
|
||||
List<QuestionDto> questions) {
|
||||
if (project.getProjectType() != ProjectType.KIWI) {
|
||||
if (project.projectType() != ProjectType.KIWI) {
|
||||
return false;
|
||||
}
|
||||
return requests.stream().anyMatch(request -> isProfileId(request.getIndex()))
|
||||
|| sharedRequest.getBanners().stream().flatMap(List::stream).anyMatch(this::isProfileId)
|
||||
return requests.stream().anyMatch(request -> statisticsSourceService.isProfileId(request.getIndex()))
|
||||
|| sharedRequest.getBanners().stream().flatMap(List::stream).anyMatch(statisticsSourceService::isProfileId)
|
||||
|| filterUsesProfile(sharedRequest.getFilter(), questions);
|
||||
}
|
||||
|
||||
@@ -213,25 +212,17 @@ public class StatisticsService {
|
||||
return false;
|
||||
}
|
||||
if (filter.getDimensionId() != null
|
||||
&& isProfileId(statisticsFilterService.resolveQid(filter, questions))) {
|
||||
&& statisticsSourceService.isProfileId(statisticsFilterService.resolveQid(filter, questions))) {
|
||||
return true;
|
||||
}
|
||||
return filter.getChildren().stream().anyMatch(child -> filterUsesProfile(child, questions));
|
||||
}
|
||||
|
||||
private boolean isProfileId(String id) {
|
||||
String normalized = StringUtil.normalizeBlank(id);
|
||||
if (normalized == null) {
|
||||
return false;
|
||||
}
|
||||
String upperCaseId = normalized.toUpperCase(Locale.ROOT);
|
||||
return KartConstant.PROFILE_ID_PREFIXES.stream().anyMatch(upperCaseId::startsWith);
|
||||
}
|
||||
|
||||
private StatisticsResponseDto calculate(
|
||||
StatisticsBatchDto statisticsBatch, StatisticsRequestDto request) {
|
||||
List<SurveyResponseDto> responses =
|
||||
withinStorageRoots(statisticsBatch.responses(), storageRoots(request));
|
||||
statisticsSourceService.withinStorageRoots(
|
||||
statisticsBatch.responses(), statisticsSourceService.storageRoots(request));
|
||||
StatisticsDimension index =
|
||||
statisticsDimensionService.resolve(
|
||||
request.getIndex(), statisticsBatch.questions(), responses);
|
||||
@@ -242,34 +233,8 @@ public class StatisticsService {
|
||||
request, statisticsBatch.questions(), responses);
|
||||
}
|
||||
|
||||
/** The shared union query must not add respondents that a single-index query would omit. */
|
||||
private List<SurveyResponseDto> withinStorageRoots(
|
||||
List<SurveyResponseDto> responses, List<String> storageRoots) {
|
||||
Predicate<String> storedUnderRoots =
|
||||
key -> storageRoots.contains(key) || storageRoots.contains(key.split("_")[0]);
|
||||
return responses.stream()
|
||||
.filter(response -> response.values().keySet().stream().anyMatch(storedUnderRoots))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** Storage root keys selected by the original single-index query: index plus banners. */
|
||||
private List<String> storageRoots(StatisticsRequestDto request) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
ids.add(isStandard(request) ? request.getIndex() : KartConstant.TABULATION_STORAGE_ROOT);
|
||||
request.getBanners().forEach(ids::addAll);
|
||||
return ids.stream().map(this::toStorageRoot).distinct().toList();
|
||||
}
|
||||
|
||||
/** e.g. "q1_2#a" -> "Q1": upper-case, drop the attribute projection and keep the root. */
|
||||
private String toStorageRoot(String id) {
|
||||
return Objects.toString(StringUtil.normalizeBlank(id), "")
|
||||
.toUpperCase(Locale.ROOT)
|
||||
.replace(KartConstant.ATTRIBUTE_PROJECTION_SUFFIX, "")
|
||||
.split("_")[0];
|
||||
}
|
||||
|
||||
private boolean isOpenText(StatisticsDimension index) {
|
||||
return "text".equals(index.getQuestion().getQtype()) && !index.isAttributeProjection();
|
||||
return "text".equals(index.getQuestionType()) && !index.isAttributeProjection();
|
||||
}
|
||||
|
||||
private StatisticsResponseDto textAnalysis(
|
||||
@@ -280,11 +245,17 @@ public class StatisticsService {
|
||||
return StatisticsResponseDto.builder()
|
||||
.type("TEXT_ANALYSIS")
|
||||
.questionId(index.getDimensionId())
|
||||
.title(index.getQuestion().getTitle())
|
||||
.title(index.getTitle())
|
||||
.columns(List.of())
|
||||
.headerRows(List.of())
|
||||
.rows(List.of())
|
||||
.words(statisticsTextService.analyze(project, index.getDimensionId(), responses))
|
||||
.words(
|
||||
statisticsTextService.analyze(
|
||||
project,
|
||||
index.getDimensionId(),
|
||||
responses,
|
||||
request.getWordMergeMode(),
|
||||
request.getCompoundNounMaxTokens()))
|
||||
.appliedOptions(request)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -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.StatisticsFilterService;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -29,17 +30,17 @@ public class DerivedComputationService {
|
||||
private final StatisticsFilterService statisticsFilterService;
|
||||
|
||||
public DerivedDefinitionDto definition(DerivedSaveRequestDto request) {
|
||||
JsonNode info = request.getVariableInfo();
|
||||
JsonNode info = request.variableInfo();
|
||||
if (!info.isObject() || info.isEmpty() || info.size() > 1000) {
|
||||
throw invalid();
|
||||
}
|
||||
info.fields().forEachRemaining(entry -> validateRule(entry.getKey(), entry.getValue()));
|
||||
var question = objectMapper.createObjectNode();
|
||||
question.put("variable", request.getVariableId());
|
||||
question.put("variable", request.variableId());
|
||||
question.put("explain", "");
|
||||
question.put("title", request.getVariableTitle());
|
||||
question.put("title", request.variableTitle());
|
||||
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");
|
||||
question.put("qtype", "open");
|
||||
} else {
|
||||
@@ -52,18 +53,42 @@ public class DerivedComputationService {
|
||||
? Integer.toString(info.size())
|
||||
: entry.getKey(),
|
||||
entry.getValue().deepCopy()));
|
||||
dataset.set(request.getVariableType(), labels);
|
||||
question.put("qtype", request.getVariableType());
|
||||
dataset.set(request.variableType(), labels);
|
||||
question.put("qtype", request.variableType());
|
||||
}
|
||||
var definition = new DerivedDefinitionDto();
|
||||
definition.setQid(request.getVariableId());
|
||||
definition.setQid(request.variableId());
|
||||
definition.setDerivedJson(JsonUtil.toJson(objectMapper, info));
|
||||
definition.setQuestionJson(JsonUtil.toJson(objectMapper, question));
|
||||
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(
|
||||
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());
|
||||
String type = object(definition.getQuestionJson()).path("qtype").asText();
|
||||
String qid = definition.getQid();
|
||||
@@ -84,6 +109,7 @@ public class DerivedComputationService {
|
||||
for (DerivedDataDto row : data) {
|
||||
Map<String, String> flat = new LinkedHashMap<>();
|
||||
flatten(object(row.getDatjson()), flat);
|
||||
flat.keySet().removeIf(key -> isDerivedKey(key, derivedIds));
|
||||
if (row.getDerivedJson() != null) {
|
||||
ObjectNode derived = object(row.getDerivedJson());
|
||||
derived.remove(qid);
|
||||
@@ -108,6 +134,37 @@ public class DerivedComputationService {
|
||||
return results;
|
||||
}
|
||||
|
||||
/** Reuse one respondent snapshot, feeding preceding variable results into later conditions. */
|
||||
public List<List<ObjectNode>> calculateRespondent(
|
||||
List<DerivedDefinitionDto> definitions, List<QuestionDto> questions,
|
||||
List<DerivedDataDto> data, Collection<String> derivedIds) {
|
||||
List<DerivedDataDto> working = new ArrayList<>();
|
||||
for (DerivedDataDto row : data) {
|
||||
DerivedDataDto copy = new DerivedDataDto();
|
||||
copy.setIdkey(row.getIdkey());
|
||||
copy.setDatjson(row.getDatjson());
|
||||
copy.setDerivedJson(row.getDerivedJson());
|
||||
working.add(copy);
|
||||
}
|
||||
List<List<ObjectNode>> prepared = new ArrayList<>();
|
||||
for (DerivedDefinitionDto definition : definitions) {
|
||||
List<ObjectNode> groups = calculate(definition, questions, working, derivedIds);
|
||||
prepared.add(groups);
|
||||
for (int row = 0; row < working.size(); row++) {
|
||||
DerivedDataDto response = working.get(row);
|
||||
ObjectNode derived = response.getDerivedJson() == null
|
||||
? objectMapper.createObjectNode() : object(response.getDerivedJson());
|
||||
if (groups.get(row).isEmpty()) {
|
||||
derived.remove(definition.getQid());
|
||||
} else {
|
||||
derived.set(definition.getQid(), groups.get(row));
|
||||
}
|
||||
response.setDerivedJson(JsonUtil.toJson(objectMapper, derived));
|
||||
}
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
|
||||
private void flatten(ObjectNode grouped, Map<String, String> flat) {
|
||||
grouped
|
||||
.fields()
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.kri.kart.server.service.derived;
|
||||
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Serialize duplicate respondent recalculations before reading their response snapshots. */
|
||||
@Component
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class DerivedRecalculationGuard {
|
||||
private final ConcurrentHashMap<RespondentKey, RespondentGate> respondents = new ConcurrentHashMap<>();
|
||||
private final long waitNanos;
|
||||
|
||||
public DerivedRecalculationGuard() {
|
||||
this(TimeUnit.SECONDS.toNanos(10));
|
||||
}
|
||||
|
||||
DerivedRecalculationGuard(long waitNanos) {
|
||||
this.waitNanos = waitNanos;
|
||||
}
|
||||
|
||||
public <T> T execute(ProjectRefDto project, String idkey, Supplier<T> action) {
|
||||
RespondentKey respondent = new RespondentKey(project, idkey);
|
||||
RespondentGate gate = respondents.compute(respondent, (key, current) -> {
|
||||
RespondentGate selected = current == null ? new RespondentGate() : current;
|
||||
selected.users++;
|
||||
return selected;
|
||||
});
|
||||
boolean acquired = false;
|
||||
try {
|
||||
acquired = gate.permit.tryAcquire(waitNanos, TimeUnit.NANOSECONDS);
|
||||
if (!acquired) {
|
||||
throw busy();
|
||||
}
|
||||
return action.get();
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw busy();
|
||||
} finally {
|
||||
if (acquired) {
|
||||
gate.permit.release();
|
||||
}
|
||||
respondents.computeIfPresent(respondent, (key, current) -> --current.users == 0 ? null : current);
|
||||
}
|
||||
}
|
||||
|
||||
private BusinessException busy() {
|
||||
return BusinessException.of(
|
||||
HttpStatus.SERVICE_UNAVAILABLE, "DERIVED_RECALCULATION_BUSY",
|
||||
"파생변수 재계산 요청이 많습니다. 잠시 후 다시 요청해 주세요.");
|
||||
}
|
||||
|
||||
private record RespondentKey(ProjectRefDto project, String idkey) {}
|
||||
|
||||
private static final class RespondentGate {
|
||||
private final Semaphore permit = new Semaphore(1, true);
|
||||
// Accessed only inside ConcurrentHashMap.compute/computeIfPresent for the respondent.
|
||||
private int users;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
package com.kri.kart.server.service.quota;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kri.common.feature.json.JsonUtil;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.kart.server.dto.quota.PreparedQuotaDto.Condition;
|
||||
import com.kri.kart.server.dto.quota.PreparedQuotaDto.Entry;
|
||||
import com.kri.kart.server.dto.quota.QuotaCellDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaEntryDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaResultDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaRowDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaSetDto;
|
||||
@@ -15,18 +13,19 @@ import com.kri.kart.server.dto.statistics.StatisticsRowDto;
|
||||
import com.kri.kart.server.service.statistics.StatisticsArithmetic;
|
||||
import com.kri.kart.server.service.statistics.StatisticsTableService;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class QuotaComputationService {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final QuotaPreparationService quotaPreparationService;
|
||||
private final StatisticsTableService statisticsTableService;
|
||||
|
||||
private record Entry(QuotaEntryDto quotaEntry, JsonNode values) {}
|
||||
|
||||
private record Target(long count, String isUsed, Long quotaId) {}
|
||||
|
||||
public QuotaResultDto compute(
|
||||
@@ -35,100 +34,85 @@ public class QuotaComputationService {
|
||||
String matchIndex,
|
||||
List<List<String>> banners,
|
||||
StatisticsResponseDto table,
|
||||
List<QuotaEntryDto> quotaEntries) {
|
||||
List<Entry> entries =
|
||||
quotaEntries.stream()
|
||||
.map(
|
||||
quotaEntry -> {
|
||||
JsonNode values;
|
||||
try {
|
||||
values =
|
||||
JsonUtil.fromJson(objectMapper, quotaEntry.getQuotaJson(), JsonNode.class);
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw BusinessException.validationError(
|
||||
"QUOTA_DATA_INVALID", "저장된 쿼터 조건을 확인해 주세요.");
|
||||
}
|
||||
if (values == null || !values.isObject()) {
|
||||
throw BusinessException.validationError(
|
||||
"QUOTA_DATA_INVALID", "저장된 쿼터 조건을 확인해 주세요.");
|
||||
}
|
||||
return new Entry(quotaEntry, values);
|
||||
})
|
||||
.toList();
|
||||
List<Entry> entries) {
|
||||
Map<String, List<Condition>> conditions = new HashMap<>();
|
||||
Function<String, List<Condition>> columnConditions =
|
||||
id -> conditions.computeIfAbsent(id, key -> quotaPreparationService.columnConditions(
|
||||
key, banners.isEmpty() ? List.of() : banners.get(0)));
|
||||
List<StatisticsColumnDto> columns = new ArrayList<>();
|
||||
columns.add(table.getColumns().get(0));
|
||||
table.getColumns().stream()
|
||||
.filter(column -> !List.of("LABEL", "TOTAL").contains(column.getKind()))
|
||||
columns.add(table.columns().get(0));
|
||||
table.columns().stream()
|
||||
.filter(column -> !List.of("LABEL", "TOTAL").contains(column.kind()))
|
||||
.forEach(
|
||||
column -> {
|
||||
// Legacy quota removes the question-title header rows and retains choice labels only.
|
||||
List<String> labels = new ArrayList<>();
|
||||
for (int depth = 1; depth < column.getLabels().size(); depth += 2) {
|
||||
labels.add(column.getLabels().get(depth));
|
||||
for (int depth = 1; depth < column.labels().size(); depth += 2) {
|
||||
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(
|
||||
table.getColumns().stream()
|
||||
.filter(column -> "TOTAL".equals(column.getKind()))
|
||||
table.columns().stream()
|
||||
.filter(column -> "TOTAL".equals(column.kind()))
|
||||
.findFirst()
|
||||
.orElseThrow());
|
||||
List<StatisticsRowDto> headers =
|
||||
statisticsTableService.headers("", columns, "MERGED");
|
||||
List<QuotaRowDto> rows = new ArrayList<>();
|
||||
for (StatisticsRowDto row : table.getRows()) {
|
||||
for (StatisticsRowDto row : table.rows()) {
|
||||
List<QuotaCellDto> cells = new ArrayList<>();
|
||||
cells.add(
|
||||
QuotaCellDto.builder()
|
||||
.columnIndex(0)
|
||||
.kind("LABEL")
|
||||
.textValue(
|
||||
"TOTAL".equals(row.getKind()) ? "Total" : row.getCells().get(0).getTextValue())
|
||||
"TOTAL".equals(row.kind()) ? "Total" : row.cells().get(0).getTextValue())
|
||||
.build());
|
||||
long rowTargetSum = 0;
|
||||
for (int columnIndex = 1; columnIndex < columns.size(); columnIndex++) {
|
||||
String columnId = columns.get(columnIndex).getColumnId();
|
||||
String columnId = columns.get(columnIndex).columnId();
|
||||
int sourceColumn = 0;
|
||||
while (!table.getColumns().get(sourceColumn).getColumnId().equals(columnId)) {
|
||||
while (!table.columns().get(sourceColumn).columnId().equals(columnId)) {
|
||||
sourceColumn++;
|
||||
}
|
||||
Long complete = row.getCells().get(sourceColumn).getCount();
|
||||
Long complete = row.cells().get(sourceColumn).getCount();
|
||||
if (complete == null) {
|
||||
throw BusinessException.validationError(
|
||||
"QUOTA_STATISTIC_UNSUPPORTED", "통계량 문항은 기존 쿼터 집계에서 지원하지 않습니다.");
|
||||
}
|
||||
Target target =
|
||||
target(
|
||||
entries, row, matchIndex, columnId, banners.isEmpty() ? List.of() : banners.get(0));
|
||||
entries, row, matchIndex, columnConditions, columnId);
|
||||
rowTargetSum += target.count();
|
||||
cells.add(cell(columnIndex, complete, target));
|
||||
}
|
||||
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 =
|
||||
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) {
|
||||
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++) {
|
||||
long complete = 0;
|
||||
for (QuotaRowDto row : rows) {
|
||||
if (!"TOTAL".equals(row.getKind())) {
|
||||
complete += row.getCells().get(columnIndex).getComplete();
|
||||
if (!"TOTAL".equals(row.kind())) {
|
||||
complete += row.cells().get(columnIndex).complete();
|
||||
}
|
||||
}
|
||||
QuotaCellDto original = total.getCells().get(columnIndex);
|
||||
QuotaCellDto original = total.cells().get(columnIndex);
|
||||
cells.add(
|
||||
cell(
|
||||
columnIndex,
|
||||
complete,
|
||||
new Target(original.getTarget(), original.getIsUsed(), original.getQuotaId())));
|
||||
new Target(original.target(), original.isUsed(), original.quotaId())));
|
||||
}
|
||||
rows.remove(total);
|
||||
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<>();
|
||||
@@ -136,7 +120,7 @@ public class QuotaComputationService {
|
||||
QuotaRowDto row = rows.get(rowIndex);
|
||||
positionedRows.add(
|
||||
new QuotaRowDto(
|
||||
headers.size() + rowIndex, row.getRowId(), row.getKind(), row.getCells()));
|
||||
headers.size() + rowIndex, row.rowId(), row.kind(), row.cells()));
|
||||
}
|
||||
return QuotaResultDto.builder()
|
||||
.quotaSetId(quotaSet.getId())
|
||||
@@ -151,46 +135,30 @@ public class QuotaComputationService {
|
||||
}
|
||||
|
||||
private Target target(
|
||||
List<Entry> entries, StatisticsRowDto row, String index, String columnId, List<String> banners) {
|
||||
List<Entry> entries,
|
||||
StatisticsRowDto row, String index,
|
||||
Function<String, List<Condition>> columnConditions,
|
||||
String columnId) {
|
||||
List<Entry> matching = entries;
|
||||
if (!index.isEmpty()
|
||||
&& StatisticsArithmetic.number(row.getRowId()) != null
|
||||
&& !"TOTAL".equals(row.getKind())) {
|
||||
&& StatisticsArithmetic.number(row.rowId()) != null
|
||||
&& !"TOTAL".equals(row.kind())) {
|
||||
matching =
|
||||
matching.stream()
|
||||
.filter(entry -> value(entry.values(), index).equals(row.getRowId()))
|
||||
.filter(entry -> entry.value().apply(index).equals(row.rowId()))
|
||||
.toList();
|
||||
}
|
||||
if (!"i".equals(columnId)) {
|
||||
String[] values = columnId.split("_");
|
||||
if (values.length - 1 > banners.size()) {
|
||||
throw BusinessException.validationError("QUOTA_COLUMNS_INVALID", "쿼터 배너와 집계 열이 일치하지 않습니다.");
|
||||
}
|
||||
for (int depth = 1; depth < values.length; depth++) {
|
||||
String banner = banners.get(depth - 1);
|
||||
String choice = values[depth];
|
||||
matching =
|
||||
matching.stream()
|
||||
.filter(entry -> value(entry.values(), banner).equals(choice))
|
||||
.toList();
|
||||
}
|
||||
for (Condition condition : columnConditions.apply(columnId)) {
|
||||
matching = matching.stream()
|
||||
.filter(entry -> entry.value().apply(condition.dimension()).equals(condition.choice())).toList();
|
||||
}
|
||||
long count =
|
||||
matching.stream()
|
||||
.map(Entry::quotaEntry)
|
||||
.mapToLong(entry -> entry.getOriCnt() == null ? 0 : entry.getOriCnt())
|
||||
.mapToLong(entry -> entry.target() == null ? 0 : entry.target())
|
||||
.sum();
|
||||
QuotaEntryDto only = matching.size() == 1 ? matching.get(0).quotaEntry() : null;
|
||||
Entry only = matching.size() == 1 ? matching.get(0) : null;
|
||||
return new Target(
|
||||
count, only == null ? null : only.getIsUse(), only == null ? null : only.getId());
|
||||
}
|
||||
|
||||
private String value(JsonNode values, String key) {
|
||||
JsonNode value = values.get(key);
|
||||
if (value == null || value.isNull() || !value.isValueNode()) {
|
||||
throw BusinessException.validationError("QUOTA_DATA_INVALID", "쿼터 조건에 필요한 문항 값이 없습니다.");
|
||||
}
|
||||
return value.asText();
|
||||
count, only == null ? null : only.isUsed(), only == null ? null : only.quotaId());
|
||||
}
|
||||
|
||||
private QuotaCellDto cell(int columnIndex, long complete, Target target) {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.kri.kart.server.service.quota;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kri.common.feature.json.JsonUtil;
|
||||
import com.kri.common.feature.util.StringUtil;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.kart.server.dto.quota.PreparedQuotaDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaEntryDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsFilterDto;
|
||||
import com.kri.kart.server.service.statistics.LegacyFilterService;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** Interprets saved quota formats without changing target/error semantics. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class QuotaPreparationService {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final LegacyFilterService legacyFilterService;
|
||||
|
||||
public PreparedQuotaDto settings(String json) {
|
||||
JsonNode settings;
|
||||
try {
|
||||
settings = JsonUtil.fromJson(objectMapper, json, JsonNode.class);
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw invalidSettings();
|
||||
}
|
||||
if (settings == null
|
||||
|| !settings.isObject()
|
||||
|| !settings.path("ROW").isArray()
|
||||
|| !settings.path("COL").isArray()) {
|
||||
throw invalidSettings();
|
||||
}
|
||||
String index =
|
||||
settings.path("ROW").isEmpty() ? "" : dimension(settings.path("ROW").get(0), true);
|
||||
List<String> columns = new ArrayList<>();
|
||||
for (JsonNode column : settings.path("COL")) {
|
||||
columns.add(dimension(column, false));
|
||||
}
|
||||
List<List<String>> banners =
|
||||
columns.isEmpty()
|
||||
? List.of()
|
||||
: Arrays.stream(String.join("|", columns).split(",", -1))
|
||||
.map(group -> Arrays.stream(group.split("\\|", -1)).map(String::trim).toList())
|
||||
.toList();
|
||||
if (banners.stream()
|
||||
.anyMatch(
|
||||
group ->
|
||||
group.isEmpty() || group.size() > 5 || group.stream().anyMatch(String::isEmpty))) {
|
||||
throw invalidSettings();
|
||||
}
|
||||
StatisticsFilterDto filter;
|
||||
try {
|
||||
filter = legacyFilterService.parse(settings.get("FILTER"));
|
||||
} catch (BusinessException exception) {
|
||||
throw BusinessException.validationError("QUOTA_FILTER_INVALID", "저장된 쿼터 필터 형식을 확인해 주세요.");
|
||||
}
|
||||
return new PreparedQuotaDto(index, banners, filter);
|
||||
}
|
||||
|
||||
public List<PreparedQuotaDto.Entry> entries(List<QuotaEntryDto> quotaEntries) {
|
||||
return quotaEntries.stream()
|
||||
.map(
|
||||
quotaEntry -> {
|
||||
JsonNode values;
|
||||
try {
|
||||
values =
|
||||
JsonUtil.fromJson(objectMapper, quotaEntry.getQuotaJson(), JsonNode.class);
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw BusinessException.validationError(
|
||||
"QUOTA_DATA_INVALID", "저장된 쿼터 조건을 확인해 주세요.");
|
||||
}
|
||||
if (values == null || !values.isObject()) {
|
||||
throw BusinessException.validationError(
|
||||
"QUOTA_DATA_INVALID", "저장된 쿼터 조건을 확인해 주세요.");
|
||||
}
|
||||
return new PreparedQuotaDto.Entry(
|
||||
quotaEntry.getOriCnt(), quotaEntry.getIsUse(), quotaEntry.getId(),
|
||||
key -> value(values, key));
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<PreparedQuotaDto.Condition> columnConditions(String columnId, List<String> banners) {
|
||||
if ("i".equals(columnId)) {
|
||||
return List.of();
|
||||
}
|
||||
String[] values = columnId.split("_");
|
||||
if (values.length - 1 > banners.size()) {
|
||||
throw BusinessException.validationError("QUOTA_COLUMNS_INVALID", "쿼터 배너와 집계 열이 일치하지 않습니다.");
|
||||
}
|
||||
List<PreparedQuotaDto.Condition> conditions = new ArrayList<>();
|
||||
for (int depth = 1; depth < values.length; depth++) {
|
||||
conditions.add(new PreparedQuotaDto.Condition(banners.get(depth - 1), values[depth]));
|
||||
}
|
||||
return conditions;
|
||||
}
|
||||
|
||||
private String value(JsonNode values, String key) {
|
||||
JsonNode value = values.get(key);
|
||||
if (value == null || value.isNull() || !value.isValueNode()) {
|
||||
throw BusinessException.validationError("QUOTA_DATA_INVALID", "쿼터 조건에 필요한 문항 값이 없습니다.");
|
||||
}
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
private String dimension(JsonNode value, boolean allowEmpty) {
|
||||
if (!value.isTextual()) {
|
||||
throw invalidSettings();
|
||||
}
|
||||
String dimension = StringUtil.normalizeBlank(value.asText());
|
||||
if (dimension == null) {
|
||||
if (allowEmpty) {
|
||||
return "";
|
||||
}
|
||||
throw invalidSettings();
|
||||
}
|
||||
return dimension.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private BusinessException invalidSettings() {
|
||||
return BusinessException.validationError(
|
||||
"QUOTA_CONFIGURATION_INVALID", "저장된 쿼터 ROW/COL 설정을 확인해 주세요.");
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public class LegacyProjectKeyService {
|
||||
|
||||
public String encode(ProjectRefDto project) {
|
||||
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));
|
||||
return URLEncoder.encode(Base64.getEncoder().encodeToString(cipher), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@@ -1,22 +1,39 @@
|
||||
package com.kri.kart.server.service.statistics;
|
||||
|
||||
import com.kri.common.feature.util.StringUtil;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.kart.server.dto.statistics.NlpDictionaryWordDto;
|
||||
import com.kri.kart.server.dto.statistics.NlpTokenDto;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import kr.pe.bab2min.Kiwi;
|
||||
import kr.pe.bab2min.KiwiBuilder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class KiwiNlpService {
|
||||
// Same as kiwipiepy's default typo cost threshold.
|
||||
private static final float TYPO_COST_THRESHOLD = 2.5f;
|
||||
private static final Set<String> COMPOUND_NOUN_TAGS = Set.of("NNG", "NNP", "SL");
|
||||
private static final Set<String> NOUN_AFFIX_TAGS = Set.of("SL", "SH", "XPN", "XSN");
|
||||
// Above every user dictionary score (10/50/100) so a synonym always wins.
|
||||
private static final float SYNONYM_SCORE = 200f;
|
||||
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
|
||||
|
||||
private final Path modelDirectory;
|
||||
|
||||
public KiwiNlpService(
|
||||
@@ -24,34 +41,76 @@ public class KiwiNlpService {
|
||||
this.modelDirectory = Path.of(modelDirectory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the existing behavior: synonym rows (with SOURCE_TEXT) are ignored and there is no
|
||||
* compound-noun or noun-affix joining.
|
||||
*/
|
||||
public List<NlpTokenDto> tokenize(List<String> texts, List<NlpDictionaryWordDto> dictionary) {
|
||||
List<NlpDictionaryWordDto> words =
|
||||
dictionary.stream().filter(word -> !isSynonymRow(word)).toList();
|
||||
return tokenize(texts, words, List.of(), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokenizes texts with REPORT_NLP_WORD rows: a row with SOURCE_TEXT is a synonym that replaces
|
||||
* SOURCE_TEXT with WORD_TEXT/WORD_TAG before anything else, any other row is a user word. When
|
||||
* {@code compoundNounMaxTokens} is 2 or more, noun prefixes/suffixes are joined and adjacent
|
||||
* nouns are merged into one compound noun (see {@link #joinCompoundNouns}).
|
||||
*/
|
||||
public List<NlpTokenDto> tokenize(
|
||||
List<String> texts, List<NlpDictionaryWordDto> dictionary, int compoundNounMaxTokens) {
|
||||
List<NlpDictionaryWordDto> words = new ArrayList<>();
|
||||
List<NlpDictionaryWordDto> synonyms = new ArrayList<>();
|
||||
for (NlpDictionaryWordDto word : dictionary) {
|
||||
(isSynonymRow(word) ? synonyms : words).add(word);
|
||||
}
|
||||
return tokenize(texts, words, synonyms, compoundNounMaxTokens);
|
||||
}
|
||||
|
||||
private static boolean isSynonymRow(NlpDictionaryWordDto word) {
|
||||
return StringUtil.normalizeBlank(word.getSourceText()) != null;
|
||||
}
|
||||
|
||||
private List<NlpTokenDto> tokenize(
|
||||
List<String> texts,
|
||||
List<NlpDictionaryWordDto> dictionary,
|
||||
List<NlpDictionaryWordDto> synonyms,
|
||||
int compoundNounMaxTokens) {
|
||||
if (texts.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
if (!Files.isRegularFile(modelDirectory.resolve("cong.mdl"))) {
|
||||
throw unavailable();
|
||||
}
|
||||
Map<String, Byte> tags = tags();
|
||||
List<NlpTokenDto> result = new ArrayList<>();
|
||||
int options = KiwiBuilder.BuildOption.loadDefaultDict | KiwiBuilder.BuildOption.loadTypoDict;
|
||||
// Use the user-approved latest model; retain dictionary, allomorph and typo-processing rules.
|
||||
// Kiwi defaults: allomorph integration plus default, typo and multi-word dictionaries.
|
||||
int options = KiwiBuilder.BuildOption.default_;
|
||||
try (KiwiBuilder kiwiBuilder =
|
||||
new KiwiBuilder(modelDirectory.toString(), 1, options, KiwiBuilder.ModelType.cong)) {
|
||||
for (NlpDictionaryWordDto word : dictionary) {
|
||||
Byte tag = tags.get(word.getWordTag());
|
||||
if (tag != null && word.getWordText() != null && word.getWordScore() != null) {
|
||||
try {
|
||||
kiwiBuilder.addWord(word.getWordText(), tag, word.getWordScore());
|
||||
} catch (RuntimeException ignored) {
|
||||
// Existing dictionary registration ignores an individually invalid word.
|
||||
}
|
||||
}
|
||||
new KiwiBuilder(modelDirectory.toString(), 1, options, KiwiBuilder.ModelType.cong);
|
||||
KiwiBuilder.PreparedTypoTransformer typoTransformer =
|
||||
KiwiBuilder.basicTypoSetWithContinual.prepare()) {
|
||||
// User words and synonym targets are never merged with their neighbors.
|
||||
Set<DictionaryWord> userWords = registerWords(kiwiBuilder, dictionary);
|
||||
List<Synonym> spacedSynonyms = registerSynonyms(kiwiBuilder, synonyms, userWords);
|
||||
boolean joinNouns = compoundNounMaxTokens > 1;
|
||||
// Recognize URL/email/hashtag/mention/serial spans, normalize informal codas,
|
||||
// analyze unknown words with the character model and correct common typos.
|
||||
int match = Kiwi.Match.allWithNormalizing | Kiwi.Match.oovChrModel;
|
||||
if (joinNouns) {
|
||||
match |= Kiwi.Match.joinNounPrefix | Kiwi.Match.joinNounSuffix;
|
||||
}
|
||||
Kiwi.AnalyzeOption analyzeOption =
|
||||
new Kiwi.AnalyzeOption(
|
||||
match, null, (short) 0, 0f, typoTransformer, TYPO_COST_THRESHOLD);
|
||||
try (Kiwi kiwi = kiwiBuilder.build()) {
|
||||
for (String text : texts) {
|
||||
for (Kiwi.Token token : kiwi.tokenize(text, new Kiwi.AnalyzeOption(0))) {
|
||||
String tag = Kiwi.POSTag.toString(token.tag);
|
||||
result.add(new NlpTokenDto(token.form, tag == null ? "UNK" : tag));
|
||||
List<Kiwi.Token> tokens =
|
||||
replaceSpacedSynonyms(
|
||||
text, List.of(kiwi.tokenize(text, analyzeOption)), spacedSynonyms);
|
||||
if (joinNouns) {
|
||||
result.addAll(joinCompoundNouns(tokens, userWords, compoundNounMaxTokens));
|
||||
} else {
|
||||
tokens.forEach(token -> result.add(toToken(token)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,6 +121,279 @@ public class KiwiNlpService {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers each word once with its highest scope score (10/50/100). Kiwi keeps the last score
|
||||
* of a duplicate registration, and the dictionary query has no defined order.
|
||||
*/
|
||||
private Set<DictionaryWord> registerWords(
|
||||
KiwiBuilder kiwiBuilder, List<NlpDictionaryWordDto> dictionary) {
|
||||
Map<String, Byte> tags = tags();
|
||||
Map<DictionaryWord, Integer> scores = new LinkedHashMap<>();
|
||||
int skipped = 0;
|
||||
for (NlpDictionaryWordDto word : dictionary) {
|
||||
String text = StringUtil.normalizeBlank(word.getWordText());
|
||||
String tagName = StringUtil.normalizeBlank(word.getWordTag());
|
||||
Byte tag = tagName == null ? null : tags.get(tagName.toUpperCase(Locale.ROOT));
|
||||
if (text == null || tag == null || word.getWordScore() == null) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
scores.merge(new DictionaryWord(text, tag), word.getWordScore(), Math::max);
|
||||
}
|
||||
int rejected = 0;
|
||||
for (Map.Entry<DictionaryWord, Integer> entry : scores.entrySet()) {
|
||||
try {
|
||||
if (!kiwiBuilder.addWord(entry.getKey().text(), entry.getKey().tag(), entry.getValue())) {
|
||||
rejected++;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// The native call throws checked exceptions; an invalid word does not stop the analysis.
|
||||
rejected++;
|
||||
}
|
||||
}
|
||||
if (skipped > 0 || rejected > 0) {
|
||||
int registered = scores.size() - rejected;
|
||||
// Counts only: never log dictionary words.
|
||||
log.warn(
|
||||
"Kiwi user dictionary: registered={}, skipped={}, rejected={}",
|
||||
registered,
|
||||
skipped,
|
||||
rejected);
|
||||
}
|
||||
return new HashSet<>(scores.keySet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers synonym rows above every user word: SOURCE_TEXT is analyzed directly as
|
||||
* WORD_TEXT/WORD_TAG, and a spaced source also registers its spaceless form. The most specific
|
||||
* scope (score 100 > 50 > 10) wins for the same source, and an explicit spaceless source wins over
|
||||
* a derived one. Returns spaced sources, longest first, for {@link #replaceSpacedSynonyms}; adds
|
||||
* every target to {@code protectedWords}.
|
||||
*/
|
||||
private List<Synonym> registerSynonyms(
|
||||
KiwiBuilder kiwiBuilder,
|
||||
List<NlpDictionaryWordDto> synonyms,
|
||||
Set<DictionaryWord> protectedWords) {
|
||||
Map<String, Byte> tags = tags();
|
||||
// Targets already registered as plain user words keep their scope score.
|
||||
Set<DictionaryWord> registeredTargets = new HashSet<>(protectedWords);
|
||||
Map<String, Synonym> sources = new LinkedHashMap<>();
|
||||
Map<String, Integer> sourceRanks = new HashMap<>();
|
||||
int skipped = 0;
|
||||
for (NlpDictionaryWordDto synonym : synonyms) {
|
||||
String source = normalizeSpaces(synonym.getSourceText());
|
||||
String target = StringUtil.normalizeBlank(synonym.getWordText());
|
||||
String tagName = StringUtil.normalizeBlank(synonym.getWordTag());
|
||||
Byte tag = tagName == null ? null : tags.get(tagName.toUpperCase(Locale.ROOT));
|
||||
if (source == null || target == null || tag == null) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
int rank = synonym.getWordScore() == null ? 0 : synonym.getWordScore();
|
||||
if (!sources.containsKey(source) || rank > sourceRanks.get(source)) {
|
||||
sources.put(source, new Synonym(source, target, tag));
|
||||
sourceRanks.put(source, rank);
|
||||
}
|
||||
}
|
||||
Map<String, Synonym> attached = new LinkedHashMap<>();
|
||||
Map<String, Integer> attachedWeights = new HashMap<>();
|
||||
List<Synonym> spaced = new ArrayList<>();
|
||||
for (Synonym synonym : sources.values()) {
|
||||
boolean explicit = !synonym.source().contains(" ");
|
||||
String form = synonym.source().replace(" ", "");
|
||||
int weight = sourceRanks.get(synonym.source()) * 2 + (explicit ? 1 : 0);
|
||||
Integer current = attachedWeights.get(form);
|
||||
if (current == null || weight > current) {
|
||||
attached.put(form, new Synonym(form, synonym.target(), synonym.tag()));
|
||||
attachedWeights.put(form, weight);
|
||||
}
|
||||
if (!explicit) {
|
||||
spaced.add(synonym);
|
||||
}
|
||||
protectedWords.add(new DictionaryWord(synonym.target(), synonym.tag()));
|
||||
}
|
||||
int rejected = 0;
|
||||
for (Synonym synonym : attached.values()) {
|
||||
KiwiBuilder.AnalyzedMorph[] morphs = {
|
||||
new KiwiBuilder.AnalyzedMorph(
|
||||
synonym.target(), synonym.tag(), 0, synonym.source().length())
|
||||
};
|
||||
try {
|
||||
// Kiwi requires the target morpheme to exist, e.g. "LG" is not in the default dictionary.
|
||||
// Score 0 keeps a short target from being forced inside longer words.
|
||||
if (registeredTargets.add(new DictionaryWord(synonym.target(), synonym.tag()))) {
|
||||
kiwiBuilder.addWord(synonym.target(), synonym.tag(), 0f);
|
||||
}
|
||||
if (!kiwiBuilder.addPreAnalyzedWord(synonym.source(), morphs, SYNONYM_SCORE)) {
|
||||
rejected++;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// The native call throws checked exceptions; an invalid synonym does not stop the analysis.
|
||||
rejected++;
|
||||
}
|
||||
}
|
||||
if (skipped > 0 || rejected > 0) {
|
||||
int registered = attached.size() - rejected;
|
||||
// Counts only: never log synonym texts.
|
||||
log.warn(
|
||||
"Kiwi synonyms: registered={}, skipped={}, rejected={}",
|
||||
registered,
|
||||
skipped,
|
||||
rejected);
|
||||
}
|
||||
spaced.sort(Comparator.comparingInt((Synonym synonym) -> synonym.source().length()).reversed());
|
||||
return spaced;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces a run of tokens whose original text, with spaces collapsed, equals a spaced synonym
|
||||
* source. The run must start and end on token boundaries and must not continue into a noun of
|
||||
* the same word, so "엘지 전자레인지" (엘지/전자/레인지) is not "엘지 전자".
|
||||
*/
|
||||
static List<Kiwi.Token> replaceSpacedSynonyms(
|
||||
String text, List<Kiwi.Token> tokens, List<Synonym> spacedSynonyms) {
|
||||
if (spacedSynonyms.isEmpty()) {
|
||||
return tokens;
|
||||
}
|
||||
List<Kiwi.Token> result = new ArrayList<>();
|
||||
int start = 0;
|
||||
while (start < tokens.size()) {
|
||||
int end = -1;
|
||||
Synonym matched = null;
|
||||
for (Synonym synonym : spacedSynonyms) {
|
||||
end = matchEnd(text, tokens, start, synonym.source());
|
||||
if (end > start && !continuesNoun(tokens, start, end)) {
|
||||
matched = synonym;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched == null) {
|
||||
result.add(tokens.get(start));
|
||||
start++;
|
||||
continue;
|
||||
}
|
||||
Kiwi.Token first = tokens.get(start);
|
||||
Kiwi.Token last = tokens.get(end - 1);
|
||||
Kiwi.Token replaced = new Kiwi.Token();
|
||||
replaced.form = matched.target();
|
||||
replaced.tag = matched.tag();
|
||||
replaced.position = first.position;
|
||||
replaced.length = (short) (last.position + last.length - first.position);
|
||||
replaced.wordPosition = first.wordPosition;
|
||||
replaced.sentPosition = first.sentPosition;
|
||||
replaced.lineNumber = first.lineNumber;
|
||||
result.add(replaced);
|
||||
start = end;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Whether a noun is attached right before or after the run inside the same word. */
|
||||
private static boolean continuesNoun(List<Kiwi.Token> tokens, int start, int end) {
|
||||
boolean before =
|
||||
start > 0
|
||||
&& isAttached(tokens.get(start - 1), tokens.get(start))
|
||||
&& isNounLike(tokens.get(start - 1));
|
||||
boolean after =
|
||||
end < tokens.size()
|
||||
&& isAttached(tokens.get(end - 1), tokens.get(end))
|
||||
&& isNounLike(tokens.get(end));
|
||||
return before || after;
|
||||
}
|
||||
|
||||
private static boolean isNounLike(Kiwi.Token token) {
|
||||
String tag = tagName(token);
|
||||
return tag.startsWith("N") || NOUN_AFFIX_TAGS.contains(tag);
|
||||
}
|
||||
|
||||
/** Exclusive end index of the run starting at {@code start} that spells {@code source}, or -1. */
|
||||
private static int matchEnd(String text, List<Kiwi.Token> tokens, int start, String source) {
|
||||
int from = tokens.get(start).position;
|
||||
for (int end = start; end < tokens.size(); end++) {
|
||||
Kiwi.Token last = tokens.get(end);
|
||||
int to = last.position + last.length;
|
||||
if (from < 0 || to > text.length() || to < from) {
|
||||
return -1;
|
||||
}
|
||||
String span = WHITESPACE.matcher(text.substring(from, to)).replaceAll(" ");
|
||||
if (span.equals(source)) {
|
||||
return end + 1;
|
||||
}
|
||||
if (span.length() >= source.length()) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static String normalizeSpaces(String raw) {
|
||||
String normalized = StringUtil.normalizeBlank(raw);
|
||||
return normalized == null ? null : WHITESPACE.matcher(normalized).replaceAll(" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges a run of 2..maxTokens NNG/NNP/SL tokens written without a space inside one word into a
|
||||
* single noun, when the run contains a Korean noun. The merged tag is NNP if any part is NNP,
|
||||
* otherwise NNG. User dictionary words always stay as they are, and longer runs are kept apart.
|
||||
*/
|
||||
static List<NlpTokenDto> joinCompoundNouns(
|
||||
List<Kiwi.Token> tokens, Set<DictionaryWord> userWords, int maxTokens) {
|
||||
List<NlpTokenDto> result = new ArrayList<>();
|
||||
int start = 0;
|
||||
while (start < tokens.size()) {
|
||||
if (!isCompoundPart(tokens.get(start), userWords)) {
|
||||
result.add(toToken(tokens.get(start)));
|
||||
start++;
|
||||
continue;
|
||||
}
|
||||
int end = start + 1;
|
||||
while (end < tokens.size()
|
||||
&& isCompoundPart(tokens.get(end), userWords)
|
||||
&& isAttached(tokens.get(end - 1), tokens.get(end))) {
|
||||
end++;
|
||||
}
|
||||
List<Kiwi.Token> run = tokens.subList(start, end);
|
||||
boolean hasKoreanNoun = run.stream().anyMatch(token -> !isForeignWord(token));
|
||||
if (run.size() > 1 && run.size() <= maxTokens && hasKoreanNoun) {
|
||||
StringBuilder form = new StringBuilder();
|
||||
boolean properNoun = false;
|
||||
for (Kiwi.Token token : run) {
|
||||
form.append(token.form);
|
||||
properNoun |= "NNP".equals(tagName(token));
|
||||
}
|
||||
result.add(new NlpTokenDto(form.toString(), properNoun ? "NNP" : "NNG"));
|
||||
} else {
|
||||
run.forEach(token -> result.add(toToken(token)));
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static boolean isCompoundPart(Kiwi.Token token, Set<DictionaryWord> userWords) {
|
||||
return COMPOUND_NOUN_TAGS.contains(tagName(token))
|
||||
&& !userWords.contains(new DictionaryWord(token.form, token.tag));
|
||||
}
|
||||
|
||||
private static boolean isForeignWord(Kiwi.Token token) {
|
||||
return "SL".equals(tagName(token));
|
||||
}
|
||||
|
||||
/** Same word and no space or other character between the two tokens. */
|
||||
private static boolean isAttached(Kiwi.Token previous, Kiwi.Token next) {
|
||||
return previous.wordPosition == next.wordPosition
|
||||
&& previous.position + previous.length == next.position;
|
||||
}
|
||||
|
||||
private static NlpTokenDto toToken(Kiwi.Token token) {
|
||||
return new NlpTokenDto(token.form, tagName(token));
|
||||
}
|
||||
|
||||
private static String tagName(Kiwi.Token token) {
|
||||
String tag = Kiwi.POSTag.toString(token.tag);
|
||||
return tag == null ? "UNK" : tag;
|
||||
}
|
||||
|
||||
private Map<String, Byte> tags() {
|
||||
Map<String, Byte> result = new LinkedHashMap<>();
|
||||
for (int code = Byte.MIN_VALUE; code <= Byte.MAX_VALUE; code++) {
|
||||
@@ -77,4 +409,8 @@ public class KiwiNlpService {
|
||||
return BusinessException.of(
|
||||
HttpStatus.SERVICE_UNAVAILABLE, "KIWI_NLP_UNAVAILABLE", "Kiwi NLP 라이브러리와 모델 설정을 확인해 주세요.");
|
||||
}
|
||||
|
||||
record DictionaryWord(String text, byte tag) {}
|
||||
|
||||
record Synonym(String source, String target, byte tag) {}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.kri.kart.server.dto.statistics.StatisticsRowDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsValueGroupDto;
|
||||
import com.kri.kart.server.dto.statistics.SurveyResponseDto;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
@@ -19,6 +18,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -53,9 +53,10 @@ public class StatisticsAggregationService {
|
||||
StatisticsRequestDto request,
|
||||
List<QuestionDto> questions,
|
||||
List<SurveyResponseDto> responses) {
|
||||
StatisticsDimension index =
|
||||
statisticsDimensionService.resolve(request.getIndex(), questions, responses);
|
||||
List<Column> columns = columns(index, request, questions, responses);
|
||||
Function<String, StatisticsDimension> dimensions =
|
||||
statisticsDimensionService.prepare(questions, responses);
|
||||
StatisticsDimension index = dimensions.apply(request.getIndex());
|
||||
List<Column> columns = columns(index, request, responses, dimensions);
|
||||
if (KartConstant.BANNER_CROSS_MODE.equals(request.getMode())) {
|
||||
return bannerCrossTable(index, columns, request);
|
||||
}
|
||||
@@ -65,7 +66,7 @@ public class StatisticsAggregationService {
|
||||
addSummaryRows(rows, index, columns, request);
|
||||
return statisticsTableService.table(
|
||||
index.getDimensionId(),
|
||||
index.getQuestion().getTitle(),
|
||||
index.getTitle(),
|
||||
columnHeaders(index, columns),
|
||||
rows,
|
||||
request);
|
||||
@@ -75,8 +76,8 @@ public class StatisticsAggregationService {
|
||||
private List<Column> columns(
|
||||
StatisticsDimension index,
|
||||
StatisticsRequestDto request,
|
||||
List<QuestionDto> questions,
|
||||
List<SurveyResponseDto> responses) {
|
||||
List<SurveyResponseDto> responses,
|
||||
Function<String, StatisticsDimension> preparedDimensions) {
|
||||
List<SurveyResponseDto> total = statisticsSelectionService.total(responses, index);
|
||||
List<List<SurveyResponseDto>> cases =
|
||||
index.getChoices().stream()
|
||||
@@ -87,12 +88,12 @@ public class StatisticsAggregationService {
|
||||
List<List<String>> banners = request.getBanners();
|
||||
if (!index.getAttributes().isEmpty()) {
|
||||
// The old matrix summary replaces supplied banners with its own attribute projection.
|
||||
banners = List.of(List.of(index.getQuestion().getQid() + "#A"));
|
||||
banners = List.of(List.of(index.getAttributeBannerId()));
|
||||
}
|
||||
for (int group = 0; group < banners.size(); group++) {
|
||||
List<StatisticsDimension> dimensions =
|
||||
banners.get(group).stream()
|
||||
.map(id -> statisticsDimensionService.resolve(id, questions, responses))
|
||||
.map(preparedDimensions)
|
||||
.toList();
|
||||
if (dimensions.stream().anyMatch(this::isOpenAnswer)) {
|
||||
throw BusinessException.badRequest("주관식 문자·숫자 문항은 배너로 사용할 수 없습니다.");
|
||||
@@ -123,7 +124,7 @@ public class StatisticsAggregationService {
|
||||
for (StatisticsDimension.Choice choice : banner.getChoices()) {
|
||||
String columnId = parentId + "_" + choice.value();
|
||||
List<String> labels = new ArrayList<>(parentLabels);
|
||||
labels.add(banner.getQuestion().getTitle());
|
||||
labels.add(banner.getTitle());
|
||||
labels.add(choice.label());
|
||||
List<SurveyResponseDto> bannerTotal =
|
||||
statisticsSelectionService.bannerTotal(total, banner, choice.value());
|
||||
@@ -161,7 +162,7 @@ public class StatisticsAggregationService {
|
||||
}
|
||||
|
||||
private boolean isOpenAnswer(StatisticsDimension dimension) {
|
||||
return KartConstant.OPEN_QUESTION_TYPES.contains(dimension.getQuestion().getQtype())
|
||||
return KartConstant.OPEN_QUESTION_TYPES.contains(dimension.getQuestionType())
|
||||
&& !dimension.isAttributeProjection();
|
||||
}
|
||||
|
||||
@@ -221,7 +222,7 @@ public class StatisticsAggregationService {
|
||||
StatisticsDimension index,
|
||||
List<Column> columns,
|
||||
StatisticsRequestDto request) {
|
||||
String type = index.getQuestion().getQtype();
|
||||
String type = index.getQuestionType();
|
||||
if ("num".equals(type)) {
|
||||
addStatistic(rows, columns, index, KartConstant.MEAN, request);
|
||||
for (String statistic : KartConstant.NUMERIC_STATISTICS) {
|
||||
@@ -235,7 +236,7 @@ public class StatisticsAggregationService {
|
||||
addScaleGroups(rows, columns, index, request);
|
||||
}
|
||||
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)) {
|
||||
addStatistic(rows, columns, index, KartConstant.MEAN, request);
|
||||
@@ -396,12 +397,11 @@ public class StatisticsAggregationService {
|
||||
Column column, StatisticsDimension index, boolean totalColumn) {
|
||||
List<SurveyResponseDto> source =
|
||||
totalColumn ? column.total() : column.cases().stream().flatMap(List::stream).toList();
|
||||
String baseKey = index.getBaseKey();
|
||||
LinkedHashSet<String> keys = new LinkedHashSet<>();
|
||||
source.forEach(
|
||||
response ->
|
||||
response.values().keySet().stream()
|
||||
.filter(key -> key.equals(baseKey) || key.startsWith(baseKey + "_"))
|
||||
.filter(index.getAnswerAccess().valueKeys())
|
||||
.forEach(keys::add));
|
||||
List<Double> numbers = new ArrayList<>();
|
||||
for (String key : keys) {
|
||||
@@ -526,8 +526,8 @@ public class StatisticsAggregationService {
|
||||
List<StatisticsCellDto> cells = new ArrayList<>();
|
||||
cells.add(StatisticsTableService.text(0, "NPS"));
|
||||
for (int column = 1; column <= columns.size(); column++) {
|
||||
StatisticsCellDto promoters = rows.get(promotersRow).getCells().get(column);
|
||||
StatisticsCellDto detractors = rows.get(detractorsRow).getCells().get(column);
|
||||
StatisticsCellDto promoters = rows.get(promotersRow).cells().get(column);
|
||||
StatisticsCellDto detractors = rows.get(detractorsRow).cells().get(column);
|
||||
Double percent =
|
||||
promoters.getPercent() == null || detractors.getPercent() == null
|
||||
? null
|
||||
@@ -555,21 +555,15 @@ public class StatisticsAggregationService {
|
||||
}
|
||||
|
||||
private List<Double> missingValues(StatisticsDimension index) {
|
||||
String values = index.getQuestion().getMissingValue();
|
||||
return values == null
|
||||
? List.of()
|
||||
: Arrays.stream(values.split(","))
|
||||
.map(StatisticsArithmetic::number)
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
return index.getMissingValues();
|
||||
}
|
||||
|
||||
private boolean isReverse(StatisticsDimension index) {
|
||||
return "1".equals(index.getQuestion().getIsReverse());
|
||||
return index.isReverse();
|
||||
}
|
||||
|
||||
private boolean isNps(StatisticsDimension index) {
|
||||
return "1".equals(index.getQuestion().getIsNps());
|
||||
return index.isNps();
|
||||
}
|
||||
|
||||
/** One row summing the cases of the given choice codes. */
|
||||
@@ -615,7 +609,7 @@ public class StatisticsAggregationService {
|
||||
|
||||
private List<StatisticsColumnDto> columnHeaders(StatisticsDimension index, List<Column> columns) {
|
||||
List<StatisticsColumnDto> result = new ArrayList<>();
|
||||
result.add(new StatisticsColumnDto("LABEL", "LABEL", List.of(index.getQuestion().getTitle())));
|
||||
result.add(new StatisticsColumnDto("LABEL", "LABEL", List.of(index.getTitle())));
|
||||
for (Column column : columns) {
|
||||
result.add(new StatisticsColumnDto(column.id(), columnKind(column), column.labels()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.kri.kart.server.service.statistics;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/** Prepared access to existing response maps; never owns or copies respondent values. */
|
||||
public record StatisticsAnswerAccess(
|
||||
boolean wholeSample, Predicate<String> valueKeys, Selection selection) {
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Selection {
|
||||
List<Read> prepare(
|
||||
String attribute, String multiValue, List<String> attributes, int numberedSlots);
|
||||
}
|
||||
|
||||
public record Read(String key, Predicate<String> answeredKeys) {}
|
||||
}
|
||||
@@ -1,21 +1,48 @@
|
||||
package com.kri.kart.server.service.statistics;
|
||||
|
||||
import com.kri.kart.server.dto.question.QuestionDto;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public class StatisticsDimension {
|
||||
private final String dimensionId;
|
||||
private final QuestionDto question;
|
||||
private final String baseKey;
|
||||
private final String attributeValue;
|
||||
private final List<String> attributes;
|
||||
private final int rankCount;
|
||||
private final boolean attributeProjection;
|
||||
private final List<Choice> choices;
|
||||
private final String title;
|
||||
private final String questionType;
|
||||
private final String attributeBannerId;
|
||||
private final List<Double> missingValues;
|
||||
private final boolean reverse;
|
||||
private final boolean nps;
|
||||
private final StatisticsAnswerAccess answerAccess;
|
||||
|
||||
public StatisticsDimension(
|
||||
String dimensionId, Definition definition, String baseKey, String attributeValue,
|
||||
List<String> attributes, int rankCount, boolean attributeProjection, List<Choice> choices,
|
||||
StatisticsAnswerAccess answerAccess) {
|
||||
this.dimensionId = dimensionId;
|
||||
this.baseKey = baseKey;
|
||||
this.attributeValue = attributeValue;
|
||||
this.attributes = attributes;
|
||||
this.rankCount = rankCount;
|
||||
this.attributeProjection = attributeProjection;
|
||||
this.choices = choices;
|
||||
this.title = definition.title();
|
||||
this.questionType = definition.questionType();
|
||||
this.attributeBannerId = definition.attributeBannerId();
|
||||
this.missingValues = definition.missingValues();
|
||||
this.reverse = definition.reverse();
|
||||
this.nps = definition.nps();
|
||||
this.answerAccess = answerAccess;
|
||||
}
|
||||
|
||||
public record Definition(
|
||||
String title, String questionType, String attributeBannerId,
|
||||
List<Double> missingValues, boolean reverse, boolean nps) {}
|
||||
|
||||
public record Choice(String value, String label) {}
|
||||
|
||||
|
||||
@@ -9,10 +9,15 @@ import com.kri.kart.server.common.consts.KartConstant;
|
||||
import com.kri.kart.server.dto.question.QuestionDto;
|
||||
import com.kri.kart.server.dto.statistics.SurveyResponseDto;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -21,6 +26,7 @@ import org.springframework.stereotype.Service;
|
||||
public class StatisticsDimensionService {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final StatisticsSourceService statisticsSourceService;
|
||||
|
||||
/**
|
||||
* Resolves an index or banner id. A blank id is the whole sample; "Q1#A" projects the attributes
|
||||
@@ -73,7 +79,24 @@ public class StatisticsDimensionService {
|
||||
List<StatisticsDimension.Choice> choices = choices(question, qid, projection, responses);
|
||||
excludeScreenedOutChoices(question, qid, choices);
|
||||
return new StatisticsDimension(
|
||||
id, question, baseKey, attributeValue, attributes, rankCount, projection, choices);
|
||||
id, definition(question), baseKey, attributeValue, attributes, rankCount, projection,
|
||||
choices, statisticsSourceService.access(baseKey));
|
||||
}
|
||||
|
||||
/** Cache only within one calculation and its exact respondent population. */
|
||||
public Function<String, StatisticsDimension> prepare(
|
||||
List<QuestionDto> questions, List<SurveyResponseDto> responses) {
|
||||
Map<String, StatisticsDimension> dimensions = new HashMap<>();
|
||||
return id -> dimensions.computeIfAbsent(id, key -> resolve(key, questions, responses));
|
||||
}
|
||||
|
||||
private StatisticsDimension.Definition definition(QuestionDto question) {
|
||||
String missing = question.getMissingValue();
|
||||
List<Double> missingValues = missing == null ? List.of() : Arrays.stream(missing.split(","))
|
||||
.map(StatisticsArithmetic::number).filter(Objects::nonNull).toList();
|
||||
return new StatisticsDimension.Definition(
|
||||
question.getTitle(), question.getQtype(), question.getQid() + KartConstant.ATTRIBUTE_PROJECTION_SUFFIX,
|
||||
missingValues, "1".equals(question.getIsReverse()), "1".equals(question.getIsNps()));
|
||||
}
|
||||
|
||||
public JsonNode metadata(String json) {
|
||||
@@ -96,13 +119,13 @@ public class StatisticsDimensionService {
|
||||
.build();
|
||||
return new StatisticsDimension(
|
||||
"",
|
||||
question,
|
||||
definition(question),
|
||||
"",
|
||||
"",
|
||||
List.of(),
|
||||
0,
|
||||
false,
|
||||
List.of(new StatisticsDimension.Choice("0", "전체")));
|
||||
List.of(new StatisticsDimension.Choice("0", "전체")), statisticsSourceService.access(""));
|
||||
}
|
||||
|
||||
private List<StatisticsDimension.Choice> choices(
|
||||
@@ -126,11 +149,12 @@ public class StatisticsDimensionService {
|
||||
/** Open questions have no label metadata; every distinct answer becomes a choice. */
|
||||
private List<StatisticsDimension.Choice> answeredChoices(
|
||||
QuestionDto question, String qid, List<SurveyResponseDto> responses) {
|
||||
Predicate<String> valueKeys = statisticsSourceService.valueKeys(qid);
|
||||
LinkedHashSet<String> keys = new LinkedHashSet<>();
|
||||
responses.forEach(
|
||||
response ->
|
||||
response.values().keySet().stream()
|
||||
.filter(key -> key.equals(qid) || key.startsWith(qid + "_"))
|
||||
.filter(valueKeys)
|
||||
.forEach(keys::add));
|
||||
LinkedHashSet<String> values = new LinkedHashSet<>();
|
||||
for (String key : keys) {
|
||||
|
||||
@@ -8,16 +8,17 @@ import com.kri.kart.server.dto.question.QuestionDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsFilterDto;
|
||||
import com.kri.kart.server.dto.statistics.SurveyResponseDto;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
/** Compiles a filter AST into a respondent predicate. User input is never turned into SQL. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class StatisticsFilterService {
|
||||
private final StatisticsSourceService statisticsSourceService;
|
||||
|
||||
public Predicate<SurveyResponseDto> compile(
|
||||
StatisticsFilterDto filter, List<QuestionDto> questions) {
|
||||
@@ -25,29 +26,7 @@ public class StatisticsFilterService {
|
||||
}
|
||||
|
||||
public String resolveQid(StatisticsFilterDto filter, List<QuestionDto> questions) {
|
||||
String dimension = StringUtil.normalizeBlank(filter.getDimensionId());
|
||||
if (dimension == null
|
||||
|| dimension.contains("#")
|
||||
|| !Set.of("QID", "VARIABLE").contains(Objects.toString(filter.getReference(), ""))) {
|
||||
throw BusinessException.badRequest("필터 문항과 참조 방식을 확인해 주세요.");
|
||||
}
|
||||
String id = dimension.toUpperCase(Locale.ROOT);
|
||||
for (QuestionDto question : questions) {
|
||||
String reference = reference(filter, question);
|
||||
if (reference != null && reference.equalsIgnoreCase(id)) {
|
||||
return question.getQid().toUpperCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
// Base rank/open IDs exist in saved data even though the UI lists expanded dimensions only.
|
||||
String root = id.split("_")[0];
|
||||
for (QuestionDto question : questions) {
|
||||
String reference = reference(filter, question);
|
||||
if (reference != null && reference.split("_")[0].equalsIgnoreCase(root)) {
|
||||
return question.getQid().split("_")[0].toUpperCase(Locale.ROOT)
|
||||
+ id.substring(root.length());
|
||||
}
|
||||
}
|
||||
throw BusinessException.badRequest("필터 문항을 찾을 수 없습니다.");
|
||||
return statisticsSourceService.resolveFilterQid(filter, questions);
|
||||
}
|
||||
|
||||
private Predicate<SurveyResponseDto> compile(
|
||||
@@ -94,11 +73,11 @@ public class StatisticsFilterService {
|
||||
if (!hasValidValues(operator, filter.getValues())) {
|
||||
throw BusinessException.badRequest("필터 비교 값의 개수나 유형이 올바르지 않습니다.");
|
||||
}
|
||||
String qid = resolveQid(filter, questions);
|
||||
Predicate<String> keys = statisticsSourceService.filterKeys(resolveQid(filter, questions));
|
||||
Predicate<SurveyResponseDto> predicate =
|
||||
response ->
|
||||
response.filterValues().entrySet().stream()
|
||||
.filter(entry -> matchingKey(qid, entry.getKey()))
|
||||
.filter(entry -> keys.test(entry.getKey()))
|
||||
.anyMatch(entry -> compare(entry.getValue(), operator, filter.getValues()));
|
||||
// Legacy negative multi conditions are NOT EXISTS of a matching value, including missing keys.
|
||||
return KartConstant.FILTER_NEGATED_OPERATORS.contains(operator) ? predicate.negate() : predicate;
|
||||
@@ -123,22 +102,6 @@ public class StatisticsFilterService {
|
||||
&& !(value.isNumber() && !Double.isFinite(value.asDouble()));
|
||||
}
|
||||
|
||||
private String reference(StatisticsFilterDto filter, QuestionDto question) {
|
||||
return "VARIABLE".equals(filter.getReference()) ? question.getVariable() : question.getQid();
|
||||
}
|
||||
|
||||
/** Q1 matches Q1 and Q1_*; Q1_2 matches Q1_2 and Q1_*_2. */
|
||||
private boolean matchingKey(String qid, String key) {
|
||||
if (key.equals(qid)) {
|
||||
return true;
|
||||
}
|
||||
String[] parts = qid.split("_");
|
||||
if (parts.length == 1) {
|
||||
return key.startsWith(qid + "_");
|
||||
}
|
||||
return parts.length == 2 && key.startsWith(parts[0] + "_") && key.endsWith("_" + parts[1]);
|
||||
}
|
||||
|
||||
private boolean compare(String actual, String operator, List<JsonNode> operands) {
|
||||
if (Set.of("IS_ANSWERED", "IS_UNANSWERED").contains(operator)) {
|
||||
return actual != null;
|
||||
@@ -172,8 +135,7 @@ public class StatisticsFilterService {
|
||||
return number == null ? KartConstant.FILTER_NOT_COMPARABLE : Double.compare(number, expected.asDouble());
|
||||
}
|
||||
// SQL Server's existing collation is case-insensitive; DAT also contains FOR XML escaping.
|
||||
return HtmlUtils.htmlUnescape(actual)
|
||||
.replaceFirst(" +$", "")
|
||||
return statisticsSourceService.filterText(actual)
|
||||
.compareToIgnoreCase(expected.asText().replaceFirst(" +$", ""));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ public class StatisticsSelectionService {
|
||||
List<SurveyResponseDto> source, StatisticsDimension dimension) {
|
||||
return select(
|
||||
source,
|
||||
dimension.getBaseKey(),
|
||||
dimension.getAnswerAccess(),
|
||||
true,
|
||||
dimension.getAttributeValue(),
|
||||
"",
|
||||
@@ -32,7 +32,7 @@ public class StatisticsSelectionService {
|
||||
String multiValue = isMulti(dimension) ? value : "";
|
||||
return select(
|
||||
source,
|
||||
dimension.getBaseKey(),
|
||||
dimension.getAnswerAccess(),
|
||||
false,
|
||||
dimension.getAttributeValue(),
|
||||
multiValue,
|
||||
@@ -48,7 +48,7 @@ public class StatisticsSelectionService {
|
||||
boolean projection = banner.isAttributeProjection();
|
||||
return select(
|
||||
source,
|
||||
banner.getBaseKey(),
|
||||
banner.getAnswerAccess(),
|
||||
multi || projection,
|
||||
projection ? value : banner.getAttributeValue(),
|
||||
multi && !projection ? value : "",
|
||||
@@ -71,7 +71,7 @@ public class StatisticsSelectionService {
|
||||
boolean projection = banner.isAttributeProjection();
|
||||
return select(
|
||||
source,
|
||||
banner.getBaseKey(),
|
||||
banner.getAnswerAccess(),
|
||||
false,
|
||||
projection ? value : banner.getAttributeValue(),
|
||||
multi && !projection ? value : "",
|
||||
@@ -81,7 +81,7 @@ public class StatisticsSelectionService {
|
||||
}
|
||||
|
||||
private boolean isMulti(StatisticsDimension dimension) {
|
||||
return "multi".equals(dimension.getQuestion().getQtype());
|
||||
return "multi".equals(dimension.getQuestionType());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,7 +90,7 @@ public class StatisticsSelectionService {
|
||||
*/
|
||||
private List<SurveyResponseDto> select(
|
||||
List<SurveyResponseDto> source,
|
||||
String baseKey,
|
||||
StatisticsAnswerAccess access,
|
||||
boolean anyAnswer,
|
||||
String attributeValue,
|
||||
String multiValue,
|
||||
@@ -98,21 +98,13 @@ public class StatisticsSelectionService {
|
||||
List<String> attributes,
|
||||
int numberedSlots) {
|
||||
List<SurveyResponseDto> result = new ArrayList<>();
|
||||
int attributeCount = Math.max(1, attributes.size());
|
||||
int slotCount = Math.max(1, numberedSlots);
|
||||
for (int attributeIndex = 0; attributeIndex < attributeCount; attributeIndex++) {
|
||||
String attribute = attributes.isEmpty() ? attributeValue : attributes.get(attributeIndex);
|
||||
String attributeSuffix = attribute.isEmpty() ? "" : "_" + attribute;
|
||||
for (int slot = 0; slot < slotCount; slot++) {
|
||||
String slotSuffix =
|
||||
numberedSlots != 0 ? "_" + (slot + 1) : multiValue.isEmpty() ? "" : "_" + multiValue;
|
||||
String suffix = slotSuffix + attributeSuffix;
|
||||
for (SurveyResponseDto response : source) {
|
||||
if (baseKey.isEmpty()
|
||||
|| matches(response.values(), baseKey, suffix, anyAnswer, choiceValue)) {
|
||||
// Legacy JArray.Merge concatenates; the same person can be counted in several slots.
|
||||
result.add(response);
|
||||
}
|
||||
List<StatisticsAnswerAccess.Read> reads =
|
||||
access.selection().prepare(attributeValue, multiValue, attributes, numberedSlots);
|
||||
for (StatisticsAnswerAccess.Read read : reads) {
|
||||
for (SurveyResponseDto response : source) {
|
||||
if (access.wholeSample() || matches(response.values(), read, anyAnswer, choiceValue)) {
|
||||
// Preserve repeated attribute/slot occurrences and their original order.
|
||||
result.add(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,24 +112,13 @@ public class StatisticsSelectionService {
|
||||
}
|
||||
|
||||
private boolean matches(
|
||||
Map<String, String> values,
|
||||
String baseKey,
|
||||
String suffix,
|
||||
boolean anyAnswer,
|
||||
String choiceValue) {
|
||||
Map<String, String> values, StatisticsAnswerAccess.Read read,
|
||||
boolean anyAnswer, String choiceValue) {
|
||||
if (anyAnswer) {
|
||||
return values.entrySet().stream()
|
||||
.anyMatch(
|
||||
entry -> {
|
||||
String key = entry.getKey();
|
||||
boolean sameBase =
|
||||
baseKey.contains("_")
|
||||
? key.equals(baseKey) || key.startsWith(baseKey + "_")
|
||||
: key.split("_")[0].equals(baseKey);
|
||||
return sameBase && key.endsWith(suffix) && !"".equals(entry.getValue());
|
||||
});
|
||||
return values.entrySet().stream().anyMatch(entry ->
|
||||
read.answeredKeys().test(entry.getKey()) && !"".equals(entry.getValue()));
|
||||
}
|
||||
Double actual = StatisticsArithmetic.number(values.get(baseKey + suffix));
|
||||
Double actual = StatisticsArithmetic.number(values.get(read.key()));
|
||||
Double expected = StatisticsArithmetic.number(choiceValue);
|
||||
return actual != null && expected != null && actual.doubleValue() == expected.doubleValue();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.kri.kart.server.service.statistics;
|
||||
|
||||
import com.kri.common.feature.util.StringUtil;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.kart.server.common.consts.KartConstant;
|
||||
import com.kri.kart.server.dto.question.QuestionDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsFilterDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsRequestDto;
|
||||
import com.kri.kart.server.dto.statistics.SurveyResponseDto;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
/** KON/KIWI storage conventions, kept outside statistical calculations. */
|
||||
@Service
|
||||
public class StatisticsSourceService {
|
||||
|
||||
public StatisticsAnswerAccess access(String baseKey) {
|
||||
Predicate<String> sameBase =
|
||||
baseKey.contains("_")
|
||||
? key -> key.equals(baseKey) || key.startsWith(baseKey + "_")
|
||||
: key -> key.split("_")[0].equals(baseKey);
|
||||
return new StatisticsAnswerAccess(
|
||||
baseKey.isEmpty(),
|
||||
valueKeys(baseKey),
|
||||
(attributeValue, multiValue, attributes, numberedSlots) -> {
|
||||
List<StatisticsAnswerAccess.Read> reads = new ArrayList<>();
|
||||
int attributeCount = Math.max(1, attributes.size());
|
||||
int slotCount = Math.max(1, numberedSlots);
|
||||
for (int attributeIndex = 0; attributeIndex < attributeCount; attributeIndex++) {
|
||||
String attribute = attributes.isEmpty() ? attributeValue : attributes.get(attributeIndex);
|
||||
String attributeSuffix = attribute.isEmpty() ? "" : "_" + attribute;
|
||||
for (int slot = 0; slot < slotCount; slot++) {
|
||||
String slotSuffix = numberedSlots != 0
|
||||
? "_" + (slot + 1) : multiValue.isEmpty() ? "" : "_" + multiValue;
|
||||
String suffix = slotSuffix + attributeSuffix;
|
||||
reads.add(new StatisticsAnswerAccess.Read(
|
||||
baseKey + suffix, key -> sameBase.test(key) && key.endsWith(suffix)));
|
||||
}
|
||||
}
|
||||
return reads;
|
||||
});
|
||||
}
|
||||
|
||||
public Predicate<String> valueKeys(String baseKey) {
|
||||
String prefix = baseKey + "_";
|
||||
return key -> key.equals(baseKey) || key.startsWith(prefix);
|
||||
}
|
||||
|
||||
public Predicate<String> filterKeys(String qid) {
|
||||
String[] parts = qid.split("_");
|
||||
return key -> key.equals(qid)
|
||||
|| (parts.length == 1 && key.startsWith(qid + "_"))
|
||||
|| (parts.length == 2 && key.startsWith(parts[0] + "_") && key.endsWith("_" + parts[1]));
|
||||
}
|
||||
|
||||
public String resolveFilterQid(StatisticsFilterDto filter, List<QuestionDto> questions) {
|
||||
String dimension = StringUtil.normalizeBlank(filter.getDimensionId());
|
||||
if (dimension == null || dimension.contains("#")
|
||||
|| !Set.of("QID", "VARIABLE").contains(Objects.toString(filter.getReference(), ""))) {
|
||||
throw BusinessException.badRequest("필터 문항과 참조 방식을 확인해 주세요.");
|
||||
}
|
||||
String id = dimension.toUpperCase(Locale.ROOT);
|
||||
for (QuestionDto question : questions) {
|
||||
String reference = reference(filter, question);
|
||||
if (reference != null && reference.equalsIgnoreCase(id)) {
|
||||
return question.getQid().toUpperCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
String root = id.split("_")[0];
|
||||
for (QuestionDto question : questions) {
|
||||
String reference = reference(filter, question);
|
||||
if (reference != null && reference.split("_")[0].equalsIgnoreCase(root)) {
|
||||
return question.getQid().split("_")[0].toUpperCase(Locale.ROOT)
|
||||
+ id.substring(root.length());
|
||||
}
|
||||
}
|
||||
throw BusinessException.badRequest("필터 문항을 찾을 수 없습니다.");
|
||||
}
|
||||
|
||||
private String reference(StatisticsFilterDto filter, QuestionDto question) {
|
||||
return "VARIABLE".equals(filter.getReference()) ? question.getVariable() : question.getQid();
|
||||
}
|
||||
|
||||
public List<String> storageRoots(StatisticsRequestDto request) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
ids.add(KartConstant.STANDARD_MODE.equals(request.getMode())
|
||||
? request.getIndex() : KartConstant.TABULATION_STORAGE_ROOT);
|
||||
request.getBanners().forEach(ids::addAll);
|
||||
return ids.stream().map(this::storageRoot).distinct().toList();
|
||||
}
|
||||
|
||||
private String storageRoot(String id) {
|
||||
return Objects.toString(StringUtil.normalizeBlank(id), "")
|
||||
.toUpperCase(Locale.ROOT).replace(KartConstant.ATTRIBUTE_PROJECTION_SUFFIX, "").split("_")[0];
|
||||
}
|
||||
|
||||
public List<SurveyResponseDto> withinStorageRoots(
|
||||
List<SurveyResponseDto> responses, List<String> roots) {
|
||||
Predicate<String> stored = key -> roots.contains(key) || roots.contains(key.split("_")[0]);
|
||||
return responses.stream()
|
||||
.filter(response -> response.values().keySet().stream().anyMatch(stored)).toList();
|
||||
}
|
||||
|
||||
public boolean isProfileId(String id) {
|
||||
String normalized = StringUtil.normalizeBlank(id);
|
||||
if (normalized == null) {
|
||||
return false;
|
||||
}
|
||||
String upper = normalized.toUpperCase(Locale.ROOT);
|
||||
return KartConstant.PROFILE_ID_PREFIXES.stream().anyMatch(upper::startsWith);
|
||||
}
|
||||
|
||||
public String textAnswer(String value) {
|
||||
return HtmlUtils.htmlUnescape(value.replace('¸', ','));
|
||||
}
|
||||
|
||||
public String filterText(String value) {
|
||||
return HtmlUtils.htmlUnescape(value).replaceFirst(" +$", "");
|
||||
}
|
||||
}
|
||||
@@ -57,14 +57,14 @@ public class StatisticsTableService {
|
||||
flat
|
||||
? 1
|
||||
: 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<>();
|
||||
for (int row = 0; row < height; row++) {
|
||||
cells.add(new ArrayList<>());
|
||||
}
|
||||
cells.get(0).add(text(0, title).toBuilder().rowSpan(height).build());
|
||||
for (int column = 1; column < columns.size(); column++) {
|
||||
List<String> labels = columns.get(column).getLabels();
|
||||
List<String> labels = columns.get(column).labels();
|
||||
if (flat) {
|
||||
cells.get(0).add(text(column, String.join(" - ", labels)));
|
||||
continue;
|
||||
@@ -105,8 +105,8 @@ public class StatisticsTableService {
|
||||
if (previous == null || column <= 1) {
|
||||
return false;
|
||||
}
|
||||
List<String> labels = columns.get(column).getLabels();
|
||||
List<String> previousLabels = columns.get(column - 1).getLabels();
|
||||
List<String> labels = columns.get(column).labels();
|
||||
List<String> previousLabels = columns.get(column - 1).labels();
|
||||
boolean stretches = row == Math.max(1, labels.size()) - 1 && height - row > 1;
|
||||
return previous.getRowSpan() == 1
|
||||
&& !stretches
|
||||
@@ -122,7 +122,7 @@ public class StatisticsTableService {
|
||||
StatisticsRowDto row = body.get(rowIndex);
|
||||
rows.add(
|
||||
new StatisticsRowDto(
|
||||
rowIndex + headerCount, row.getRowId(), row.getKind(), row.getCells()));
|
||||
rowIndex + headerCount, row.rowId(), row.kind(), row.cells()));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -136,11 +136,11 @@ public class StatisticsTableService {
|
||||
for (int rowIndex = 0; rowIndex < columns.size(); rowIndex++) {
|
||||
List<StatisticsCellDto> cells = new ArrayList<>();
|
||||
for (StatisticsRowDto row : source) {
|
||||
for (StatisticsCellDto cell : row.getCells()) {
|
||||
for (StatisticsCellDto cell : row.cells()) {
|
||||
if (cell.getColumnIndex() == rowIndex) {
|
||||
cells.add(
|
||||
cell.toBuilder()
|
||||
.columnIndex(row.getRowIndex())
|
||||
.columnIndex(row.rowIndex())
|
||||
.rowSpan(cell.getColSpan())
|
||||
.colSpan(cell.getRowSpan())
|
||||
.build());
|
||||
@@ -151,15 +151,15 @@ public class StatisticsTableService {
|
||||
transposed.add(
|
||||
new StatisticsRowDto(
|
||||
rowIndex,
|
||||
columns.get(rowIndex).getColumnId(),
|
||||
rowIndex == 0 ? "HEADER" : columns.get(rowIndex).getKind(),
|
||||
columns.get(rowIndex).columnId(),
|
||||
rowIndex == 0 ? "HEADER" : columns.get(rowIndex).kind(),
|
||||
cells));
|
||||
}
|
||||
List<StatisticsColumnDto> transposedColumns =
|
||||
source.stream()
|
||||
.map(
|
||||
row ->
|
||||
new StatisticsColumnDto(row.getRowId(), row.getKind(), List.of(row.getRowId())))
|
||||
new StatisticsColumnDto(row.rowId(), row.kind(), List.of(row.rowId())))
|
||||
.toList();
|
||||
List<StatisticsRowDto> headers = transposed.isEmpty() ? List.of() : List.of(transposed.get(0));
|
||||
List<StatisticsRowDto> rows =
|
||||
|
||||
@@ -1,22 +1,28 @@
|
||||
package com.kri.kart.server.service.statistics;
|
||||
|
||||
import com.kri.common.feature.util.StringUtil;
|
||||
import com.kri.kart.server.common.consts.KartConstant;
|
||||
import com.kri.kart.server.common.enums.WordMergeMode;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.statistics.NlpDictionaryWordDto;
|
||||
import com.kri.kart.server.dto.statistics.NlpTokenDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsWordDto;
|
||||
import com.kri.kart.server.dto.statistics.SurveyResponseDto;
|
||||
import com.kri.kart.server.persistence.repository.NlpRepository;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
/** Word frequencies of open text answers, using the Report DB NLP dictionary and tag scopes. */
|
||||
@Service
|
||||
@@ -24,48 +30,147 @@ import org.springframework.web.util.HtmlUtils;
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class StatisticsTextService {
|
||||
|
||||
// Noun family for WordMergeMode.NOUN: nouns, foreign words and Chinese characters.
|
||||
private static final Set<String> NOUN_FAMILY_TAGS =
|
||||
Set.of("NNG", "NNP", "NNB", "NR", "NP", "SL", "SH");
|
||||
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
|
||||
|
||||
private final NlpRepository nlpRepository;
|
||||
private final KiwiNlpService kiwiNlpService;
|
||||
private final StatisticsSourceService statisticsSourceService;
|
||||
|
||||
/**
|
||||
* Keeps the existing behavior: no synonyms or stopwords, the same word with a different tag is
|
||||
* counted separately and compound nouns are not merged.
|
||||
*/
|
||||
public List<StatisticsWordDto> analyze(
|
||||
ProjectRefDto project, String qid, List<SurveyResponseDto> responses) {
|
||||
return analyze(project, qid, responses, false, WordMergeMode.NONE, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the REPORT_NLP_WORD synonyms (rows with SOURCE_TEXT), the stopwords (불용어, rows
|
||||
* tagged STOP) and the given merge options.
|
||||
*/
|
||||
public List<StatisticsWordDto> analyze(
|
||||
ProjectRefDto project,
|
||||
String qid,
|
||||
List<SurveyResponseDto> responses,
|
||||
WordMergeMode mode,
|
||||
int compoundNounMaxTokens) {
|
||||
return analyze(project, qid, responses, true, mode, compoundNounMaxTokens);
|
||||
}
|
||||
|
||||
private List<StatisticsWordDto> analyze(
|
||||
ProjectRefDto project,
|
||||
String qid,
|
||||
List<SurveyResponseDto> responses,
|
||||
boolean extended,
|
||||
WordMergeMode mode,
|
||||
int compoundNounMaxTokens) {
|
||||
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));
|
||||
// 불용어 (STOP) rows are not dictionary words: they are never registered in Kiwi.
|
||||
List<NlpDictionaryWordDto> dictionary = new ArrayList<>();
|
||||
Set<String> stopwords = new HashSet<>();
|
||||
for (NlpDictionaryWordDto word : nlpRepository.words(project.pkey(), qid)) {
|
||||
if (isStopwordRow(word)) {
|
||||
String stopword = stopwordKey(word.getWordText());
|
||||
if (stopword != null) {
|
||||
stopwords.add(stopword);
|
||||
}
|
||||
} else {
|
||||
dictionary.add(word);
|
||||
}
|
||||
}
|
||||
// The original overload ignores synonym rows and does not merge compound nouns.
|
||||
List<NlpTokenDto> tokens =
|
||||
kiwiNlpService.tokenize(texts, nlpRepository.words(project.getPkey(), qid));
|
||||
// The same word with a different tag is counted separately, in first-appearance order.
|
||||
extended
|
||||
? kiwiNlpService.tokenize(texts, dictionary, compoundNounMaxTokens)
|
||||
: kiwiNlpService.tokenize(texts, dictionary);
|
||||
// Count each word and tag pair in first-appearance order.
|
||||
LinkedHashMap<NlpTokenDto, Long> counts = new LinkedHashMap<>();
|
||||
for (NlpTokenDto token : tokens) {
|
||||
if (isCounted(token, selectedTags)) {
|
||||
// Stopwords apply to the final word after synonyms and compound merging, for every tag.
|
||||
boolean stopword = extended && stopwords.contains(stopwordKey(token.text()));
|
||||
if (!stopword && isCounted(token, selectedTags)) {
|
||||
counts.merge(token, 1L, Long::sum);
|
||||
}
|
||||
}
|
||||
// Stable sort: equal counts keep their first-appearance order.
|
||||
return counts.entrySet().stream()
|
||||
return merge(counts, mode == null ? WordMergeMode.NONE : mode).entrySet().stream()
|
||||
.sorted(Map.Entry.<NlpTokenDto, Long>comparingByValue().reversed())
|
||||
.limit(KartConstant.TOP_WORD_LIMIT)
|
||||
.map(entry -> toWord(entry.getKey(), entry.getValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sums the same text across mergeable tags. The merged word keeps the tag with the highest count
|
||||
* (first appearance on ties) and the position of its first appearance.
|
||||
*/
|
||||
private LinkedHashMap<NlpTokenDto, Long> merge(
|
||||
LinkedHashMap<NlpTokenDto, Long> counts, WordMergeMode mode) {
|
||||
if (mode == WordMergeMode.NONE) {
|
||||
return counts;
|
||||
}
|
||||
LinkedHashMap<NlpTokenDto, LinkedHashMap<String, Long>> groups = new LinkedHashMap<>();
|
||||
for (Map.Entry<NlpTokenDto, Long> entry : counts.entrySet()) {
|
||||
NlpTokenDto token = entry.getKey();
|
||||
boolean mergeable = mode == WordMergeMode.ALL || NOUN_FAMILY_TAGS.contains(token.tag());
|
||||
NlpTokenDto key = mergeable ? new NlpTokenDto(token.text(), null) : token;
|
||||
groups.computeIfAbsent(key, ignored -> new LinkedHashMap<>()).put(token.tag(), entry.getValue());
|
||||
}
|
||||
LinkedHashMap<NlpTokenDto, Long> result = new LinkedHashMap<>();
|
||||
for (Map.Entry<NlpTokenDto, LinkedHashMap<String, Long>> group : groups.entrySet()) {
|
||||
String tag = null;
|
||||
long best = 0;
|
||||
long total = 0;
|
||||
for (Map.Entry<String, Long> tagCount : group.getValue().entrySet()) {
|
||||
total += tagCount.getValue();
|
||||
if (tag == null || tagCount.getValue() > best) {
|
||||
tag = tagCount.getKey();
|
||||
best = tagCount.getValue();
|
||||
}
|
||||
}
|
||||
result.put(new NlpTokenDto(group.getKey().text(), tag), total);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 불용어 row: WORD_TAG is STOP, ignoring case and surrounding spaces. */
|
||||
private boolean isStopwordRow(NlpDictionaryWordDto word) {
|
||||
String tag = StringUtil.normalizeBlank(word.getWordTag());
|
||||
return KartConstant.STOPWORD_TAG.equalsIgnoreCase(tag);
|
||||
}
|
||||
|
||||
/** Stopword comparison key: trimmed, spaces collapsed and case-insensitive. */
|
||||
private String stopwordKey(String text) {
|
||||
String normalized = StringUtil.normalizeBlank(text);
|
||||
return normalized == null
|
||||
? null
|
||||
: WHITESPACE.matcher(normalized).replaceAll(" ").toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private StatisticsWordDto toWord(NlpTokenDto token, long count) {
|
||||
return new StatisticsWordDto(token.text(), token.tag(), count);
|
||||
}
|
||||
|
||||
/** Answers of the question and its sub-keys, grouped by key in first-appearance order. */
|
||||
private List<String> answerTexts(String qid, List<SurveyResponseDto> responses) {
|
||||
Predicate<String> valueKeys = statisticsSourceService.valueKeys(qid);
|
||||
LinkedHashSet<String> keys = new LinkedHashSet<>();
|
||||
responses.forEach(
|
||||
response ->
|
||||
response.values().keySet().stream()
|
||||
.filter(key -> key.equals(qid) || key.startsWith(qid + "_"))
|
||||
.filter(valueKeys)
|
||||
.forEach(keys::add));
|
||||
List<String> texts = new ArrayList<>();
|
||||
for (String key : keys) {
|
||||
responses.stream()
|
||||
.map(response -> response.values().get(key))
|
||||
.filter(Objects::nonNull)
|
||||
.map(value -> HtmlUtils.htmlUnescape(value.replace('¸', ',')))
|
||||
.map(statisticsSourceService::textAnswer)
|
||||
.forEach(texts::add);
|
||||
}
|
||||
return texts;
|
||||
|
||||
@@ -19,7 +19,7 @@ public class QuestionImportService {
|
||||
|
||||
public List<ImportQuestionDto> prepare(UploadTableDto table) {
|
||||
List<ImportQuestionDto> result = new ArrayList<>();
|
||||
List<List<String>> rows = table.getRows();
|
||||
List<List<String>> rows = table.rows();
|
||||
int first = 0;
|
||||
while (first < rows.size() && !rows.get(first).get(0).matches("[A-Za-z][A-Za-z0-9]*")) {
|
||||
first++;
|
||||
@@ -86,6 +86,17 @@ public class QuestionImportService {
|
||||
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();
|
||||
if (!labels.isEmpty()) {
|
||||
dataset.set(itemType, labels);
|
||||
@@ -209,7 +220,7 @@ public class QuestionImportService {
|
||||
info.put(textKey, label.get("label").asText() + "(기타)");
|
||||
}
|
||||
}
|
||||
if (itemType.equals("single")) {
|
||||
if (itemType.equals("single") || itemType.equals("rank")) {
|
||||
for (var label : labels) {
|
||||
if (label.path("etc").asText().equals("1")) {
|
||||
String value = label.get("value").asText();
|
||||
|
||||
@@ -6,10 +6,12 @@ import com.kri.common.feature.json.JsonUtil;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.kart.server.dto.upload.ImportResponseDto;
|
||||
import com.kri.kart.server.dto.upload.UploadTableDto;
|
||||
import com.kri.kart.server.service.derived.DerivedComputationService;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
@@ -24,13 +26,21 @@ public class ResponseImportService {
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
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")) {
|
||||
if (headers.stream().noneMatch(header -> header.equalsIgnoreCase(required))) {
|
||||
throw BusinessException.badRequest("응답 파일의 고정 헤더를 확인해 주세요.");
|
||||
}
|
||||
}
|
||||
if (table.getRows().size() < 2) {
|
||||
if (table.rows().size() < 2) {
|
||||
throw BusinessException.badRequest("별칭 행 다음에 업로드할 응답이 필요합니다.");
|
||||
}
|
||||
List<String> roots =
|
||||
@@ -41,8 +51,8 @@ public class ResponseImportService {
|
||||
.toList();
|
||||
List<ImportResponseDto> result = new ArrayList<>();
|
||||
String now = DateTimeUtil.nowKstLocalDateTime().format(TIMESTAMP);
|
||||
for (int rowIndex = 1; rowIndex < table.getRows().size(); rowIndex++) {
|
||||
var row = table.getRows().get(rowIndex);
|
||||
for (int rowIndex = 1; rowIndex < table.rows().size(); rowIndex++) {
|
||||
var row = table.rows().get(rowIndex);
|
||||
String idkey = value(headers, row, "IDKEY");
|
||||
String status = value(headers, row, "Status");
|
||||
String start = value(headers, row, "start_date");
|
||||
@@ -74,6 +84,9 @@ public class ResponseImportService {
|
||||
|| key.startsWith("T" + root + "_"))) {
|
||||
continue;
|
||||
}
|
||||
if (DerivedComputationService.isDerivedKey(key, derivedIds)) {
|
||||
continue;
|
||||
}
|
||||
String cell = row.get(col).trim().replace(".00", "");
|
||||
if (cell.isEmpty()) {
|
||||
continue;
|
||||
|
||||
@@ -22,7 +22,7 @@ public class UploadArchiveService {
|
||||
}
|
||||
|
||||
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 =
|
||||
type
|
||||
+ "_"
|
||||
|
||||
@@ -6,4 +6,14 @@ kri:
|
||||
url: jdbc:mysql://db-md87m.vpc-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8
|
||||
username: kriit
|
||||
password: it#51304
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
kart:
|
||||
share:
|
||||
public-origin: https://test-kart.kric.com
|
||||
database:
|
||||
konkiwi:
|
||||
url: 'jdbc:sqlserver://mssql-7sq2n.vpc-cdb.ntruss.com;databaseName={konkiwi};encrypt=false'
|
||||
username: 'kadmin'
|
||||
password: 'it#51304'
|
||||
maximum-pool-size: 5
|
||||
@@ -6,4 +6,8 @@ kri:
|
||||
url: jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8
|
||||
username: kriit
|
||||
password: it#51304
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
kart:
|
||||
share:
|
||||
public-origin: http://localhost:4014
|
||||
@@ -6,4 +6,14 @@ kri:
|
||||
url: jdbc:mysql://db-md87m.vpc-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8
|
||||
username: kriit
|
||||
password: it#51304
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
kart:
|
||||
share:
|
||||
public-origin: https://kart.kric.com
|
||||
database:
|
||||
konkiwi:
|
||||
url: 'jdbc:sqlserver://mssql-7sq2n.vpc-cdb.ntruss.com;databaseName={konkiwi};encrypt=false'
|
||||
username: 'kadmin'
|
||||
password: 'it#51304'
|
||||
maximum-pool-size: 5
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user