261016_01_ENH: 1차 마이그레이션 완료
This commit is contained in:
@@ -20,6 +20,7 @@ Source: .agent/consumer-references/platform-capabilities.md
|
||||
- JWT and API-key authentication integrate with Spring Security. API-key JPA preload requires Spring Data JPA; a consumer-provided claims provider can be used without JPA.
|
||||
- Common Web may register error handling, tracing/MDC, request-user resolution, enum conversion, and CORS behavior. Check for overlap before defining consumer-local equivalents.
|
||||
- Swagger support requires springdoc and defines the shared Bearer/API-key schemes and grouped paths.
|
||||
- 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.
|
||||
- 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`.
|
||||
|
||||
@@ -15,7 +15,15 @@ shared_contracts:
|
||||
- kri-common
|
||||
|
||||
databases:
|
||||
- id: primary
|
||||
- id: kon
|
||||
engine: mssql
|
||||
role: primary
|
||||
role: survey-data
|
||||
access: read-write
|
||||
- id: konkiwi
|
||||
engine: mssql
|
||||
role: survey-data
|
||||
access: read-write
|
||||
- id: report
|
||||
engine: mssql
|
||||
role: shared-report-data
|
||||
access: read-write
|
||||
|
||||
@@ -1,8 +1,185 @@
|
||||
## Generated Spring Boot Repository Rules
|
||||
## KART Server Repository Rules
|
||||
|
||||
- This backend application was generated by `@kri/create-spring-app` with Java 17 and Spring Boot 3.5.7.
|
||||
- Consume KriCommon through `com.kri.common:starter:beta.1.6.8`; do not change that approved version or duplicate shared behavior without explicit approval.
|
||||
- The selected primary database is `mssql`. Preserve its configured dialect, driver, transaction, schema, and migration conventions.
|
||||
- Keep controllers thin and preserve the generated service, DTO, persistence, configuration, QueryDSL, JDBC, and optional MyBatis boundaries.
|
||||
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
|
||||
- Use the repository Gradle Wrapper and run `.\gradlew.bat compileJava` followed by focused tests for relevant changes.
|
||||
- Java 17, Spring Boot 3.5.7, KriCommon `com.kri.common:starter:beta.1.6.9`.
|
||||
- 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.
|
||||
- Share-link grants allow scoped report reads and aggregate Excel only. Deny raw exports and management writes. Resolve grants from verified authentication and stored permissions, never request JSON.
|
||||
- Per explicit user instruction and internal convention, connection credentials and runtime settings are stored directly in application.yml. Do not replace them with environment placeholders or print secrets. Do not connect to shared databases without explicit environment authorization. Tests must disable database access or use synthetic settings.
|
||||
- Bind write transactions to the named source; a default kart (Report DB) transaction cannot encompass KON/KONKIWI writes. No schema creation or automatic migrations.
|
||||
- Preserve current Excel workbook format and non-weighted calculation semantics.
|
||||
- Generated AGENTS.md/CLAUDE.md are read-only; change .agent sources and recompose.
|
||||
- Verify with .\\gradlew.bat compileJava and focused tests, then build. Tests use synthetic values and do not connect to databases.
|
||||
- Per user decision, src/test (tests and fixtures) is kept locally and excluded from Git by .gitignore. Run local tests when present; do not stage or commit test files.
|
||||
|
||||
- Follow Contact's controller/service/dto/persistence/config/common package structure. Place enums under common/enums and use KriCommon CodeEnum for coded values. Do not introduce domain/access or domain/project packages.
|
||||
|
||||
## User-defined coded enum convention
|
||||
|
||||
- Follow the user's standard form for enums implementing KriCommon CodeEnum<T>.
|
||||
- Use @Getter(onMethod_ = @JsonValue), @RequiredArgsConstructor and @Schema(description = "...").
|
||||
- Store the code in a private final boxed field (e.g. Integer code).
|
||||
- Declare @JsonCreator(mode = JsonCreator.Mode.DELEGATING) on static fromCode(T code).
|
||||
- Return null for a null code; iterate values() and compare s.code.equals(code); throw IllegalArgumentException("Unknown <EnumName> code: " + code) for unknown codes.
|
||||
- Do not replace this pattern with JsonNode parsing, a custom getCode(), or CodeEnumUtils.fromCode. Validate required request fields separately.
|
||||
- Use the common MVC CodeEnum converter for path/query parameters; do not add a ProjectType-specific converter without a concrete requirement.
|
||||
|
||||
- Do not predefine speculative authentication/permission/page enums or grant abstractions. Add only what actual endpoints and Contact-style authentication require. External-link access restrictions remain requirements for implementation.
|
||||
|
||||
## Authorization implementation convention
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
## Phase 1 migration decisions
|
||||
|
||||
- Implement the seven agreed auth/project/quota routes (singular project, /project/list, quota at /quota/{projectType}/{pkey}/list).
|
||||
- The user approved list/summary team/assignment and derived-management list visibility. Apply the current Read visibility rules below; other general authorization remains separate. Keep common authentication and original business filters/calculations.
|
||||
- Project list/summary use the current frontend's v2 KON/KIWI portions; progress and quota use the KON v1 functions. Exclude NEWSSAK data, preserve v2 must-view overrides and the two-stage source/merged summary ordering.
|
||||
- Replace User.getDinIDs() with GET /api/v1/user/list, filtering exact userTeam S101/S201. Bind userId values into MKEY NOT IN before candidate TOP 50 selection; never silently omit the exclusion on upstream failure.
|
||||
- The user supplied a dedicated KART Intranet API key, configured literally at kri.auth.apikey.key in application.yml. Do not copy Contact credentials or print the key.
|
||||
- Unit/mocked application checks are not real database result-equivalence verification. Do not claim live migration acceptance without comparing actual old/new results.
|
||||
|
||||
## Latest user conventions
|
||||
|
||||
- Place mapper XML files together in src/main/resources/mybatis/mapper, distinguishing by file names such as ProjectMapper.xml, UserMapper.xml and LogMapper.xml. Keep source-specific SqlSessionFactory registration isolated.
|
||||
- Use the Intranet userRole value directly in JWT/RequestUserContext; do not convert it back to legacy isAdmin.
|
||||
- Legacy isAdmin 0/1 correspond to userRole 1001, 5 to userRole 2001 or 3001, and 7 to userRole 9001. Legacy isAdmin 4/6 are abolished. Never infer 2001 versus 3001 from legacy 5 alone.
|
||||
- All REPORT_MEMBER logins use userRole=9001. Do not query is_kri for role calculation or grant a special administrator role to a particular account. Intranet userRole is preserved directly.
|
||||
|
||||
- Group mapper/repository names by business purpose, not database name. findMember belongs to UserMapper/UserRepository, mustViewPkeys to ProjectMapper/ProjectRepository, loginLog to LogMapper/LogRepository. Use explicit MyBatis databaseId survey/kart to isolate statement registration while retaining each operation's original database source.
|
||||
|
||||
- quotaSets belongs to QuotaMapper/QuotaRepository, using the survey databaseId and the explicitly routed KON/KONKIWI session. Preserve its existing SQL and output ordering.
|
||||
|
||||
- Match Contact application.yml conventions: kri.auth.apikey for key/header/enabled/service-code/allowed-paths/preload/admin fields; kri.api-url for intranet-extension; noti-hub and short-url are unused. Do not invent another Intranet properties prefix. Tests must disable common API-key preload/database access. Do not optimize or rewrite existing queries unless the user explicitly requests application of an agreed change.
|
||||
|
||||
- Like Contact, omit the kri.auth.jwt block from application.yml and use common JWT defaults (24-hour access-token lifetime and default signing settings). Keep JWT login/authentication itself. Tests may override the signing secret with synthetic values.
|
||||
|
||||
- API Key DB settings belong in application-local/dev/prod.yml under kri.auth.apikey.db. Common API Key persistence alone uses JPA/MySQL; KON/KONKIWI/kart (Report DB) remain MyBatis. Exclude default Boot JPA configuration to avoid binding it to a business datasource.
|
||||
- Follow Contact readability: two-space indentation, explicit main-source imports, separate annotations and fields, braces around conditionals/loops, and clear method spacing. GET query dates use Spring DateTimeFormat; JsonFormat alone only affects JSON mapping.
|
||||
|
||||
- Keep summary in ProjectMapper/ProjectRepository. daily/type/loi and dateRange belong to ProgressMapper/ProgressRepository, namespace kart.Progress and databaseId survey. Preserve SQL text, API paths and source routing during separation.
|
||||
|
||||
- Use CDATA for static SQL sections containing XML-sensitive comparisons instead of lt/gt entity escapes. Keep MyBatis if/foreach/include tags outside CDATA and preserve decoded SQL text.
|
||||
|
||||
## Phase 2 migration decisions
|
||||
|
||||
- Implement only question list/detail, progress screen/custom, and bookmark list. Do not implement auth/session or quota aggregation in this phase.
|
||||
- QuestionMapper/QuestionRepository use survey sessions. Match KON getQuestionList/organizeQuestionList expansion and select the first exact QID after expansion; return arrays. User explicitly confirmed KIWI profile questions only for userRole=1001.
|
||||
- ProgressMapper screen preserves OPENJSON value DESC ranking per pkey/idkey, rn=1, Korean_Wansung_CI_AS join and date filtering after ranking. Custom progress is a URL/file list, not aggregate computation.
|
||||
- Custom progress local files use kri.kart.progress.append-directory; deployment must supply the existing report_append directory. Keep first KON URL then ordered append rows; only type 0 checks local file existence.
|
||||
- BookmarkMapper/BookmarkRepository use the kart session (Report DB) and the original pure pkey, page, public-or-own-private filter and order. Identity/IS_MINE must use RequestUserContext, never userId submitted as a query parameter.
|
||||
## Visit/site logging
|
||||
|
||||
- POST /api/v1/log/visit uses LogService/LogRepository/LogMapper, kart session (Report DB) and kartTransactionManager. TB_SITE_LOG is server-owned: expose no /log/site HTTP endpoint; call LogService.writeSiteLog from business operations. Identity and IP come only from RequestUserContext. AuthService calls LogService.writeLoginLog rather than LogRepository directly.
|
||||
- Preserve TB_VISIT_LOG/TB_SITE_LOG columns and pure pkey. Visit accepts paired optional projectType/pkey. Site JSON uses legacy v2 projectCode/LOGTITLE/LOGCONTENT plus projectType; support serialized JSON content and bind all SQL values.
|
||||
- Preserve legacy best-effort behavior and text/plain PASS response. Never print payload, SQL, actor or IP on audit failures. Do not add new automatic events to existing reads without a legacy event or a user decision.
|
||||
- Future report aggregation, bookmark mutations, imports and share-link creation should call LogService.writeSiteLog at their legacy event points. Record QUOTA VIEW in the future quota-result operation instead of a separate frontend logging API; do not record it during quota-list loading.
|
||||
## Object naming convention
|
||||
|
||||
- Name Repository, Service, Client and session-provider dependencies by their type in lowerCamelCase, e.g. logRepository, authService, intranetExtensionApiClient and surveySessionProvider. Use source-qualified session names such as kartSqlSessionTemplate.
|
||||
- Name DTO instances by their meaning without the Dto suffix, e.g. IntranetUserDto intranetUser and ReportMemberDto reportMember. Do not abbreviate these as logs, service, repository or employee.
|
||||
|
||||
## KriCommon reuse priority
|
||||
|
||||
- Before adding any utility, helper or infrastructure code, inspect KriCommon's existing capabilities and source. Reuse an existing API whenever its behavior matches; do not duplicate or wrap it only to change its name.
|
||||
- Blank-to-null trimming uses com.kri.common.feature.util.StringUtil.normalizeBlank(raw). Do not implement a local StringNormalizer or trimToNull equivalent.
|
||||
- Add local utilities only for behavior absent from KriCommon or when a documented semantic difference prevents reuse. Preserve migration output and validation semantics when replacing existing code.
|
||||
|
||||
## Derived list and bookmark mutations
|
||||
|
||||
- Do not implement assign: current legacy and new frontend sources contain no caller. Implement only GET /project/{projectType}/{pkey}/derived/list and bookmark POST/PUT/DELETE for this phase; keep singular project/bookmark paths.
|
||||
- DerivedMapper uses survey sources and the KON getOnlyDerivedList SELECT and order. Reuse QuestionService.organize for expansion; expose only original derived-list fields, without reverse/missingValue additions or regular-question/profile filters. Management list visibility is now role 1001 all teams, otherwise authenticated userTeam only; do not apply this filter to regular question/report metadata.
|
||||
- Bookmark mutations use the kart session (Report DB), existing columns and pure pkey. Preserve timestamp ID, per-page MAX+1 insertion order, JSON text and successful create/update ID responses. Delete returns a JSON boolean: true after successful deletion; frontend owns presentation messages. Keep standard errors for missing/conflicting targets and persistence failures. Owner/team come from RequestUserContext. Update only title/info/JSON/isOpen and constrain lookup/mutation by pkey+ID.
|
||||
- Preserve legacy deletion order adjustment across all pages of the same pkey; do not add a page condition. Reordering and deletion must roll back together through kartTransactionManager. Do not add schema constraints or pretend existing timestamp/MAX+1 concurrency guarantees uniqueness.
|
||||
- Call LogService for Insert/Update/Delete Bookmark with NEW/ORIGIN snapshots. Site audit writes use REQUIRES_NEW so best-effort audit failure cannot mark the business transaction rollback-only. Keep the legacy pre-delete audit point; such a log may remain if deletion fails.
|
||||
- Validation of create-page presence happens before service invocation; update-page is optional and does not change stored page. Preserve empty title/info and raw bookmark JSON text. Missing scoped IDs return 404, disappearing mutation targets 409, persistence failures use common error handling rather than empty success responses.
|
||||
## Upload forms and variable guide downloads
|
||||
|
||||
- Implement only GET /export/form/question and GET /project/{projectType}/{pkey}/export/form/data, /export/form/title and /export/guide in this phase. Keep existing octet-stream and file/sheet names.
|
||||
- Bundle the existing KON question-upload workbook unchanged. Its SHA-256 is DC557EC7E3296AA629589FE3BAAC9C4BFF1750205078D8E9CEFD5D71C477E584. Never regenerate it from metadata.
|
||||
- Header order is the fixed seven columns, add_column, userRole=1001 derived dataset headers, then STRUCTURE QINFO/question headers. Preserve legacy splitting, qid-to-variable replacement and duplicate-key position. Existing missing-project behavior returns the fixed header; actual persistence errors use common error handling.
|
||||
- Title form uses four original columns and Qorder, excludes description/MM_FILE and does not substitute empty explanation with title.
|
||||
- Guide uses raw QuestionRepository metadata with includeProfiles=false, not organized/expanded question rows. Preserve original attribute values, multi/open/rank ranges and labels, HTML decoding/tag removal, CR/LF conversion and negative zero-padded labels.
|
||||
- Reuse current KriCommon ExcelMapper and matching POI 5.5.1. Adapt its automatic widths and blank cells to the legacy plain EPPlus writer rather than duplicate a generic workbook utility. Preserve Unicode names with common basename extraction, unsafe-character removal and UTF-8 Content-Disposition; the common ASCII-only filename sanitizer would change the original name.
|
||||
- Downloads have no original SiteLog point: do not invent one. Test output against EPPlus-generated synthetic workbook fixtures and preserve the original question template bytes. Do not claim real database/production-file equivalence from synthetic checks.
|
||||
## General report and Kiwi NLP
|
||||
|
||||
- Implement POST /api/v1/project/{projectType}/{pkey}/statistics/result and common response/filter/dimension/aggregation components under service/statistics. Include text analysis in this operation; quota result and aggregate Excel remain follow-up work.
|
||||
- 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.
|
||||
- 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.
|
||||
## Statistics batch streaming
|
||||
|
||||
- POST /project/{projectType}/{pkey}/statistics/result accepts StatisticsBatchRequestDto.indexes plus shared StatisticsOptionsDto, and returns application/x-ndjson. No legacy single-index HTTP response is retained. TABULATION_0/1 use indexes=[""]. Keep single StatisticsRequestDto internally for the existing calculation engine.
|
||||
- Load questions once and union-projected response data once per request. Filter once; before each calculation restrict respondents to the storage roots that the corresponding single-index request would have selected. Preserve input order and duplicate positions, original N/%/NLP calculations and profile role rules. No cross-request cache is added.
|
||||
- Validate all input/metadata and load shared data before returning a stream. Emit result/error for each position, then complete with total/succeeded/failed. Do not expose internal errors or raw responses. NLP dictionary/tag queries remain per text dimension.
|
||||
- Use Spring ResponseBodyEmitter/applicationTaskExecutor, one compact JSON line per flush, 10-minute total timeout, request-scoped authentication preservation for ASYNC dispatch, and cancellation checks between calculations. Failed writes terminate the stream; never continue writing events to a lost connection.
|
||||
- Write the Get Report Data audit through LogService once per general statistics batch, without a Referer condition. Do not change shared DB schema or existing StatisticsMapper SQL. Frontend integration, package publication and operational proxy verification are separate tasks.
|
||||
|
||||
## Quota result
|
||||
|
||||
- POST /quota/{projectType}/{pkey}/{quotaOrder}/result is implemented as a dedicated single JSON operation. Use saved QUOTASET first ROW, joined COL and FILTER; request contains dataScope/startDate/endDate only. Keep quota/list unchanged.
|
||||
- Reuse common report data/filter/count/header services. Handle empty ROW separately from TABULATION, keep no subtotals, target ori_cnt and stored IS_USE/quotaId only for a single matching target. Never filter out disabled targets.
|
||||
- Preserve original computeQuota zero-target row removal, case-sum Total recomputation and Total column/row placement. Use null plus explicit undefined/infinite achievement state for zero targets, with original '-'/'∞' display. No targets return empty rows instead of the legacy index exception. Reject unconvertible statistic rows explicitly.
|
||||
- Parse saved legacy FILTER into AST only; support Q| QID or VARIABLE, boolean precedence/groups and documented condition operators. Reject unsupported grammar rather than ignoring it or executing SQL. No shared DB schema changes or execution.
|
||||
- Record QUOTA VIEW through LogService after scoped setting lookup, preserving QSTITLE/QSJSON and authenticated identity. Add no frontend logging API. Validate against 8 original C# postprocessing fixtures, filter tests, H2 mapping/routing and authenticated API checks. Live SQL Server/filter cases, frontend and aggregate Excel remain separate work.
|
||||
|
||||
## Share links and External authentication
|
||||
|
||||
- POST /project/{projectType}/{pkey}/share accepts realUrl and P/U; GET /share/{urlKey} is authenticated metadata; public POST /external/{urlKey}/login validates the link, issues common 24-hour JWT and increments landing count exactly once. Preserve case-sensitive URL_KEY and original /External/ public link path.
|
||||
- New REPORT_URL rows dual-write PKEY/PROJECT_TYPE/SKEY; reuse existing compatible rows without mass backfill. Legacy-only rows decode SKEY internally; partial fields, unknown type, NEWSSAK/mixed markers and mismatched keys are rejected. Do not expose SKEY or run DDL/shared DB changes.
|
||||
- The approved legacy raw AES-CBC key/IV are configured literally under kri.kart.share, without printing secrets. This narrowly scoped JCE adapter is necessary because common AES always derives its key through PBKDF2 and cannot reproduce original ciphertext.
|
||||
- Verified common authentication details with KART_EXTERNAL team and EXTERNAL:urlKey identity must pass stored project/page checks on every request. Use an explicit MVC allowlist; deny raw exports, static files, progress/custom links, management and cross-project APIs. Permit only current report/metadata/quota reads and scoped visit logging. Crosstab P forbids TABULATION modes. Ordinary role authorization remains deferred.
|
||||
- Preserve URL Copy and login logging through LogService, original REPORT ownership for normal identities and KON/KIWI names where applicable. Reuse/create are protected by kartTransactionManager and UPDLOCK/HOLDLOCK reads; do not claim uncoordinated old-server concurrency uniqueness. Frontend External remains separate. Aggregate Excel paths are now explicitly allowed only for matching project/page.
|
||||
|
||||
## Derived management and aggregate Excel
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
## Raw-data downloads
|
||||
|
||||
- POST /project/{projectType}/{pkey}/export/data accepts type COMPLETE(default, old com) or INCOMPLETE(old not), optional startDate/endDate. Exclude TEST for both; do not remove Status 999 from incomplete. Filter FN_LAST_TIME DATE inclusively; start-only means same day; end-only/reversed/unknown type fail 400 before persistence.
|
||||
- Reuse ExportService headers/guide and current Common ExcelMapper; retain DATA storage header, variable-alias row, respondent rows then GUIDE, plain string cells and original fixed/additional/role1001-derived/STRUCTURE order. No profile join, invented sort, new SiteLog or generic role authorization. Preserve original SQL UPPER/FOR XML PATH, ReplaceUnicodeEmpty, DISTINCT derived join, CAPI interviewer expressions and time functions.
|
||||
- External raw export remains denied by the existing explicit allowlist. All file responses use no-store. Keep authentication and userRole from RequestUserContext; ordinary visibility rules remain deferred.
|
||||
- Test against original C# synthetic ordinary/CAPI workbooks and bound MyBatis condition/routing/API checks. No live SQL Server or large-file equivalence claim; current raw query/workbook remain in memory, without new dependencies, cross-request cache or shared DB execution.
|
||||
## 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.
|
||||
- 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.
|
||||
- Validate against original C# SQL-capture synthetic fixtures, actual isolated H2 reset/JSON-string cases, all three operation rollbacks on both sources and multipart/authentication checks. These are not live SQL Server or production-file acceptance.
|
||||
## Service integration audit
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
## Server-to-server authentication
|
||||
|
||||
- User removed the redundant system-login/token-exchange requirement. Authenticate each server call directly through Common API Key; do not add /auth/system/login or consumer-local REPORT_EXTERNAL_SYS validation. Preserve regular login and scoped REPORT_URL external login. Keep incoming API Key claims and configured path restrictions under Common authentication.
|
||||
|
||||
|
||||
## Read visibility
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
4
.env.example
Normal file
4
.env.example
Normal file
@@ -0,0 +1,4 @@
|
||||
# Runtime DB/auth settings are explicitly stored in src/main/resources/application.yml.
|
||||
# Optional Maven repository credentials only; prefer user Gradle properties.
|
||||
GITEA_MAVEN_USER=
|
||||
GITEA_MAVEN_TOKEN=
|
||||
9
.gitignore
vendored
9
.gitignore
vendored
@@ -27,3 +27,12 @@ Thumbs.db
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Kiwi runtime model, installed separately
|
||||
nlp_model/
|
||||
|
||||
# Uploaded source files contain respondent data
|
||||
upload_data/
|
||||
|
||||
# Tests and fixtures are kept locally and not committed
|
||||
src/test/
|
||||
|
||||
@@ -245,6 +245,7 @@ When implementation is complete, report in Korean:
|
||||
- Prefer a shared feature or approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, crypto, or utility behavior locally.
|
||||
- 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.
|
||||
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.
|
||||
|
||||
### Required Shared References
|
||||
|
||||
374
README.md
374
README.md
@@ -1,81 +1,357 @@
|
||||
# kart-server
|
||||
|
||||
KART 백엔드 API
|
||||
KART 백엔드: Java 17 / Spring Boot 3.5.7 / KriCommon beta.1.6.9 / SQL Server + MyBatis, 포트 4015.
|
||||
|
||||
## 기술 구성
|
||||
## 설정
|
||||
|
||||
- Java 17
|
||||
- Spring Boot 3.5.7
|
||||
- `com.kri.common:starter:beta.1.6.4`
|
||||
- JPA + QueryDSL + JdbcTemplate
|
||||
- EmbeddedId 예제
|
||||
- MyBatis는 생성 옵션에 따라 포함
|
||||
사내 규약에 따라 DB URL·계정·비밀번호를 src/main/resources/application.yml에 명시한다. KON·KONKIWI·Report 정보는 기존 KART의 KonString·KiwiString·ReportString을 사용한다. local/dev/prod는 공통 설정을 상속하며, API Key 전용 DB 접속정보는 각 프로파일의 kri.auth.apikey.db에 명시한다. JWT는 Contact처럼 common의 기본 서명 설정과 유효기간 86400초를 사용하며 별도 yml 설정을 두지 않는다.
|
||||
|
||||
## Gitea Maven 인증
|
||||
Contact와 동일하게 Intranet URL은 kri.api-url.intranet-extension, API Key는 kri.auth.apikey.key, 헤더는 kri.auth.apikey.header-name에 둔다. 사용자가 제공한 KART 전용 키를 사용한다. 실제 Intranet 로그인과 프로젝트 목록/summary 조회에 사용한다. 키 미설정 또는 Intranet 로그인 실패·장애 시 REPORT_MEMBER 인증을 시도한다.
|
||||
|
||||
Windows 사용자 Gradle 설정:
|
||||
업무용 SQL Server 풀은 SQL 실행 전까지 연결을 열지 않는다. 공용 API Key 인증은 starter-data-jpa와 MySQL 드라이버를 사용하고 별도의 apiKeyDataSource/EntityManagerFactory/transaction-manager로 분리한다. 기본 Boot JPA 자동 설정은 제외하여 Report DB에 연결되지 않게 한다. API Key가 활성화되면 전용 JPA 초기화 및 preload 과정에서 해당 DB에 연결한다. 테스트는 DB를 비활성화하거나 가상 주소·모의 repository/client를 사용한다. 테스트 및 빌드에서 실제 DB/Intranet을 호출하지 않는다.
|
||||
|
||||
```text
|
||||
%USERPROFILE%\.gradle\gradle.properties
|
||||
```
|
||||
테스트 코드와 fixture(src/test)는 로컬에서만 유지하며 .gitignore로 Git에 올리지 않는다. 아래 각 항목의 "검증"·"테스트" 설명은 로컬 테스트 기준이며, 새로 내려받은 저장소에는 테스트가 포함되지 않는다.
|
||||
|
||||
```properties
|
||||
giteaUser=사용자명
|
||||
giteaToken=Gitea토큰
|
||||
```
|
||||
## 1차 API
|
||||
|
||||
또는 다음 환경변수를 사용할 수 있습니다.
|
||||
| 기능 | 경로 |
|
||||
|---|---|
|
||||
| 로그인 | POST /api/v1/auth/login |
|
||||
| 프로젝트 목록 | GET /api/v1/project/list |
|
||||
| 프로젝트 현황 최대 6개 | GET /api/v1/project/summary |
|
||||
| 쿼터 설정 목록 | GET /api/v1/quota/{projectType}/{pkey}/list |
|
||||
| 일별 현황 | GET /api/v1/project/{projectType}/{pkey}/progress/day |
|
||||
| 전체 상태 건수 | GET /api/v1/project/{projectType}/{pkey}/progress/type |
|
||||
| LOI 현황 | GET /api/v1/project/{projectType}/{pkey}/progress/loi |
|
||||
|
||||
```text
|
||||
GITEA_MAVEN_USER
|
||||
GITEA_MAVEN_TOKEN
|
||||
```
|
||||
projectType은 0=KON, 1=KIWI이며 pkey에는 legacy 마커를 넣지 않는다. type/loi의 날짜 조건은 startDate/endDate(yyyy-MM-dd)이며 양끝을 포함한다. 날짜를 둘 다 생략하면 전체 기간이다. day는 기존처럼 날짜 범위 파라미터가 없다.
|
||||
|
||||
## 실행
|
||||
로그인 요청은 {userId,userPw}, 응답은 {accessToken,user,memberRedirect}다. user는 공용 JwtUserClaimsDto다. Intranet 실패/장애 시 is_use=1인 REPORT_MEMBER를 조회하고 모든 REPORT_MEMBER 사용자에게 userRole=9001을 부여한다. is_kri 기반 역할 계산과 특정 계정 관리자 예외는 사용하지 않는다. 로그인 이력은 기존 TB_LOGIN_LOG에 저장하며 저장 실패가 성공한 로그인을 취소하지 않는다.
|
||||
|
||||
Windows:
|
||||
조회 응답은 DTO 배열이며 기존 값의 의미를 유지하고 필드명은 camelCase로 정리했다. 목록은 projectType,rowNumber,pkey,title,surveyType,status,gkey,mkey,createDate를 반환한다. summary는 프로젝트 정보와 allCount/ongoingCount/screenCount/quotaCount/completeCount를 반환한다. 암호화 security와 ver/iskiwi는 projectType+pkey로 대체한다.
|
||||
|
||||
프로젝트 목록/summary는 현재 화면의 v2 KON/KIWI SQL을 기준으로 한다. 목록의 REPORT_MUST_VIEW_PROJECT 기간 예외, KIWI 접두 제목 및 통합 정렬을 유지한다. summary는 소스별 후보 TOP 50 → 상태/날짜 정렬 TOP 6 → 통합 날짜 정렬 최대 6개 순서다. CTE 최적화는 사용자 실환경에서 성능이 악화되어 기존 SQL로 복구했다. 원본 SQL fixture를 회귀 비교 기준으로 유지한다. 추가 최적화는 실제 SQL Server 실행계획과 인덱스, IO/TIME 측정 후 진행한다. v1의 단일 소스 ID 기준과 구분한다.
|
||||
|
||||
담당자 제외는 GET /api/v1/user/list에서 S101/S201의 userId를 한 번 조회해 두 소스의 MKEY NOT IN 바인딩 조건으로 적용한다. summary는 후보 TOP 50 선정 전에 제외한다. API 오류/잘못된 응답은 503이며 제외 조건이 빠진 목록을 반환하지 않는다. 정상 빈 사용자 목록은 제외 대상이 없는 것으로 처리한다. 실제 API 목록과 기존 person 테이블의 동등성은 별도 검수가 필요하다.
|
||||
|
||||
progress/type은 조사 유형별 그룹이 아니라 전체 상태 건수 1행이다. day는 기존 INDEX 존재 조건과 날짜 정렬을 유지한다. LOI는 완료/비TEST 응답의 정수 평균·2.5% 순위 경계 및 기존 시간 문자열을 유지한다. quota/list는 저장된 설정 JSON을 문자열 그대로 반환한다.
|
||||
|
||||
## 구조와 후속 범위
|
||||
|
||||
Contact의 controller/service/dto/persistence/config/common 구조를 따른다. enum은 common/enums에 두고 사용자가 지정한 CodeEnum/Lombok/Jackson 형태를 사용한다. mapper XML은 mybatis/mapper 아래의 ProjectMapper.xml·ProgressMapper.xml·UserMapper.xml·LogMapper.xml·QuotaMapper.xml로 구분하고 SqlSessionTemplate와 transaction-manager를 명시한다.
|
||||
|
||||
프로젝트 목록·최신 6개 및 파생변수 관리 목록의 조회 권한은 RequestUserContext의 getUserRole()/getUserTeam()을 기준으로 적용한다. 상세 규칙은 아래 조회 권한 항목을 따른다. 공용 JWT/API Key 인증은 유지한다. External 전용 인증과 링크의 프로젝트/페이지 제한은 아래 공유 링크 기능에서 구현한다. 현재 상태를 운영 전환 준비 완료로 간주하지 않는다.
|
||||
|
||||
## 검증
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat bootRun
|
||||
.\gradlew.bat build
|
||||
```
|
||||
|
||||
Linux/macOS:
|
||||
테스트는 로그인 fallback·24시간 JWT·부서 제외·소스 분리·목록/summary 정렬·날짜/LOI·SQL 바인딩·7개 경로·공용 보안 필터·지연 풀 생성과 OpenAPI를 검증한다. 생성된 1차 명세는 테스트 후 build/phase1-openapi.json에서 확인할 수 있다. 실제 SQL Server 결과와 기존 응답 표본의 비교 검수는 아직 수행하지 않았다.
|
||||
|
||||
```bash
|
||||
./gradlew bootRun
|
||||
Gitea Maven 인증은 사용자 Gradle 설정의 giteaUser/giteaToken 또는 GITEA_MAVEN_USER/GITEA_MAVEN_TOKEN으로 공급한다.
|
||||
|
||||
Agent Harness local ID는 kart-server다. .agent 원본을 수정하고 검증하며 생성된 AGENTS.md/CLAUDE.md는 직접 편집하지 않는다.
|
||||
|
||||
mapper는 업무별 파일로 나누고 databaseId=survey/kart로 쿼리 등록 대상을 분리한다. ProjectMapper의 mustViewPkeys는 kart 세션(Report DB)을 사용하며 설문 쿼리는 KON/KONKIWI 세션을 사용한다. 사용자 인증과 로그인 이력도 각각 UserRepository/LogRepository에서 kart 세션(Report DB)을 명시한다.
|
||||
|
||||
공용 API Key 설정은 enabled/preload-on-startup/admin-api-enabled=true, service-code=kart-server이며 allowed-paths가 빈 목록이므로 경로 제한 없이 API Key 인증을 허용한다. 내부 관리 API 허용 IP는 Contact와 동일한 211.254.145.130이다. 일반 테스트에서는 API Key 활성화·preload·관리 API를 끈다. 전용 분리 테스트는 H2 메모리 DB에만 연결하여 활성 키·서비스 코드 필터 및 업무 DB와의 분리를 검증한다. 실제 키 등록/preload/관리 API 실행은 별도 실환경 검증이 필요하다.
|
||||
|
||||
ProjectMapper는 list/summary/mustViewPkeys를 유지하고 ProgressMapper/ProgressRepository는 daily/type/loi와 날짜 범위 조건을 담당한다. 현황 SQL과 API 경로는 분리 전과 동일하다.
|
||||
|
||||
## 2차 API
|
||||
|
||||
| 기능 | 경로 |
|
||||
|---|---|
|
||||
| 문항 목록 | GET /api/v1/project/{projectType}/{pkey}/question/list |
|
||||
| 문항 상세 | GET /api/v1/project/{projectType}/{pkey}/question/{qid} |
|
||||
| 스크린 현황 | GET /api/v1/project/{projectType}/{pkey}/progress/screen |
|
||||
| 사용자 정의 현황 URL/파일 목록 | GET /api/v1/project/{projectType}/{pkey}/progress/custom |
|
||||
| 북마크 목록 | GET /api/v1/project/{projectType}/{pkey}/bookmark/list?page=TABULATION |
|
||||
|
||||
문항 상세는 일반/파생 문항을 open·rank·attr 규칙대로 펼친 후 정확한 QID의 첫 행을 배열로 반환한다. 없으면 빈 배열이다. 메타데이터 JSON은 문자열 필드를 유지한다. KIWI 프로필 문항은 userRole=1001일 때만 포함한다. QuestionMapper는 KON/KONKIWI 세션을 사용한다.
|
||||
|
||||
스크린 현황은 startDate/endDate(yyyy-MM-dd)를 받으며 기존처럼 마지막 JSON 시간을 선정한 후 날짜 양끝을 포함해 필터링한다. 사용자 정의 현황은 첫 KON report URL과 REPORT_APPEND 첨부 목록이다. append_type=0 파일은 kri.kart.progress.append-directory(기본 ../report_append)에서 존재 여부를 확인하므로 배포 시 기존 파일 디렉터리를 제공해야 한다. 이 API는 파일 다운로드/복사를 하지 않으며 기존 URL·상대 경로를 유지한다.
|
||||
|
||||
북마크는 page가 필수이고 값을 임의 변환하지 않는다. 기존 소비자는 TABULATION/CROSSTAB을 사용한다. BookmarkMapper는 kart 세션(Report DB)에서 공개 항목과 인증된 사용자 본인의 비공개 항목을 BOOKMARK_ORDER로 조회한다. userId는 요청 파라미터로 받지 않으며 isMine은 문자열 0/1이다. Report 테이블의 기존 pure pkey 저장을 유지한다.
|
||||
|
||||
이번 범위에 쿼터 집계와 auth/session은 포함하지 않는다. 조회 권한은 아래 조회 권한 항목에 따라 적용한다. 개별 프로젝트 API의 공통 접근 검사 및 변경 기능의 역할 제한은 별도 범위다. 테스트가 생성하는 build/phase2-openapi.json에는 1·2차 명세가 포함된다. H2 문항/북마크 SQL 및 복합 문항 변환, 인증·입력 검증·명세·파일 존재 여부를 검증하며 실제 SQL Server 응답/OPENJSON/collation 검수는 별도 필요하다.
|
||||
## 방문·활동 로그
|
||||
|
||||
- POST /api/v1/log/visit: {projectType,pkey,logContent}. 프로젝트 정보는 함께 생략할 수 있으며 logContent에 페이지 URL/정보를 보낸다.
|
||||
- TB_SITE_LOG: 서버 내부 LogService.writeSiteLog로 기록한다. 별도 HTTP API는 제공하지 않는다.
|
||||
|
||||
사용자 ID와 IP는 RequestUserContext에서 가져온다. Report DB의 기존 TB_VISIT_LOG/TB_SITE_LOG 컬럼에 바인딩하여 저장한다. SITE JSON은 기존 프런트의 v2 projectCode/LOGTITLE/LOGCONTENT 형식에 projectType을 추가한다. 방문 로그의 V_PKEY는 순수 pkey이며 프로젝트가 없으면 빈 문자열이다. 스키마 변경은 없다.
|
||||
|
||||
방문 로그 응답은 기존처럼 text/plain PASS다. 로그 저장 실패는 경고만 남기는 기존 best-effort 정책을 유지하므로 PASS가 DB 저장 성공을 보장하지는 않는다. 활동 로그는 서버 업무 처리 지점에서 LogService.writeSiteLog를 호출한다. 현재 읽기 기능에는 기존 SITE 로그 지점이 없으며 보고서 집계·북마크 변경·업로드·링크 복사는 후속 구현 때 연결한다. 기존 프런트에서 전송하던 QUOTA VIEW도 후속 쿼터 결과 처리에서 기록한다. AuthService는 LogService.writeLoginLog를 통해 로그인 로그를 기록한다.
|
||||
## 파생 변수 목록·북마크 변경
|
||||
|
||||
- GET /api/v1/project/{projectType}/{pkey}/derived/list
|
||||
- POST /api/v1/project/{projectType}/{pkey}/bookmark
|
||||
- PUT /api/v1/project/{projectType}/{pkey}/bookmark/{bookmarkId}
|
||||
- DELETE /api/v1/project/{projectType}/{pkey}/bookmark/{bookmarkId}
|
||||
|
||||
파생 목록은 KON/KONKIWI의 DERIVED_VARIABLE 원본 메타데이터·정렬과 기존 문항 펼치기를 사용한다. userRole=1001은 전체 파생변수, 그 외에는 인증된 본인 팀의 GKEY만 조회한다. assign은 현재 프런트에 사용처가 없어 구현하지 않는다.
|
||||
|
||||
북마크 요청은 bookmarkPage(생성 시 필수), bookmarkTitle, bookmarkInfo, bookmarkJson(원본 JSON 문자열), isOpen(0/1)이다. 생성·수정은 ID를 text/plain으로, 삭제는 성공 여부를 JSON boolean으로 반환한다. 삭제 성공 시 true이며 화면 메시지는 프런트에서 처리한다. 생성 ID와 페이지별 순번을 유지하며 수정은 소유자·페이지·순번을 변경하지 않는다. JSON 원문과 공용 Report 테이블을 유지하고 모든 값을 바인딩한다. 없는 대상은 404, 변경 중 사라진 대상은 409이며 DB 오류는 공용 오류 처리로 전달한다.
|
||||
|
||||
삭제 후 순번 감소는 기존처럼 같은 프로젝트의 모든 페이지에 적용한다. 순번 조정·삭제는 하나의 kart 트랜잭션(Report DB)이다. Insert/Update/Delete Bookmark 활동 로그는 LogService를 통해 별도 트랜잭션으로 기록한다. 삭제 전 로그는 삭제 실패 시에도 남을 수 있으며 감사 로그 실패는 업무 저장을 취소하지 않는다.
|
||||
|
||||
테스트는 H2와 모킹된 인증 환경을 사용한다. 실제 SQL Server 결과 및 기존 서비스 응답 표본의 동등성 검수는 별도 필요하다. build/phase3-openapi.json은 테스트에서 생성하는 최신 명세다.
|
||||
## 등록 양식·가이드 다운로드
|
||||
|
||||
- GET /api/v1/export/form/question: KON 문항 등록 양식.xlsx 원본 파일.
|
||||
- GET /api/v1/project/{projectType}/{pkey}/export/form/data: 등록용 헤더와 별칭 한 행.
|
||||
- GET /api/v1/project/{projectType}/{pkey}/export/form/title: QID/문번/문항/Title 수정 양식.
|
||||
- GET /api/v1/project/{projectType}/{pkey}/export/guide: 원본 문항·파생 메타데이터의 GUIDE 시트.
|
||||
|
||||
기존 application/octet-stream과 서버 파일명을 유지한다. UTF-8 Content-Disposition은 한글 이름을 보존하고 경로·제어문자를 제거한다. 데이터 양식의 파생 헤더는 기존 관리자/DCO에 해당하는 userRole=1001일 때만 추가한다. 가이드는 펼치기 전 메타데이터를 사용하며 KIWI 프로필을 제외한다. 전체 권한 제한은 후속 일괄 적용 대상이다.
|
||||
|
||||
현재 설정된 KriCommon beta.1.6.9의 ExcelMapper를 재사용하고 POI 5.5.1을 컴파일 의존성에 명시했다. 공용 자동 열 너비와 빈 셀 생성을 보정해 기존 LoadFromDataTable의 기본 양식을 유지한다. 원본 문항 양식은 재직렬화하지 않는다.
|
||||
|
||||
기존 배포 EPPlus 4.5.3.3으로 생성한 합성 fixture와 셀 값·타입·배치·열 너비·행 높이·기본 서식을 비교한다. 실제 SQL Server OPENJSON/collation 및 운영 다운로드 표본 비교는 별도 검수가 필요하다. build/phase4-openapi.json은 테스트가 생성하는 최신 명세다.
|
||||
|
||||
## 일반 보고서 집계·Kiwi 주관식 분석
|
||||
|
||||
`POST /api/v1/project/{projectType}/{pkey}/statistics/result`
|
||||
|
||||
```json
|
||||
{
|
||||
"indexes": ["Q1", "Q2"],
|
||||
"banners": [["Q2", "Q3"], ["Q4"]],
|
||||
"dataScope": "ACTUAL",
|
||||
"mode": "STANDARD",
|
||||
"percentageDecimals": 2,
|
||||
"statisticDecimals": 2
|
||||
}
|
||||
```
|
||||
|
||||
프로필 지정:
|
||||
`banners`의 바깥 배열은 가로 묶음, 안쪽 배열은 최대 5단계 중첩이다. 날짜는 `startDate`/`endDate`(yyyy-MM-dd)이며 끝 생략 시 당일이다. `dataScope`는 ACTUAL/TEST/ALL이며 항상 완료 Status=10만 집계한다. 원본·파생 결합과 필요한 KIWI 프로필 결합, 선택한 문항이 포함된 저장 그룹의 투영, 기존 UPPER/FOR XML 처리를 유지한다. KIWI 프로필 메타데이터는 기존 목록처럼 userRole=1001에만 포함한다. 프로젝트/파생변수 관리 목록의 조회 권한은 아래 조회 권한 항목에 적용되어 있으며, 개별 집계 API의 일반 프로젝트 접근 검사는 별도 범위다.
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat bootRun --args="--spring.profiles.active=local"
|
||||
일반 표는 `type=TABLE`, `columns/headerRows/rows`를 반환한다. 셀은 `columnIndex/rowSpan/colSpan`의 논리 좌표와 `count/percent/base`, 표시 문자열을 갖는다. Total도 N/%를 함께 반환하며 복수·속성 응답의 Total %는 100을 넘을 수 있다. 분모 0 처리는 기존처럼 일반 셀·Total은 0, 척도/값 그룹은 percent=null과 표시="-"다. 숫자 통계는 `statisticValue/measurement`로 분리한다. `PRTMODE`를 받지 않으며 표시 선택은 frontend가 처리한다. `headerMode=NONE/FLAT/MERGED`, `transpose`, `showSubtotals`, `showValueCodes`, `showNumericSum`, 순서 있는 `valueGroups[{label,values}]`를 지원한다. TABULATION_0/1은 indexes=[""]로 호출한다. 쿼터 결과는 아래 전용 API로 분리한다. 집계 Excel 출력은 후속 범위다.
|
||||
|
||||
필터는 `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개를 유지한다. 문장별 분리는 토큰을 빠뜨리지 않으므로 결과를 전체 토큰 빈도로 집계한다. 별도의 불용어 규칙을 추가하지 않는다.
|
||||
|
||||
사용자 결정에 따라 최신 공식 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 이벤트를 반환하고 다음 문항을 계속한다.
|
||||
|
||||
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 네이티브 실행·운영 성능은 별도 검수 대상이며 합성 테스트 통과로 운영 동등성을 주장하지 않는다.
|
||||
|
||||
### 배열 집계와 NDJSON 스트리밍
|
||||
|
||||
같은 POST /api/v1/project/{projectType}/{pkey}/statistics/result 경로에서 단일 index 대신 indexes 배열을 받는다. 단일 문항도 indexes=["Q1"]로 요청한다. 기존 단일 index JSON 응답 계약은 종료한다. 배열은 빈 값/null/null 요소를 허용하지 않으며 STANDARD에서 빈 문자열은 거부한다. TABULATION 모드는 indexes=[""]를 사용한다. 배너·필터·기간·표시 옵션은 배열 전체에 공통 적용한다. 중복 index도 생략하지 않고 요청 위치대로 반환한다.
|
||||
|
||||
문항 목록 1회, 필요한 모든 저장 그룹의 합집합을 대상으로 응답 데이터 1회를 조회하고 JSON 변환·공통 필터를 1회 적용한다. 각 문항은 기존 단건 쿼리가 포함했을 응답자 범위만 집계하므로 다른 index의 응답자가 Total에 추가되지 않는다. 주관식의 NLP 태그·사전 조회는 문항별로 유지한다. 요청 간 서버 캐시는 아직 없다. Get Report Data 감사 기록은 사용자 결정에 따라 기존 외부 Referer 조건 없이 모든 일반 통계 배열 요청마다 한 번 남긴다. 쿼터 결과는 QUOTA VIEW만 기록하고 Get Report Data는 기록하지 않는다.
|
||||
|
||||
200 Content-Type은 application/x-ndjson;charset=UTF-8이다. 한 줄에 JSON 이벤트 하나를 쓰고 flush하며 순차 계산한다. result에는 기존 TABLE/TEXT_ANALYSIS 응답을 result 필드로 담는다. position은 0부터 시작하는 요청 배열 위치이고 index는 요청값이다.
|
||||
|
||||
```json
|
||||
{"type":"result","position":0,"index":"Q1","result":{"type":"TABLE","questionId":"Q1","...":"..."}}
|
||||
{"type":"error","position":1,"index":"Q2","status":503,"code":"KIWI_NLP_UNAVAILABLE","message":"문항 집계 처리에 실패했습니다."}
|
||||
{"type":"complete","total":2,"succeeded":1,"failed":1}
|
||||
```
|
||||
|
||||
## 빌드
|
||||
입력·문항·필터 검증과 공통 DB 조회는 스트림 시작 전에 수행한다. 실패 시 기존 HTTP 오류를 반환한다. 스트림 시작 후 문항 계산 오류는 error 이벤트로 반환하고 다음 문항을 계속한다. HTTP 상태는 이미 200이므로 이벤트 status를 확인해야 한다. complete를 받지 못한 종료는 완료로 취급하지 않는다. 내부 경로·응답 원문·예외 상세는 오류 이벤트에 노출하지 않는다.
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat clean build
|
||||
Spring ResponseBodyEmitter와 기존 applicationTaskExecutor를 사용한다. 스트림 전체 제한은 10분이다. 최초 인증 상태는 Spring Security의 RequestAttributeSecurityContextRepository로 동일 요청의 ASYNC 종료 처리까지 유지하며 세션을 만들거나 최초 인증을 생략하지 않는다. 종료·오류·시간 초과 시 작업 취소를 요청하고 문항 사이에서 중단 상태를 확인한다. 연결 단절은 쓰기 실패 또는 Servlet 콜백으로 감지하며, 진행 중 JDBC/네이티브 계산의 즉시 중단은 보장하지 않는다.
|
||||
|
||||
응답 Cache-Control: no-store, X-Accel-Buffering: no를 설정한다. 운영 프록시의 실제 버퍼링·압축·시간 제한은 배포 시 검증해야 한다. 프런트는 @kri/common 0.19.1의 streamPost로 받으며 Next 중계에서도 본문을 모아 JSON으로 재직렬화하면 안 된다. 프런트 연동은 이번 서버 변경에 포함하지 않는다.
|
||||
|
||||
배열 순서·중복·문항별 모수·응답 조회 1회·오류 이후 진행·취소와 인증된 MockMvc 스트리밍을 검증한다. 두 번째 계산을 대기시킨 동안 첫 NDJSON 결과가 전달되는 테스트를 포함한다. 기존 C# 계산 비교 기준 25개와 네이티브 Kiwi 검증도 유지한다.
|
||||
|
||||
## 쿼터 집계 결과
|
||||
|
||||
`POST /api/v1/quota/{projectType}/{pkey}/{quotaOrder}/result`
|
||||
|
||||
```json
|
||||
{"dataScope":"ACTUAL","startDate":"2026-10-01","endDate":"2026-10-13"}
|
||||
```
|
||||
|
||||
## 인증 설정
|
||||
빈 객체 {}도 허용하며 기본은 ACTUAL·전체 기간이다. TEST/ALL, 날짜 형식과 끝 날짜 생략 규칙은 공용 집계와 같다. 기존 quota/list는 설정 목록으로 유지한다. 결과는 단일 JSON이며 일반 보고서의 배열 NDJSON과 별개다.
|
||||
|
||||
공용 Starter 설정으로 제어합니다.
|
||||
해당 프로젝트와 QSORDER로 QUOTASET을 읽고 기존 front처럼 QSJSON.ROW의 **첫 항목만** 사용한다. ROW가 [] 또는 [""]이면 행 문항 없이 집계한다. COL은 기존 join("|")에 해당하는 중첩 배너다(묶음당 최대 5단계). 저장 FILTER는 Q| 접두사가 있으면 QID, 없으면 VARIABLE 참조다. AND/OR·괄호·비교·IN/NOT IN·BETWEEN·IS NULL/IS NOT NULL을 공용 AST로 변환한다. SQL 문자열을 실행하거나 삽입하지 않으며 지원하지 않는 저장 문법은 422 QUOTA_FILTER_INVALID로 거부한다. FILTER가 객체이면 공용 AST로 해석한다. client는 ROW/COL/저장 FILTER를 덮어쓰지 않는다.
|
||||
|
||||
```yaml
|
||||
kri:
|
||||
security:
|
||||
enabled: true
|
||||
auth:
|
||||
apikey:
|
||||
enabled: false
|
||||
공용 StatisticsService의 문항/응답 조회·JSON 정규화·필터, StatisticsAggregationService의 완료수 계산, StatisticsTableService의 헤더 구성을 재사용한다. 소계는 기존처럼 출력하지 않는다. 목표와 상태는 같은 survey DB의 QUOTA에서 pkey+QSORDER로 읽는다. 목표는 현재 잔여량 cnt가 아닌 **ori_cnt**, 사용 여부 IS_USE는 목표 조회에서 제외 조건으로 쓰지 않는다.
|
||||
|
||||
응답은 quotaSetId/quotaOrder/title/index/banners/columns/headerRows/rows이다. 셀에는 complete/target/achievementPercent/achievementDisplayText/displayText와 단일 목표에만 quotaId/isUsed가 있다. isUsed는 DB의 원래 문자열(예: "0", "1")이며 여러 목표가 합쳐지면 null이다. 달성률은 기존처럼 소수 2자리다. 목표=0일 때 숫자는 null, achievementState는 UNDEFINED(완료=0, 표시 "-") 또는 POSITIVE_INFINITY(완료>0, 표시 "∞")로 반환한다.
|
||||
|
||||
쿼터 헤더는 기존처럼 문항 제목을 제거하고 보기 레이블만 표시한다. 기존 computeQuota처럼 목표 합이 0인 행을 제거한 뒤 남은 사례 행의 완료수 합으로 Total을 다시 계산한다. Total 열은 마지막, Total 행은 행 문항이 있을 때만 마지막에 둔다. 다른 index가 없어서 Total을 전체 응답자 수로 바꾸거나 중복 선택을 제거하지 않는다. 목표가 전혀 없으면 기존 인덱스 예외 대신 rows=[]를 반환한다. 주관식 문자 결과를 완료수 표로 바꾸지 않으며 422 QUOTA_TEXT_UNSUPPORTED로 반환한다. 통계량을 완료수로 변환할 수 없는 문항은 422 QUOTA_STATISTIC_UNSUPPORTED이며 임의의 0으로 대체하지 않는다.
|
||||
|
||||
QUOTA VIEW는 설정 조회 후 서버 LogService가 기존 QSTITLE/QSJSON 내용과 인증된 사용자/IP로 한 번 기록한다. 목록 조회에는 남기지 않는다. 설정 없음은 404, 잘못된 요청/문항/날짜는 400, 저장 ROW/COL·쿼터 조건 오류는 422이며 DB 오류를 빈 성공으로 숨기지 않는다. DB 스키마 변경과 공유 DB 실행은 없다.
|
||||
|
||||
검증: 원본 C# computeQuota 후처리 합성 비교 기준 8개, 저장 필터, H2 SQL 바인딩/매핑/소스 분리, JWT API/첫 ROW/행 없는 쿼터/단일 응답 조회/사용 여부/감사 로그/Swagger. 실제 SQL Server의 기존·신규 응답 표본과 저장 FILTER 사례 검수는 별도 필요하다. 일반·쿼터 집계 Excel 및 front 연동은 후속 단계다.
|
||||
|
||||
## 공유 링크·External 인증·REPORT_URL 병행 호환
|
||||
|
||||
| 작업 | 경로 |
|
||||
|---|---|
|
||||
| 링크 발급/재사용 | POST /api/v1/project/{projectType}/{pkey}/share |
|
||||
| 내부 링크 정보 조회 | GET /api/v1/share/{urlKey} |
|
||||
| External 랜딩 인증 | POST /api/v1/external/{urlKey}/login |
|
||||
|
||||
발급 JSON은 `{ "realUrl": "/Report/Crosstab", "mode": "P" }`. P=Page Copy, U=URL Copy. 응답은 urlKey/url/realUrl/projectType/pkey/projectTitle/pageOnly이며 SKEY를 반환하지 않는다. 공유 가능한 경로는 기존 /Report/Current, /Report/Quota, /Report/Tabulation, /Report/Crosstab이다. 상대 내부 경로만 허용하며 query/fragment는 탐색 상태로 보존한다. 기존 프런트처럼 문항·필터 선택을 링크에 저장하지 않으며 P는 화면 단위 제한이다. 새로운 프런트도 이 탐색 경로 계약을 따라 연결한다.
|
||||
|
||||
신규 REPORT_URL 행에는 PKEY, PROJECT_TYPE와 기존 URL 인코딩 AES-CBC SKEY를 함께 저장한다. 기존 URL_KEY/소유자/페이지 모드를 보존하고 동일 조건이면 재사용한다. 일반 사용자 owner는 기존 REPORT, KON/KIWI identity는 그 이름을 사용한다. 발급 트랜잭션의 UPDLOCK/HOLDLOCK 조회와 키 중복 확인은 신규 서버의 동시 발급을 직렬화한다. 구서버는 같은 락 규약을 사용하지 않으므로 구서버 동시 발급까지 유일성을 보장하지 않는다. 스키마/인덱스 변경, 일괄 보정, SKEY 제거는 실행하지 않는다.
|
||||
|
||||
PKEY와 PROJECT_TYPE가 모두 NULL인 행만 내부 SKEY 어댑터로 해석한다. 0=KON, 1=KIWI이며 NEWSSAK/혼합 구분자/부분 NULL/잘못된 유형/프로젝트 없음/새 필드와 SKEY 불일치는 거부한다. 새 필드가 정상이고 SKEY가 없는 행도 지원한다. 운영 호환 키/IV는 사용자 규약에 따라 kri.kart.share.legacy-key/legacy-iv에 저장하며 API/로그 응답으로 노출하지 않는다. 공용 AES는 PBKDF2 키 파생을 사용하므로 기존 raw AES 키에 대한 JCE 어댑터를 REPORT_URL에만 둔다. public-origin 기본값은 기존 https://kart.kric.com이다.
|
||||
|
||||
랜딩 POST는 검증된 링크 정보와 accessToken을 반환한다. 공용 JWT 24시간 정책과 서명 검증을 사용하고, 서버가 발급한 KART_EXTERNAL team/EXTERNAL:urlKey identity로 매 요청 REPORT_URL 범위를 다시 확인한다. 랜딩 POST만 LANDING_CNT를 원자적으로 1 증가시키며 내부 GET/범위 검증은 증가시키지 않는다. POST는 재접속마다 한 번 호출하며 자동 재시도는 카운트를 늘릴 수 있다. 원래 랜딩의 로그인 로그와 발급의 URL Copy 로그는 LogService를 통해 기록한다.
|
||||
|
||||
External은 같은 프로젝트의 문항 메타데이터 및 허용 화면 API만 사용할 수 있다. P Current는 기본 현황, P Quota는 쿼터, P Tabulation/Crosstab은 일반 집계와 해당 북마크 조회를 허용한다. Crosstab P는 STANDARD만 허용한다. U는 같은 프로젝트의 위 보고서/쿼터를 허용한다. 외부 URL/파일을 반환하는 progress/custom, 프로젝트 전체 목록·summary, 파생 관리·북마크 쓰기·링크 발급·원자료/등록 양식/가이드 다운로드·정적 파일 접근은 차단한다. 방문 로그도 같은 프로젝트여야 한다. 아래 일반/쿼터 집계 Excel 경로만 해당 공유 화면에서 허용한다. 일반 사용자 역할 제한은 기존 결정대로 별도 단계다.
|
||||
|
||||
검증은 원본 .NET SKEY 합성 비교, 저장 필드/링크 재사용/충돌 재시도, SQL 소스/값 바인딩/대소문자 조건/랜딩 증가, 실제 공용 JWT의 페이지·프로젝트·관리 제한과 External NDJSON ASYNC 응답을 포함한다. H2에서는 SQL Server 전용 힌트/콜레이션을 그대로 실행하지 않으며 실제 SQL Server 동시 발급·구서비스 상호 운용·신규 프런트 랜딩 화면은 후속 실환경 검수다.
|
||||
|
||||
## 파생변수 관리
|
||||
|
||||
| 작업 | 경로 |
|
||||
|---|---|
|
||||
| 등록 | POST /api/v1/project/{projectType}/{pkey}/derived |
|
||||
| 수정/ID 변경 | PUT /api/v1/project/{projectType}/{pkey}/derived/{variableId} |
|
||||
| 삭제 | DELETE /api/v1/project/{projectType}/{pkey}/derived/{variableId} |
|
||||
| 개별 재계산 | POST /api/v1/project/{projectType}/{pkey}/derived/{variableId}/recalculate |
|
||||
| 전체 재계산 | POST /api/v1/project/{projectType}/{pkey}/derived/recalculate |
|
||||
|
||||
등록/수정 예시:
|
||||
|
||||
```json
|
||||
{
|
||||
"variableId": "D1", "variableTitle": "연령 구분", "variableType": "single",
|
||||
"variableInfo": {
|
||||
"1": {"value": "1", "label": "성인", "condition": "AGE >= 18"},
|
||||
"ELSE": {"value": "9", "label": "기타"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
프로젝트 내부에 JWT/API Key 필터를 중복 구현하지 않습니다.
|
||||
variableInfo는 JSON 문자열 대신 순서 있는 객체를 받으며, 저장된 DERIVEDJSON/QUESTIONJSON 구조를 유지한다. variableType은 single/multi/num이다. condition은 기존 VARIABLE 문법 문자열(Q|는 QID) 또는 기존 보고서 filter AST다. 문법 파서는 LegacyFilterService로 쿼터와 공유하며 계산은 StatisticsFilterService를 사용한다. 지원하지 않는 SQL 문법·식은 422로 거부한다. 조건을 SQL로 실행하거나 새 연산/format 해석을 추가하지 않는다. 실제 저장 조건 사례는 공유 DB 검수가 필요하다.
|
||||
|
||||
## Agent Harness
|
||||
single은 먼저 일치한 규칙, multi는 모든 일치 규칙을 저장한다. ELSE는 미일치 응답에만 적용한다. num은 원본의 open/num 메타데이터 및 기본 변수 응답 키를 그대로 유지한다. 등록·수정 후 실제 완료 응답(Status=10, TEST 제외)을 재계산하며, 전체 재계산은 저장 Qorder 순서로 진행한다. 이전 변수 그룹은 모든 DERIVED_DATA 행에서 정리하고 다른 변수 그룹은 JSON_MODIFY로 보존한다. 빈 그룹은 제거하며 값이 생성된 응답의 DERIVED_DATE만 GETDATE 기존 형식으로 갱신한다. 삭제/ID 변경에서 원본처럼 과거 날짜 키는 별도 삭제하지 않는다.
|
||||
|
||||
- 프로젝트 ID: `kart-server`
|
||||
- 프로젝트 유형: `internal-service`
|
||||
- 권위 원본: `.agent/profile.yml`, `.agent/project.md`, `.agent/references/*.md`
|
||||
KON/KONKIWI별 TransactionTemplate과 프로젝트 락을 사용해 정의 저장·순서 조정·JSON 정리·재계산을 함께 롤백한다. kart 트랜잭션(Report DB)으로 survey 쓰기를 묶지 않는다. 변수 중복은 DATA 응답 키/QUESTION/다른 DERIVED_VARIABLE에서 검사한다. actor/team은 인증된 RequestUserContext만 사용하고 기존 SiteLog 이벤트는 LogService를 거친다. 등록·수정은 ID, 삭제는 boolean, 재계산은 variableCount/matchedRespondents를 반환한다. 전체 matchedRespondents는 변수별 일치 건수 합이며 여러 변수에 같은 응답자가 일치하면 반복 집계된다. 프런트가 메시지를 표시한다.
|
||||
|
||||
`AGENTS.md`와 `CLAUDE.md`는 중앙 Agent Harness가 합성합니다. 두 파일을 직접 수정하지 않습니다.
|
||||
검증: 순차 규칙/다중·ELSE/숫자형 저장/빈 그룹/임의 SQL 거부, H2에서 KIWI 변경 롤백과 KON 영향 없음, rename/delete 순서, SQL 바인딩·소스 분리, CRUD/recalculate JWT API. 공유 DB DML/DDL은 실행하지 않았다.
|
||||
|
||||
## 일반·쿼터 집계 Excel
|
||||
|
||||
- POST /api/v1/project/{projectType}/{pkey}/export/excel/table
|
||||
- POST /api/v1/quota/{projectType}/{pkey}/export/excel
|
||||
|
||||
기존처럼 프런트에서 표시할 집계 표를 확정해 전달한다. ExportTable JSON 문자열 대신 `tables` 배열을 받고, PRTMODE 선택과 N/% 행 구성은 프런트가 맡는다. DB를 다시 집계하거나 원자료를 조회하지 않는다. 쿼터의 모든 대상 설정을 한 요청에 보내면 각 설정이 별도 시트가 된다.
|
||||
|
||||
```json
|
||||
{
|
||||
"turn": false,
|
||||
"tables": [{
|
||||
"head": "문항 제목", "vname": "1", "qtype": "single",
|
||||
"body": [
|
||||
{"label": "항목|1|1", "total": "전체|1|1"},
|
||||
{"label": "선택|1|1", "total": "2"}
|
||||
]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
body 객체의 키 순서가 열 순서이며 각 행의 키/순서가 동일해야 한다. 셀은 기존 표시 문자열 또는 `값|rowSpan|colSpan`을 사용한다. 일반 보고서는 목차/테이블, 제목·목차 링크·틀 고정·간격·병합·테두리·맑은 고딕 글꼴·N 괄호·소수 표시·Mean 2자리 및 전치 single의 계 열을 유지한다. 쿼터는 시트 제목/행 높이/완료·목표/자동 너비를 유지하고 달성률과 내부 quotaId/isUsed를 출력하지 않는다. 파일명은 토큰을 포함하지 않는 [REPORT]/[QUOTA]+pkey+KST 시간이다. 응답은 기존 다운로드 controller의 octet-stream/UTF-8 Content-Disposition 방식이다.
|
||||
|
||||
워드클라우드는 프런트가 흰 배경 PNG를 렌더링해 table.imagePng에 순수 Base64로 전달한다. SVG 문자열은 수용하지 않으며 누락된 그림을 조용히 성공 처리하지 않는다. 이미지 위치는 기존 데이터 시작 행+30px, 표 오른쪽, 크기는 1000×512px다. PNG당 5MB/4096×4096 한도이며 외부 이미지 주소를 조회하지 않는다. table 최대 1000개, body 최대 10000행, 최대 100만 셀이고 유효하지 않은 표/병합/이미지는 422다. null table/잘못된 DTO는 400이다.
|
||||
|
||||
KriCommon ExcelMapper로 workbook을 만들고 기존 양식만 POI로 적용한다. Java 기본 autoSize는 GDI와 다르므로 기존 맑은 고딕 9/10pt 글자 측정 snapshot을 사용한다. BMP glyph 너비와 기본 여백을 함께 저장하며, 합성 비교에서 열 너비 오차는 Excel 1/256문자 단위 한 개 이내다. 다국어 shaping/이모지, 다른 원본 서버 글꼴 버전 및 실제 운영 파일은 별도 표본 검수가 필요하다. Windows DLL/폰트 파일이나 신규 dependency를 서버에 포함하지 않는다.
|
||||
|
||||
검증: 원본 MakeExcel/EPPlus 4.5.3.3 생성 파일 5개를 대상으로 일반·전치·쿼터·다단 병합·여러 표·주관식 이미지를 비교한다. 셀 값·유형·서식·글꼴·정렬·병합·테두리·행 높이·열 너비·목차 링크·이미지 픽셀/크기/anchor를 검증하며 이미지 anchor 끝 좌표는 픽셀 반올림 오차 1px 이내다. External 페이지/프로젝트 다운로드 제한과 raw export 차단도 API 검사한다. 실제 프런트 PNG 생성/다운로드 화면과 실제 DB·운영 Excel 대조는 후속 작업이다.
|
||||
|
||||
## 원자료 Excel 다운로드
|
||||
|
||||
POST /api/v1/project/{projectType}/{pkey}/export/data
|
||||
|
||||
요청 예시:
|
||||
|
||||
~~~json
|
||||
{
|
||||
"type": "COMPLETE",
|
||||
"startDate": "2026-10-01",
|
||||
"endDate": "2026-10-15"
|
||||
}
|
||||
~~~
|
||||
|
||||
type은 COMPLETE(기본값, 기존 com: Status=10) 또는 INCOMPLETE(기존 not: Status<>10)다. 두 유형 모두 TEST 응답을 제외하며 미완료에서 Status=999를 별도로 제외하지 않는다. 날짜는 둘 다 생략하면 전체, startDate만 있으면 당일, 둘 다 있으면 FN_LAST_TIME(survey_date)의 DATE 양끝 포함 조건이다. endDate만 있거나 역전된 범위/알 수 없는 유형은 400이다. DB 함수의 기존 시간 기준을 유지하며 애플리케이션에서 UTC/KST를 재변환하지 않는다.
|
||||
|
||||
파일은 [DATA]pkey_KST시간.xlsx이며 DATA 다음 GUIDE 두 시트다. DATA는 저장 키 헤더 → 변수 별칭 → 응답 행 순서이고 고정 7열/add_column/인증된 userRole=1001의 파생변수/STRUCTURE 순서를 기존 양식 API와 공유한다. GUIDE는 기존 guide API와 같은 원본 메타데이터를 사용한다. 빈 응답 결과에서도 두 헤더 행과 GUIDE를 제공한다. 응답은 octet-stream/UTF-8 Content-Disposition/Cache-Control: no-store다.
|
||||
|
||||
원본·파생 응답의 DISTINCT 조인, SQL UPPER/FOR XML PATH 직렬화와 후속 ReplaceUnicodeEmpty, 빈 DAT 제외 및 잘못된 JSON의 빈 값 처리, CAPI(surveytype=2) 면접원 조회와 시작/종료/분 단위 소요시간을 유지한다. KIWI 프로필은 원본 원자료 경로처럼 결합하지 않는다. 원본 쿼리에 ORDER BY가 없어 임의 정렬을 추가하지 않았다. Excel 값은 원본처럼 문자열이며 수식으로 실행하지 않는다. 기존 HTML entity/대문자화/Unicode escape 처리 결과도 임의로 보정하지 않는다.
|
||||
|
||||
Common JWT 인증을 유지하고 External 링크 인증은 동일 프로젝트라도 원자료 API를 허용하지 않는다. userRole은 RequestUserContext만 사용하며 query의 userRole로 바꿀 수 없다. 일반 사용자 역할/팀/배정에 따른 접근 제한은 기존 결정대로 추후 일괄 적용한다. 기존 다운로드에는 SiteLog 지점이 없어 새로운 로그 이벤트를 추가하지 않았다.
|
||||
|
||||
검증: 원본 makeExportTable 및 Common 메서드/EPPlus 4.5.3.3로 만든 합성 일반·CAPI 파일 2개와 셀 값/유형/빈 셀/별칭/열 순서/시트/너비/서식 비교, survey 전용 동적 SQL의 완료·미완료/기간/CAPI 분기와 값 바인딩, KON/KONKIWI 라우팅, JWT/공유 링크 차단/DTO 검증 API 테스트. 실제 SQL Server 결과·시간 함수/운영 Excel 및 대용량 부하 비교는 별도 검수다. 현재 기존 방식처럼 응답 데이터와 workbook을 메모리에서 생성하며 스트리밍 다운로드나 캐시는 추가하지 않았다. 공유 DB 연결/DDL/DML·의존성 변경은 없다.
|
||||
## 문항 제목·문항·응답 데이터 업로드
|
||||
|
||||
모두 인증이 필요한 multipart/form-data POST이며 파일 필드 이름은 file이다. 응답 메시지는 프런트에서 만들고 서버는 처리 건수만 반환한다.
|
||||
|
||||
| 경로 | 동작 |
|
||||
|---|---|
|
||||
| /api/v1/project/{projectType}/{pkey}/import/title | 4열 양식의 QID로 QUESTIONJSON.explain만 변경 |
|
||||
| /api/v1/project/{projectType}/{pkey}/import/question | 6열 양식으로 문항과 STRUCTURE를 재구성 |
|
||||
| /api/v1/project/{projectType}/{pkey}/import/data | 두 줄 헤더의 응답 파일로 UPLOAD 데이터 교체 |
|
||||
|
||||
성공 응답 예시:
|
||||
|
||||
~~~json
|
||||
{"processedRows":2,"affectedRows":2,"removedRows":0,"archivedRows":3}
|
||||
~~~
|
||||
|
||||
processedRows는 제목 파일의 데이터 행/등록 문항/등록 응답 수다. affectedRows는 제목 UPDATE 영향 행 합 또는 등록 문항·응답 수다. 동일 QID가 여러 번 나오면 제목은 순서대로 갱신하므로 affectedRows는 고유 QID 개수가 아니다. removedRows는 삭제한 QUESTION 또는 이전 UPLOAD 응답 수, archivedRows는 DEL_로 옮긴 완료 응답 수다. 제목 업로드에서는 두 값 모두 0이다. 빈 파일·파일 누락·알 수 없는 형식·파일 내용 검증 실패는 400이며, 존재하지 않는 프로젝트는 404, STRUCTURE 누락/저장 대상 변경은 409다.
|
||||
|
||||
xlsx/csv/txt와 기존 20MB 제한을 사용한다. xlsx는 첫 시트의 첫 행을 건너뛰고 셀의 저장된 수식 결과를 읽으며 수식을 재계산하지 않는다. 응답 파일은 첫 행을 열 이름으로 사용한 뒤 별칭 행 하나를 추가로 제거한다. 제목·문항은 열 이름과 무관하게 순서대로 4열/6열로 해석한다. 텍스트 파일은 기존처럼 EUC-KR 기본/BOM UTF-8·UTF-16 자동 감지를 사용하며 CSV는 쉼표, TXT는 탭을 단순 분리한다. CSV 따옴표로 감싼 쉼표/줄바꿈을 새롭게 해석하지 않는다. 텍스트의 제목·문항 양식은 첫 행을 자동 제거하지 않는 기존 동작을 유지한다.
|
||||
|
||||
제목 업로드는 qid/variable/title/explain 순서다. 먼저 description/MM_FILE이 아닌 프로젝트 문항의 explain을 빈 문자열로 초기화하고 파일 QID별 explain을 적용한다. variable/title은 수정하지 않는다. 파일에 없는 일반 문항의 explain은 비워지며, 없는 QID는 영향 0, 중복 QID는 마지막 행이 적용된다. 초기화에서 제외된 문항도 파일에 QID를 명시하면 기존처럼 직접 갱신 대상이 된다.
|
||||
|
||||
문항 업로드는 variable/explain/qtype/attr_value/max_value/title 순서다. I/S/M/R/C/NPS/N/O와 속성·기타 보기, Q1부터의 QID/Qorder를 유지한다. QUESTION/QOPTION/QUOTASET과 기존 QSORDER 조건에 맞는 QUOTA를 삭제하고 STRUCTURE.QINFO/LINFO를 비운 뒤 저장한다. DERIVED_VARIABLE과 응답 데이터는 이 초기화에서 삭제하지 않는다. STRUCTURE의 문항별 배열/객체는 원본처럼 JSON 문자열 값으로 저장하며 JSON_QUERY로 구조화하지 않는다. 기존 R의 multi dataset/rank 옵션, option.option 중첩, {t}/{T}, 기타/속성 키와 GetStringFromJson의 연속 공백 제거 규칙을 유지한다.
|
||||
|
||||
응답 업로드는 기존 UPLOAD 응답 삭제 → TEST가 아닌 Status=10 응답의 PKEY를 DEL_+PKEY로 이동 → 새 SURVEY_TYPE=UPLOAD 응답 등록 순서다. TEST/미완료/다른 프로젝트/기존 DERIVED_DATA는 건드리지 않는다. 헤더의 구분자 앞부분을 중복 제거한 뒤 처음 6개 그룹을 제외하는 원본 규칙을 사용하므로 다운로드 양식의 고정 7열 순서를 유지해야 한다. 복수형 숫자 응답의 보기 키 당김, TQ·속성 그룹, .00 제거, 공백/따옴표 치환, INDEX/평균 시각/마지막 페이지 종료 시각과 빈 Status=10을 보존한다. 변환 결과에 같은 복수 응답 키가 반복되면 원본 JSON처럼 반복 키를 유지한다. IDKEY가 비거나 문항 응답이 없는 행, 정수가 아닌 Status, 파싱할 수 없는 날짜는 초기화 전에 실패한다. 날짜가 비면 KST 현재 시각을 사용한다.
|
||||
|
||||
파일 전체 해석·변환을 마친 뒤 초기화/저장을 실행하며 프로젝트별 락과 KON/KONKIWI TransactionTemplate으로 실패 시 모두 롤백한다. LogService의 Upload File 이벤트와 원본 파일 보관은 DB 롤백과 별개로 남을 수 있다. 원본 보관 경로는 kri.kart.upload.directory(기본 ./upload_data)이며 Git에서 제외한다. 파일명에는 충돌 방지 접미사를 붙이고 경로는 입력 파일명으로 정하지 않는다. 인증 주체/IP는 RequestUserContext에서만 받으며 External 링크 인증은 업로드 3종 모두 차단한다. 일반 역할/팀/배정 접근 제한은 기존 결정대로 후속 일괄 적용 대상이다.
|
||||
|
||||
검증은 원본 C# uploadQuestion/saveQuestion/saveStructure/uploadProjectData를 SQL 캡처 대역으로 실행해 생성한 합성 문항·응답 파일/JSON 비교, EUC-KR/BOM·파일 검증·보관, 3종×2개 소스 롤백, H2 초기화/문자열 JSON 저장, 매퍼 바인딩/소스 분리, multipart/JWT/External/건수/로그 주체 검사다. 실제 DB 연결·DDL/DML 실행·배포·의존성 변경은 없으며 운영 파일·SQL Server 트리거/제약·동시 운영 검수는 별도로 필요하다.
|
||||
## 서비스 연동 누락 점검 및 보완
|
||||
|
||||
### 연동용 프로젝트 검색
|
||||
|
||||
GET /api/v1/project/list?projectType=1&intranetCode=261000_part&userTeam=R101&keyword=
|
||||
|
||||
검색 조건이 없으면 기존 화면용 KON/KIWI 통합 목록을 그대로 반환한다. 연동 검색을 사용하면 projectType/intranetCode/userTeam을 함께 전달해야 하며 일부만 주면 400이다. keyword는 선택이고 빈 값이면 intranetCode의 첫 _ 앞부분을 PKEY 부분 일치로 검색한다. keyword가 있으면 인트라넷 코드 조건 대신 PKEY 또는 내부 제목 부분 일치를 사용한다. R로 시작하는 팀은 GKEY 일치, 그 외 팀은 GKEY<>M101, 등록일 내림차순이라는 원본 연동 쿼리 조건을 유지한다. SQL LIKE의 %/_ 의미도 원본과 동일하다.
|
||||
|
||||
연동 검색은 화면용 목록과 다른 계약이다. 최근 1년/상시 노출/회사 유형/진행 상태/특정 담당자 제외 조건, KIWI 제목 접두사를 추가하지 않는다. 상태/조사 유형도 원본 코드 문자열로 유지한다. 응답은 기존 ProjectListDto에 맞춰 projectType/rowNumber를 함께 반환한다. 검색의 userTeam은 조회 조건이며 인증된 역할이나 팀 권한을 바꾸지 않는다. 연동 검색에도 인증된 역할/팀/배정 조건을 추가로 적용하므로 검색의 userTeam으로 권한 범위를 넓힐 수 없다.
|
||||
|
||||
실제 호출처는 Contact의 kart/project-list 프록시와 프로젝트 정보 화면이다. 새 경로/쿼리로 바꾸는 Contact 수정은 이번 범위에 포함하지 않았다. Contact의 기존 skey 발급→공유 링크 발급 흐름은 새 POST /project/{projectType}/{pkey}/share로 한 번에 대체할 수 있다.
|
||||
|
||||
### 응답자별 파생변수 재계산
|
||||
|
||||
POST /api/v1/project/{projectType}/{pkey}/derived/respondent/{respondentId}/recalculate
|
||||
|
||||
요청 본문은 없고 결과는 variableCount/matchedRespondents다. 기존 전체/개별 변수 재계산과 동일한 계산 모듈을 사용하되, 지정한 프로젝트·IDKEY의 파생 응답만 초기화/저장한다. 정의는 Qorder 순서이며 앞 변수의 결과가 뒤 변수 조건에 반영된다. 대상 응답은 기존처럼 Status=10, SURVEY_TYPE<>TEST다. 미완료/TEST/응답 없음에서도 DERIVED_DATA의 빈 행을 보장하고 해당 응답자의 기존 변수 그룹은 제거하는 원본 동작을 유지한다. DERIVED_DATE의 과거 값은 매칭이 없으면 유지한다. 다른 응답자의 그룹을 일괄 정리하지 않는다.
|
||||
|
||||
실제 호출처는 KON 및 KON-KIWI module/survey.js의 설문 END 처리다. 기존 경로는 인증 없이 호출하지만 새 경로는 Common JWT/API Key 인증이 필요하고 External 공유 링크 인증으로는 호출할 수 없다. 기존 소비자가 새 백엔드를 바로 사용하는 것은 아니며 자동으로 이전 서버 호출을 바꾸지 않았다. 향후 설문 시스템 전환 시 서버 측 API Key 호출/프록시가 필요하며 브라우저 코드에 시스템 API Key를 넣지 않는다.
|
||||
|
||||
### 특수 인증의 확인 범위
|
||||
|
||||
원본은 KON/KIWI/CLIENT 이름 또는 REPORT_EXTERNAL_SYS의 활성 system_key(PRJCT_/KRIC_SYS_)를 확인해 외부 등급 토큰을 발급한다. 로컬에서 확인한 KART 프런트·Contact·KON/KON-KIWI·프로젝트 소스 중 CLIENT 공유 진입과 KON 공유 링크 생성 호출은 확인했다. PRJCT_/KRIC_SYS_ 등록 키를 실제로 전달하는 소비자는 확인하지 못했다. 이는 운영에서 미사용이라는 판정이 아니며, 등록 데이터나 운영 호출 이력은 조회하지 않았다.
|
||||
|
||||
CLIENT는 이미 구현한 REPORT_URL 검증 기반 /external/{urlKey}/login으로 대체한다. 서버 간 호출은 기존 Common API Key 인증으로 검색/공유/재계산 API를 직접 사용할 수 있으므로 이름 문자열만 받는 /encrypt/external 호환 토큰 발급기는 추가하지 않는다. 시스템 키의 prefix/등록 여부만으로 사용자 권한을 발급하거나 API Key를 대신하지 않는다. 수신 API Key는 Common의 service-code=kart-server 등록·claims·활성화 설정에 따라 검증되며, Intranet 호출에 사용하는 발신 키와 자동으로 동일하게 취급하지 않는다. 등록 키를 사용하는 별도 소비자가 확인되면 해당 소비자의 대상 프로젝트/기능 범위와 새 인증 전환 계약을 추가로 확정해야 한다.
|
||||
|
||||
검증: 연동 검색 분기/코드 정규화/원본 조건과 H2 결과, 응답자별 SQL 스코프·완료/TEST 제외, 정의 간 의존 순서·비대상 조회 방지·KON/KONKIWI 롤백, JWT 입력/API 및 External 차단. API Key 실등록·실제 소비자 전환·공유 DB·운영 트래픽 검수는 실행하지 않았다. 일반 권한 적용, Common/Contact/기존 설문 소스 수정, DB 변경, 배포와 의존성 변경은 없다.
|
||||
|
||||
서버 간 연동은 Common API Key로 각 API를 직접 호출한다. 별도 시스템 로그인이나 API Key→JWT 교환, REPORT_EXTERNAL_SYS 추가 조회는 사용하지 않는다. 일반 사용자 로그인과 REPORT_URL 기반 공유 링크 인증은 유지한다.
|
||||
|
||||
|
||||
## 조회 권한
|
||||
|
||||
- 프로젝트 목록(화면/연동)과 최신 6개는 공용 인증이 검증한 RequestUserContext만 사용한다. JWT와 API Key 모두 동일하게 적용한다. userRole=1001은 로그인 팀에 따른 제한 및 REPORT_ASSIGN 제한 없이 조회하며 기존 업무 검색/제외 조건은 유지한다.
|
||||
- 2001/3001 및 나머지 비관리자 역할의 화면 목록은 기존 v2 분기를 유지한다: 본인 팀이 M101이 아니면 GKEY=M101 제외, R로 시작하면 본인 팀 GKEY만 조회. M101 소속 목록에는 별도 팀 조건이 없다. 최신 6개는 원본 else-if 순서를 유지하여 M101 소속은 M101만, 나머지는 M101 제외이며 R팀의 추가 동일팀 제한은 없다. 두 조회를 임의로 통일하지 않는다.
|
||||
- userRole=9001은 위 팀 조건과 REPORT_ASSIGN.member_mail=인증된 userId의 배정 PKEY 조건을 함께 적용한다. 배정 조회는 Report DB에서 요청당 한 번 후 KON/KONKIWI에 전달한다. 빈 배정은 0건이며 원본처럼 is_use를 추가하지 않는다. REPORT_MEMBER의 member_mail을 JWT userId로 그대로 사용하고, 다른 인증도 검증된 userId 그대로 사용한다. 도메인 추가/아이디 추정 변환은 하지 않는다.
|
||||
- 프로젝트 권한 조건은 SQL의 정렬/최신 50개 후보 선정 전에 적용한다. must-view는 기간 예외일 뿐 팀/배정 제한을 우회하지 않는다. 연동 요청의 userTeam은 업무 검색 조건으로 유지하고 인증 팀은 별도 파라미터로 전달한다.
|
||||
- 파생변수 관리 목록은 userRole=1001만 전체, 그 외는 인증된 본인 팀 GKEY만 조회한다. 일반 문항 목록/집계 메타데이터에는 이 관리 목록 필터를 추가하지 않는다.
|
||||
- 적용 범위는 세 조회 조건이다. 변경 API 역할/작성자 제한이나 모든 개별 API의 프로젝트 배정 검사는 새로 추가하지 않는다. 기존 External 프로젝트/페이지 검사, KIWI 프로필/출력 파생 컬럼의 1001 조건, 북마크 공개/본인 비공개 조건은 유지한다.
|
||||
- 검증은 격리된 H2의 실제 매퍼 결과·소스 라우팅, 배정 없는/불일치/주입 문자열/최신 50개 이전 필터, JWT/API Key 컨텍스트 및 위조 요청 파라미터 검증으로 수행한다. 공유 DB 접속/스키마 변경/실데이터 정합성 검수는 별도이며 프론트 변경은 없다.
|
||||
|
||||
38
build.gradle
38
build.gradle
@@ -27,8 +27,18 @@ def giteaToken = findProperty('giteaToken')
|
||||
?: System.getenv('GITEA_MAVEN_TOKEN')
|
||||
?: ''
|
||||
|
||||
def kiwiVersion = 'v0.24.0'
|
||||
def kiwiPlatform = findProperty('kiwiPlatform') ?: (System.getProperty('os.name').toLowerCase().contains('windows') ? 'win-x64' : (System.getProperty('os.arch') == 'aarch64' ? 'lnx-aarch64' : 'lnx-x86-64'))
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
ivy {
|
||||
name = 'kiwiReleases'
|
||||
url = uri('https://github.com/bab2min/Kiwi/releases/download')
|
||||
patternLayout { artifact '[revision]/[artifact]-[revision]-[classifier].[ext]' }
|
||||
metadataSources { artifact() }
|
||||
content { includeModule('kr.pe.bab2min', 'kiwi-java') }
|
||||
}
|
||||
|
||||
maven {
|
||||
name = 'gitea'
|
||||
@@ -45,21 +55,21 @@ configurations.configureEach {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.kri.common:starter:beta.1.6.8'
|
||||
implementation 'com.kri.common:starter:beta.1.6.9'
|
||||
implementation 'org.apache.poi:poi-ooxml:5.5.1'
|
||||
implementation "kr.pe.bab2min:kiwi-java:${kiwiVersion}:${kiwiPlatform}@jar"
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
|
||||
// Common API Key persistence only; business databases use MyBatis.
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.11'
|
||||
|
||||
implementation 'io.github.openfeign.querydsl:querydsl-jpa:7.1'
|
||||
annotationProcessor 'com.querydsl:querydsl-apt:5.0.0:jakarta'
|
||||
annotationProcessor 'jakarta.annotation:jakarta.annotation-api'
|
||||
annotationProcessor 'jakarta.persistence:jakarta.persistence-api'
|
||||
|
||||
runtimeOnly 'com.microsoft.sqlserver:mssql-jdbc:13.2.1.jre11'
|
||||
runtimeOnly 'com.mysql:mysql-connector-j'
|
||||
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.5'
|
||||
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
@@ -70,18 +80,13 @@ dependencies {
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testImplementation 'org.springframework.security:spring-security-test'
|
||||
testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.5'
|
||||
testImplementation 'com.h2database:h2'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
def querydslDir = layout.buildDirectory.dir('generated/querydsl').get().asFile
|
||||
|
||||
sourceSets {
|
||||
main.java.srcDirs += [querydslDir]
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.encoding = 'UTF-8'
|
||||
options.generatedSourceOutputDirectory.set(file(querydslDir))
|
||||
}
|
||||
|
||||
tasks.withType(Test).configureEach {
|
||||
@@ -93,11 +98,8 @@ tasks.withType(JavaExec).configureEach {
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
if (project.hasProperty('kiwiModelDirectory')) {
|
||||
systemProperty 'kart.kiwi.model-directory', project.property('kiwiModelDirectory')
|
||||
}
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.named('clean') {
|
||||
doLast {
|
||||
delete querydslDir
|
||||
}
|
||||
}
|
||||
|
||||
40
scripts/setup-kiwi-model.ps1
Normal file
40
scripts/setup-kiwi-model.ps1
Normal file
@@ -0,0 +1,40 @@
|
||||
param([string]$ModelDirectory = (Join-Path $PSScriptRoot '../nlp_model/v0.24.0'))
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$version = 'v0.24.0'
|
||||
$archiveHash = '33188BA932BBA4717BAD5244BBEC0EF8B1C9CBB47E26E68394A7976D8D779083'
|
||||
$target = [System.IO.Path]::GetFullPath($ModelDirectory)
|
||||
if ((Test-Path -LiteralPath $target) -and (Get-ChildItem -LiteralPath $target -Force | Select-Object -First 1)) {
|
||||
throw '모델 대상 폴더가 비어 있지 않습니다. 기존 모델을 덮어쓰지 않습니다.'
|
||||
}
|
||||
$temporaryRoot = Join-Path ([System.IO.Path]::GetTempPath()) ('kart-kiwi-' + [guid]::NewGuid())
|
||||
New-Item -ItemType Directory -Path $temporaryRoot | Out-Null
|
||||
$archive = Join-Path $temporaryRoot 'kiwi-model.tgz'
|
||||
try {
|
||||
Invoke-WebRequest -Uri "https://github.com/bab2min/Kiwi/releases/download/$version/kiwi_model_${version}_base.tgz" -OutFile $archive
|
||||
if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $archiveHash) {
|
||||
throw 'Kiwi 모델 파일의 SHA-256이 일치하지 않습니다.'
|
||||
}
|
||||
tar -xzf $archive -C $temporaryRoot
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw 'Kiwi 모델 압축 해제에 실패했습니다.'
|
||||
}
|
||||
$source = Join-Path $temporaryRoot 'models/cong/base'
|
||||
if (!(Test-Path -LiteralPath (Join-Path $source 'cong.mdl'))) {
|
||||
throw 'Kiwi 모델 파일이 없습니다.'
|
||||
}
|
||||
New-Item -ItemType Directory -Path $target -Force | Out-Null
|
||||
Get-ChildItem -LiteralPath $source -File | ForEach-Object {
|
||||
Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $target $_.Name)
|
||||
}
|
||||
Write-Output 'Kiwi 0.24.0 모델을 설치했습니다.'
|
||||
} finally {
|
||||
$resolvedTemporaryRoot = (Resolve-Path -LiteralPath $temporaryRoot).Path
|
||||
$expectedParent = [System.IO.Path]::GetFullPath([System.IO.Path]::GetTempPath()).TrimEnd('\') + '\'
|
||||
$validTemporaryParent = $resolvedTemporaryRoot.StartsWith($expectedParent, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
$validTemporaryName = [System.IO.Path]::GetFileName($resolvedTemporaryRoot) -match '^kart-kiwi-[0-9a-f-]{36}$'
|
||||
if (!$validTemporaryParent -or !$validTemporaryName) {
|
||||
throw '임시 폴더 경로 검증 실패: 삭제하지 않습니다.'
|
||||
}
|
||||
Remove-Item -LiteralPath $resolvedTemporaryRoot -Recurse -Force
|
||||
}
|
||||
@@ -2,12 +2,20 @@ package com.kri.kart.server;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
// Common owns the isolated API Key JPA configuration.
|
||||
@SpringBootApplication(
|
||||
exclude = {
|
||||
DataSourceAutoConfiguration.class,
|
||||
HibernateJpaAutoConfiguration.class,
|
||||
JpaRepositoriesAutoConfiguration.class
|
||||
})
|
||||
@ConfigurationPropertiesScan
|
||||
public class KartServerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(KartServerApplication.class, args);
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.kri.kart.server.common.consts;
|
||||
|
||||
public final class ExampleConstant {
|
||||
|
||||
public static final int DEFAULT_BATCH_SIZE = 1_000;
|
||||
|
||||
private ExampleConstant() {
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.kri.kart.server.common.enums;
|
||||
|
||||
public enum ExampleStatus {
|
||||
ACTIVE,
|
||||
INACTIVE
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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 = "프로젝트 유형: 0=KON, 1=KIWI")
|
||||
public enum ProjectType implements CodeEnum<Integer> {
|
||||
KON(0),
|
||||
KIWI(1);
|
||||
|
||||
private final Integer code;
|
||||
|
||||
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
|
||||
public static ProjectType fromCode(Integer code) {
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
for (ProjectType s : values()) {
|
||||
if (s.code.equals(code)) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unknown ProjectType code: " + code);
|
||||
}
|
||||
}
|
||||
105
src/main/java/com/kri/kart/server/common/external/intranet/IntranetExtensionApiClient.java
vendored
Normal file
105
src/main/java/com/kri/kart/server/common/external/intranet/IntranetExtensionApiClient.java
vendored
Normal file
@@ -0,0 +1,105 @@
|
||||
package com.kri.kart.server.common.external.intranet;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kri.common.feature.http.ExternalApiClient;
|
||||
import com.kri.common.feature.http.ExternalApiResponse;
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.kart.server.dto.auth.LoginRequestDto;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class IntranetExtensionApiClient {
|
||||
private final ExternalApiClient externalApiClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final String intranetExtensionBaseUrl;
|
||||
private final String apiKey;
|
||||
private final String apiKeyHeaderName;
|
||||
|
||||
public IntranetExtensionApiClient(
|
||||
ExternalApiClient externalApiClient,
|
||||
ObjectMapper objectMapper,
|
||||
@Value("${kri.api-url.intranet-extension}") String intranetExtensionBaseUrl,
|
||||
@Value("${kri.auth.apikey.key}") String apiKey,
|
||||
@Value("${kri.auth.apikey.header-name:X-API-Key}") String apiKeyHeaderName) {
|
||||
this.externalApiClient = externalApiClient;
|
||||
this.objectMapper = objectMapper;
|
||||
this.intranetExtensionBaseUrl = intranetExtensionBaseUrl;
|
||||
this.apiKey = apiKey;
|
||||
this.apiKeyHeaderName = apiKeyHeaderName;
|
||||
}
|
||||
|
||||
public IntranetUserDto searchLoginInfo(LoginRequestDto request) {
|
||||
try {
|
||||
ExternalApiResponse response =
|
||||
externalApiClient.post(
|
||||
url("/user/login-info"), headers(), objectMapper.writeValueAsString(request));
|
||||
if (response.getStatusCode() != 200) {
|
||||
return null;
|
||||
}
|
||||
IntranetUserDto intranetUser =
|
||||
objectMapper.readValue(response.getBody(), IntranetUserDto.class);
|
||||
if (intranetUser == null
|
||||
|| intranetUser.getUserId() == null
|
||||
|| intranetUser.getUserId().isBlank()
|
||||
|| intranetUser.getUserRole() == null) return null;
|
||||
return intranetUser;
|
||||
} catch (Exception ignored) {
|
||||
// Failed authentication, HTTP errors, timeouts and malformed responses all fall back.
|
||||
// Never log the request password, headers or upstream response body.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getExcludedOwnerIds() {
|
||||
try {
|
||||
ExternalApiResponse response = externalApiClient.get(url("/user/list"), headers());
|
||||
if (response.getStatusCode() != 200) {
|
||||
throw new IllegalStateException("Upstream unavailable");
|
||||
}
|
||||
List<IntranetUserDto> users =
|
||||
objectMapper.readValue(response.getBody(), new TypeReference<>() {});
|
||||
if (users == null
|
||||
|| users.stream()
|
||||
.anyMatch(u -> u == null || u.getUserId() == null || u.getUserId().isBlank())) {
|
||||
throw new IllegalStateException("Invalid upstream response");
|
||||
}
|
||||
return users.stream()
|
||||
.filter(u -> "S101".equals(u.getUserTeam()) || "S201".equals(u.getUserTeam()))
|
||||
.map(IntranetUserDto::getUserId)
|
||||
.map(
|
||||
id -> {
|
||||
if (id == null || id.isBlank()) {
|
||||
throw new IllegalStateException("Missing upstream ID");
|
||||
}
|
||||
return id;
|
||||
})
|
||||
.distinct()
|
||||
.toList();
|
||||
} catch (Exception ignored) {
|
||||
// Do not silently broaden the project list when the exclusion source is unavailable.
|
||||
throw BusinessException.of(
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
"INTRANET_USER_LIST_UNAVAILABLE",
|
||||
"프로젝트 제외 대상 사용자 목록을 조회할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
|
||||
private String url(String path) {
|
||||
if (intranetExtensionBaseUrl == null || intranetExtensionBaseUrl.isBlank()) {
|
||||
throw new IllegalStateException("Intranet base URL is not configured");
|
||||
}
|
||||
return intranetExtensionBaseUrl.replaceAll("/+$", "") + path;
|
||||
}
|
||||
|
||||
private Map<String, String> headers() {
|
||||
if (apiKey == null || apiKey.isBlank()) {
|
||||
throw new IllegalStateException("Intranet API key is not configured");
|
||||
}
|
||||
return Map.of(apiKeyHeaderName, apiKey);
|
||||
}
|
||||
}
|
||||
16
src/main/java/com/kri/kart/server/common/external/intranet/IntranetUserDto.java
vendored
Normal file
16
src/main/java/com/kri/kart/server/common/external/intranet/IntranetUserDto.java
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
package com.kri.kart.server.common.external.intranet;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class IntranetUserDto {
|
||||
private String userId;
|
||||
private String userCmpn;
|
||||
private String userNm;
|
||||
private String userTeam;
|
||||
private Integer userRole;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.kri.kart.server.common.util;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public final class DateTimeUtil {
|
||||
|
||||
private DateTimeUtil() {}
|
||||
|
||||
public static String formatSeconds(String seconds) {
|
||||
if (seconds == null || seconds.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
int value = Integer.parseInt(seconds);
|
||||
return String.format(
|
||||
Locale.ROOT, "%02d:%02d:%02d", value / 3600, value % 3600 / 60, value % 3600 % 60);
|
||||
} catch (NumberFormatException ignored) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.kri.kart.server.common.util;
|
||||
|
||||
public final class StringNormalizer {
|
||||
|
||||
private StringNormalizer() {
|
||||
}
|
||||
|
||||
public static String trimToNull(String value) {
|
||||
if (value == null) return null;
|
||||
String normalized = value.trim();
|
||||
return normalized.isEmpty() ? null : normalized;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,2 @@
|
||||
/**
|
||||
* 프로젝트 전용 Bean Validation annotation과 validator를 배치합니다.
|
||||
*/
|
||||
/** 프로젝트 전용 Bean Validation annotation과 validator를 배치합니다. */
|
||||
package com.kri.kart.server.common.validation;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
import com.kri.common.feature.http.ExternalApiClient;
|
||||
import java.net.http.HttpClient;
|
||||
import java.time.Duration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class IntranetClientConfig {
|
||||
@Bean
|
||||
public ExternalApiClient intranetHttpClient() {
|
||||
return new ExternalApiClient(
|
||||
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(),
|
||||
Duration.ofSeconds(15));
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
@Configuration
|
||||
public class JdbcConfig {
|
||||
|
||||
@Bean
|
||||
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
|
||||
return new JdbcTemplate(dataSource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "kri.kart.database")
|
||||
public class KartDatabaseProperties {
|
||||
private boolean enabled;
|
||||
@Valid private Source kon = new Source();
|
||||
@Valid private Source konkiwi = new Source();
|
||||
@Valid private Source kart = new Source();
|
||||
|
||||
// No toString: credentials must not appear in logs.
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Source {
|
||||
@NotBlank private String url;
|
||||
@NotBlank private String username;
|
||||
@NotBlank private String password;
|
||||
|
||||
@Min(1)
|
||||
@Max(50)
|
||||
private int maximumPoolSize = 5;
|
||||
}
|
||||
}
|
||||
130
src/main/java/com/kri/kart/server/config/KartMyBatisConfig.java
Normal file
130
src/main/java/com/kri/kart/server/config/KartMyBatisConfig.java
Normal file
@@ -0,0 +1,130 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import jakarta.validation.Validator;
|
||||
import javax.sql.DataSource;
|
||||
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.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(KartDatabaseProperties.class)
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class KartMyBatisConfig {
|
||||
@Bean(destroyMethod = "close")
|
||||
public HikariDataSource konDataSource(KartDatabaseProperties properties, Validator validator) {
|
||||
return dataSource("kon", properties.getKon(), validator);
|
||||
}
|
||||
|
||||
@Bean(destroyMethod = "close")
|
||||
public HikariDataSource konkiwiDataSource(
|
||||
KartDatabaseProperties properties, Validator validator) {
|
||||
return dataSource("konkiwi", properties.getKonkiwi(), validator);
|
||||
}
|
||||
|
||||
@Bean(destroyMethod = "close")
|
||||
@Primary
|
||||
public HikariDataSource kartDataSource(KartDatabaseProperties properties, Validator validator) {
|
||||
return dataSource("kart", properties.getKart(), validator);
|
||||
}
|
||||
|
||||
private HikariDataSource dataSource(
|
||||
String name, KartDatabaseProperties.Source source, Validator validator) {
|
||||
if (source == null
|
||||
|| !validator.validate(source).isEmpty()
|
||||
|| !source.getUrl().startsWith("jdbc:sqlserver://")) {
|
||||
throw new IllegalArgumentException("Invalid " + name + " database configuration");
|
||||
}
|
||||
// Lazy pool: creating beans and SqlSessionFactory never opens a real connection.
|
||||
HikariDataSource dataSource = new HikariDataSource();
|
||||
dataSource.setPoolName("kart".equals(name) ? name : "kart-" + name);
|
||||
dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
|
||||
dataSource.setJdbcUrl(source.getUrl());
|
||||
dataSource.setUsername(source.getUsername());
|
||||
dataSource.setPassword(source.getPassword());
|
||||
dataSource.setMaximumPoolSize(source.getMaximumPoolSize());
|
||||
dataSource.setMinimumIdle(0);
|
||||
dataSource.setConnectionTimeout(10000);
|
||||
dataSource.setInitializationFailTimeout(-1);
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SqlSessionFactory konSqlSessionFactory(@Qualifier("konDataSource") DataSource dataSource)
|
||||
throws Exception {
|
||||
return sessionFactory(dataSource, "survey");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SqlSessionFactory konkiwiSqlSessionFactory(
|
||||
@Qualifier("konkiwiDataSource") DataSource dataSource) throws Exception {
|
||||
return sessionFactory(dataSource, "survey");
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public SqlSessionFactory kartSqlSessionFactory(
|
||||
@Qualifier("kartDataSource") DataSource dataSource) throws Exception {
|
||||
return sessionFactory(dataSource, "kart");
|
||||
}
|
||||
|
||||
private SqlSessionFactory sessionFactory(DataSource dataSource, String mapperGroup)
|
||||
throws Exception {
|
||||
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
|
||||
factory.setDataSource(dataSource);
|
||||
org.apache.ibatis.session.Configuration configuration =
|
||||
new org.apache.ibatis.session.Configuration();
|
||||
configuration.setMapUnderscoreToCamelCase(true);
|
||||
configuration.setDatabaseId(mapperGroup);
|
||||
factory.setConfiguration(configuration);
|
||||
factory.setMapperLocations(
|
||||
new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/*.xml"));
|
||||
return factory.getObject();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SqlSessionTemplate konSqlSessionTemplate(
|
||||
@Qualifier("konSqlSessionFactory") SqlSessionFactory factory) {
|
||||
return new SqlSessionTemplate(factory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SqlSessionTemplate konkiwiSqlSessionTemplate(
|
||||
@Qualifier("konkiwiSqlSessionFactory") SqlSessionFactory factory) {
|
||||
return new SqlSessionTemplate(factory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public SqlSessionTemplate kartSqlSessionTemplate(
|
||||
@Qualifier("kartSqlSessionFactory") SqlSessionFactory factory) {
|
||||
return new SqlSessionTemplate(factory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSourceTransactionManager konTransactionManager(
|
||||
@Qualifier("konDataSource") DataSource dataSource) {
|
||||
return new DataSourceTransactionManager(dataSource);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSourceTransactionManager konkiwiTransactionManager(
|
||||
@Qualifier("konkiwiDataSource") DataSource dataSource) {
|
||||
return new DataSourceTransactionManager(dataSource);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public DataSourceTransactionManager kartTransactionManager(
|
||||
@Qualifier("kartDataSource") DataSource dataSource) {
|
||||
return new DataSourceTransactionManager(dataSource);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class QueryDSLConfig {
|
||||
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@Bean
|
||||
public JPAQueryFactory jpaQueryFactory() {
|
||||
return new JPAQueryFactory(entityManager);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
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;
|
||||
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)
|
||||
@EnableConfigurationProperties(ShareLinkProperties.class)
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class ShareLinkConfig implements WebMvcConfigurer {
|
||||
private final ShareLinkService shareLinkService;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new ExternalAccessInterceptor(shareLinkService)).addPathPatterns("/**");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.kri.kart.server.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties("kri.kart.share")
|
||||
public class ShareLinkProperties {
|
||||
private String publicOrigin = "https://kart.kric.com";
|
||||
private String legacyKey;
|
||||
private String legacyIv;
|
||||
}
|
||||
@@ -14,13 +14,11 @@ public class WebResourceConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
String location = Path.of(fileStorageProperties.getBaseDir())
|
||||
.toAbsolutePath()
|
||||
.normalize()
|
||||
.toUri()
|
||||
.toString();
|
||||
String location =
|
||||
Path.of(fileStorageProperties.getBaseDir()).toAbsolutePath().normalize().toUri().toString();
|
||||
|
||||
registry.addResourceHandler(fileStorageProperties.getResourcePattern())
|
||||
registry
|
||||
.addResourceHandler(fileStorageProperties.getResourcePattern())
|
||||
.addResourceLocations(location.endsWith("/") ? location : location + "/");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.dto.auth.LoginRequestDto;
|
||||
import com.kri.kart.server.dto.auth.LoginResponseDto;
|
||||
import com.kri.kart.server.service.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class AuthController {
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/login")
|
||||
public LoginResponseDto login(
|
||||
@Valid @RequestBody LoginRequestDto request, RequestUserContext ctx) {
|
||||
return authService.login(request, ctx.getClientIp());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.bookmark.BookmarkDto;
|
||||
import com.kri.kart.server.dto.bookmark.BookmarkSaveRequestDto;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.service.BookmarkService;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.groups.Default;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/project/{projectType}/{pkey}/bookmark")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class BookmarkController {
|
||||
private final BookmarkService bookmarkService;
|
||||
|
||||
@GetMapping("/list")
|
||||
public List<BookmarkDto> list(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@RequestParam String page,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return bookmarkService.list(new ProjectRefDto(projectType, pkey), page, ctx.getUserId());
|
||||
}
|
||||
|
||||
@PostMapping(produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
public String create(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Validated({Default.class, BookmarkSaveRequestDto.Create.class}) @RequestBody
|
||||
BookmarkSaveRequestDto request,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return bookmarkService.create(new ProjectRefDto(projectType, pkey), request, ctx);
|
||||
}
|
||||
|
||||
@PutMapping(value = "/{bookmarkId}", produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
public String update(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@PathVariable String bookmarkId,
|
||||
@Valid @RequestBody BookmarkSaveRequestDto request,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return bookmarkService.update(new ProjectRefDto(projectType, pkey), bookmarkId, request, ctx);
|
||||
}
|
||||
|
||||
@DeleteMapping(value = "/{bookmarkId}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public boolean delete(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@PathVariable String bookmarkId,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return bookmarkService.delete(new ProjectRefDto(projectType, pkey), bookmarkId, ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
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.DerivedSaveRequestDto;
|
||||
import com.kri.kart.server.dto.derived.DerivedVariableDto;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.service.DerivedManagementService;
|
||||
import com.kri.kart.server.service.DerivedService;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/project/{projectType}/{pkey}/derived")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class DerivedController {
|
||||
private final DerivedService derivedService;
|
||||
private final DerivedManagementService derivedManagementService;
|
||||
|
||||
@GetMapping("/list")
|
||||
public List<DerivedVariableDto> list(
|
||||
@PathVariable ProjectType projectType, @PathVariable String pkey, RequestUserContext ctx) {
|
||||
return derivedService.list(new ProjectRefDto(projectType, pkey), ctx);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String create(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @RequestBody DerivedSaveRequestDto request,
|
||||
RequestUserContext ctx) {
|
||||
return derivedManagementService.save(new ProjectRefDto(projectType, pkey), null, request, ctx);
|
||||
}
|
||||
|
||||
@PutMapping("/{variableId}")
|
||||
public String update(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@PathVariable String variableId,
|
||||
@Valid @RequestBody DerivedSaveRequestDto request,
|
||||
RequestUserContext ctx) {
|
||||
return derivedManagementService.save(
|
||||
new ProjectRefDto(projectType, pkey), variableId, request, ctx);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{variableId}")
|
||||
public boolean delete(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@PathVariable String variableId,
|
||||
RequestUserContext ctx) {
|
||||
return derivedManagementService.delete(new ProjectRefDto(projectType, pkey), variableId, ctx);
|
||||
}
|
||||
|
||||
@PostMapping("/{variableId}/recalculate")
|
||||
public DerivedCalculationDto recalculate(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@PathVariable String variableId,
|
||||
RequestUserContext ctx) {
|
||||
return derivedManagementService.recalculate(
|
||||
new ProjectRefDto(projectType, pkey), variableId, ctx);
|
||||
}
|
||||
|
||||
@PostMapping("/respondent/{respondentId}/recalculate")
|
||||
public DerivedCalculationDto recalculateRespondent(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@PathVariable String respondentId) {
|
||||
return derivedManagementService.recalculateRespondent(
|
||||
new ProjectRefDto(projectType, pkey), respondentId);
|
||||
}
|
||||
|
||||
@PostMapping("/recalculate")
|
||||
public DerivedCalculationDto recalculateAll(
|
||||
@PathVariable ProjectType projectType, @PathVariable String pkey, RequestUserContext ctx) {
|
||||
return derivedManagementService.recalculate(new ProjectRefDto(projectType, pkey), null, ctx);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.kart.server.dto.request.CreateExampleRequest;
|
||||
import com.kri.kart.server.dto.response.ExampleResponse;
|
||||
import com.kri.kart.server.service.ExampleService;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/examples")
|
||||
public class ExampleController {
|
||||
|
||||
private final ExampleService exampleService;
|
||||
|
||||
@GetMapping
|
||||
public List<ExampleResponse> search(
|
||||
@RequestParam(defaultValue = "") String keyword,
|
||||
@RequestParam(defaultValue = "20") int limit
|
||||
) {
|
||||
return exampleService.search(keyword, limit);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public ExampleResponse create(@Valid @RequestBody CreateExampleRequest request) {
|
||||
return exampleService.create(request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.file.FileUtil;
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.export.AggregateExcelRequestDto;
|
||||
import com.kri.kart.server.dto.export.ExportFileDto;
|
||||
import com.kri.kart.server.dto.export.RawDataExportRequestDto;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.service.AggregateExcelService;
|
||||
import com.kri.kart.server.service.ExportService;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
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 java.nio.charset.StandardCharsets;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/octet-stream",
|
||||
schema = @Schema(type = "string", format = "binary")))
|
||||
public class ExportController {
|
||||
private final ExportService exportService;
|
||||
private final AggregateExcelService aggregateExcelService;
|
||||
|
||||
@PostMapping("/project/{projectType}/{pkey}/export/excel/table")
|
||||
public ResponseEntity<byte[]> reportExcel(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @RequestBody AggregateExcelRequestDto request) {
|
||||
return download(aggregateExcelService.report(new ProjectRefDto(projectType, pkey), request));
|
||||
}
|
||||
|
||||
@PostMapping("/quota/{projectType}/{pkey}/export/excel")
|
||||
public ResponseEntity<byte[]> quotaExcel(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @RequestBody AggregateExcelRequestDto request) {
|
||||
return download(aggregateExcelService.quota(new ProjectRefDto(projectType, pkey), request));
|
||||
}
|
||||
|
||||
@GetMapping(value = "/export/form/question", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
|
||||
public ResponseEntity<byte[]> questionForm() {
|
||||
return download(exportService.questionForm());
|
||||
}
|
||||
|
||||
@GetMapping(
|
||||
value = "/project/{projectType}/{pkey}/export/form/data",
|
||||
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
|
||||
public ResponseEntity<byte[]> dataForm(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return download(
|
||||
exportService.dataForm(new ProjectRefDto(projectType, pkey), ctx.getUserRole()));
|
||||
}
|
||||
|
||||
@GetMapping(
|
||||
value = "/project/{projectType}/{pkey}/export/form/title",
|
||||
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
|
||||
public ResponseEntity<byte[]> titleForm(
|
||||
@PathVariable ProjectType projectType, @PathVariable String pkey) {
|
||||
return download(exportService.titleForm(new ProjectRefDto(projectType, pkey)));
|
||||
}
|
||||
|
||||
@GetMapping(
|
||||
value = "/project/{projectType}/{pkey}/export/guide",
|
||||
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
|
||||
public ResponseEntity<byte[]> guide(
|
||||
@PathVariable ProjectType projectType, @PathVariable String pkey) {
|
||||
return download(exportService.guide(new ProjectRefDto(projectType, pkey)));
|
||||
}
|
||||
|
||||
@PostMapping(
|
||||
value = "/project/{projectType}/{pkey}/export/data",
|
||||
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
|
||||
public ResponseEntity<byte[]> 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));
|
||||
}
|
||||
|
||||
private ResponseEntity<byte[]> download(ExportFileDto file) {
|
||||
String fileName =
|
||||
FileUtil.extractFileNameFromPath(file.getFileName())
|
||||
.replaceAll("[\\p{Cntrl}\\\\/:*?\"<>|]", "_");
|
||||
String disposition =
|
||||
ContentDisposition.attachment()
|
||||
.filename(fileName, StandardCharsets.UTF_8)
|
||||
.build()
|
||||
.toString();
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, disposition)
|
||||
.header(HttpHeaders.CACHE_CONTROL, "no-store")
|
||||
.body(file.getContent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.dto.share.ExternalLoginResponseDto;
|
||||
import com.kri.kart.server.service.ShareLinkService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class ExternalController {
|
||||
private final ShareLinkService shareLinkService;
|
||||
|
||||
@PostMapping("/api/v1/external/{urlKey}/login")
|
||||
@Operation(summary = "공유 링크 전용 인증 발급", description = "검증된 링크의 프로젝트·페이지 범위에 제한되는 24시간 인증")
|
||||
public ResponseEntity<ExternalLoginResponseDto> login(
|
||||
@PathVariable String urlKey, RequestUserContext ctx) {
|
||||
return ResponseEntity.ok()
|
||||
.header("Cache-Control", "no-store")
|
||||
.body(shareLinkService.login(urlKey, ctx.getClientIp()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.upload.ImportResultDto;
|
||||
import com.kri.kart.server.service.ImportService;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/project/{projectType}/{pkey}/import")
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class ImportController {
|
||||
private final ImportService importService;
|
||||
|
||||
@PostMapping(value = "/title", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ImportResultDto titles(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@RequestPart(value = "file", required = false) MultipartFile file,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return importService.titles(new ProjectRefDto(projectType, pkey), file, ctx);
|
||||
}
|
||||
|
||||
@PostMapping(value = "/question", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ImportResultDto questions(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@RequestPart(value = "file", required = false) MultipartFile file,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return importService.questions(new ProjectRefDto(projectType, pkey), file, ctx);
|
||||
}
|
||||
|
||||
@PostMapping(value = "/data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ImportResultDto data(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@RequestPart(value = "file", required = false) MultipartFile file,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return importService.data(new ProjectRefDto(projectType, pkey), file, ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.dto.log.VisitLogRequestDto;
|
||||
import com.kri.kart.server.dto.share.ShareLinkDto;
|
||||
import com.kri.kart.server.service.LogService;
|
||||
import com.kri.kart.server.service.ShareLinkService;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/log")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class LogController {
|
||||
private final LogService logService;
|
||||
|
||||
@PostMapping(value = "/visit", produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
public String visit(
|
||||
@Valid @RequestBody VisitLogRequestDto request,
|
||||
@Parameter(hidden = true) RequestUserContext ctx,
|
||||
HttpServletRequest servletRequest) {
|
||||
ShareLinkDto link =
|
||||
(ShareLinkDto) servletRequest.getAttribute(ShareLinkService.REQUEST_LINK_ATTRIBUTE);
|
||||
if (link != null
|
||||
&& (link.getProjectType() != request.getProjectType()
|
||||
|| !link.getPkey().equals(request.getPkey()))) {
|
||||
throw BusinessException.forbidden("EXTERNAL_SCOPE_DENIED", "공유 프로젝트의 방문 로그만 기록할 수 있습니다.");
|
||||
}
|
||||
logService.writeVisitLog(
|
||||
request.getProjectType(), request.getPkey(), request.getLogContent(), ctx);
|
||||
return "PASS";
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import java.util.Map;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class PingController {
|
||||
|
||||
@GetMapping("/ping")
|
||||
public Map<String, String> ping() {
|
||||
return Map.of("status", "ok");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.project.CustomProgressDto;
|
||||
import com.kri.kart.server.dto.project.LoiDto;
|
||||
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.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.service.CustomProgressService;
|
||||
import com.kri.kart.server.service.ProgressService;
|
||||
import com.kri.kart.server.service.ProjectService;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springdoc.core.annotations.ParameterObject;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/project")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class ProjectController {
|
||||
private final ProjectService projectService;
|
||||
private final ProgressService progressService;
|
||||
private final CustomProgressService customProgressService;
|
||||
|
||||
@GetMapping("/list")
|
||||
public List<ProjectListDto> list(
|
||||
@Valid @ParameterObject @ModelAttribute ProjectLinkSearchDto search, RequestUserContext ctx) {
|
||||
return projectService.list(search, ctx);
|
||||
}
|
||||
|
||||
@GetMapping("/summary")
|
||||
public List<ProjectSummaryDto> summary(RequestUserContext ctx) {
|
||||
return projectService.summary(ctx);
|
||||
}
|
||||
|
||||
@GetMapping("/{projectType}/{pkey}/progress/day")
|
||||
public List<ProgressDayDto> daily(
|
||||
@PathVariable ProjectType projectType, @PathVariable String pkey) {
|
||||
return progressService.daily(new ProjectRefDto(projectType, pkey));
|
||||
}
|
||||
|
||||
@GetMapping("/{projectType}/{pkey}/progress/type")
|
||||
public List<ProgressTypeDto> type(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @ParameterObject @ModelAttribute ProgressSearchDto search) {
|
||||
return progressService.type(new ProjectRefDto(projectType, pkey), search);
|
||||
}
|
||||
|
||||
@GetMapping("/{projectType}/{pkey}/progress/loi")
|
||||
public List<LoiDto> loi(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @ParameterObject @ModelAttribute ProgressSearchDto search) {
|
||||
return progressService.loi(new ProjectRefDto(projectType, pkey), search);
|
||||
}
|
||||
|
||||
@GetMapping("/{projectType}/{pkey}/progress/screen")
|
||||
public List<ProgressScreenDto> screen(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @ParameterObject @ModelAttribute ProgressSearchDto search) {
|
||||
return progressService.screen(new ProjectRefDto(projectType, pkey), search);
|
||||
}
|
||||
|
||||
@GetMapping("/{projectType}/{pkey}/progress/custom")
|
||||
public List<CustomProgressDto> custom(
|
||||
@PathVariable ProjectType projectType, @PathVariable String pkey) {
|
||||
return customProgressService.list(new ProjectRefDto(projectType, pkey));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.question.QuestionDto;
|
||||
import com.kri.kart.server.service.QuestionService;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/project/{projectType}/{pkey}/question")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class QuestionController {
|
||||
private final QuestionService questionService;
|
||||
|
||||
@GetMapping("/list")
|
||||
public List<QuestionDto> list(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return questionService.list(new ProjectRefDto(projectType, pkey), ctx.getUserRole());
|
||||
}
|
||||
|
||||
@GetMapping("/{qid}")
|
||||
public List<QuestionDto> detail(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@PathVariable String qid,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return questionService.detail(new ProjectRefDto(projectType, pkey), qid, ctx.getUserRole());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaResultDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaResultRequestDto;
|
||||
import com.kri.kart.server.dto.quota.QuotaSetDto;
|
||||
import com.kri.kart.server.service.QuotaService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/quota")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class QuotaController {
|
||||
private final QuotaService quotaService;
|
||||
|
||||
@GetMapping("/{projectType}/{pkey}/list")
|
||||
public List<QuotaSetDto> list(@PathVariable ProjectType projectType, @PathVariable String pkey) {
|
||||
return quotaService.list(new ProjectRefDto(projectType, pkey));
|
||||
}
|
||||
|
||||
@PostMapping("/{projectType}/{pkey}/{quotaOrder}/result")
|
||||
@Operation(summary = "저장된 쿼터 설정의 집계 결과", description = "첫 ROW·COL·FILTER로 집계하고 완료수/목표수/달성률 반환")
|
||||
public QuotaResultDto result(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@PathVariable int quotaOrder,
|
||||
@Valid @RequestBody QuotaResultRequestDto request,
|
||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
||||
return quotaService.result(new ProjectRefDto(projectType, pkey), quotaOrder, request, ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
import com.kri.common.feature.web.RequestUserContext;
|
||||
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.ShareLinkService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class ShareLinkController {
|
||||
private final ShareLinkService shareLinkService;
|
||||
|
||||
@PostMapping("/api/v1/project/{projectType}/{pkey}/share")
|
||||
@Operation(summary = "공유 링크 발급 또는 재사용")
|
||||
public ShareLinkDto create(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @RequestBody ShareLinkRequestDto request,
|
||||
RequestUserContext ctx) {
|
||||
return shareLinkService.create(new ProjectRefDto(projectType, pkey), request, ctx);
|
||||
}
|
||||
|
||||
@GetMapping("/api/v1/share/{urlKey}")
|
||||
@Operation(summary = "공유 링크 정보 조회", description = "내부 인증 필요. 랜딩 횟수를 증가시키지 않는다.")
|
||||
public ShareLinkDto lookup(@PathVariable String urlKey) {
|
||||
return shareLinkService.lookup(urlKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.kri.kart.server.controller;
|
||||
|
||||
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.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.share.ShareLinkDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsBatchDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsBatchRequestDto;
|
||||
import com.kri.kart.server.dto.statistics.StatisticsStreamEventDto;
|
||||
import com.kri.kart.server.service.ShareLinkService;
|
||||
import com.kri.kart.server.service.StatisticsService;
|
||||
import com.kri.kart.server.service.statistics.StatisticsStreamService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
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.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import java.net.URI;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
|
||||
import org.springframework.security.web.context.SecurityContextRepository;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/project/{projectType}/{pkey}/statistics")
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
||||
public class StatisticsController {
|
||||
private static final String STANDARD_MODE = "STANDARD";
|
||||
private static final String CROSSTAB_PAGE = "/Report/Crosstab";
|
||||
|
||||
private final StatisticsService statisticsService;
|
||||
private final StatisticsStreamService statisticsStreamService;
|
||||
private final SecurityContextRepository securityContextRepository =
|
||||
new RequestAttributeSecurityContextRepository();
|
||||
|
||||
@PostMapping(value = "/result", produces = "application/x-ndjson")
|
||||
@Operation(
|
||||
summary = "일반 보고서 배열 집계 스트림",
|
||||
description = "공유 데이터를 한 번 조회하고 indexes 순서대로 result/error, 마지막 complete 전송")
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/x-ndjson",
|
||||
schema = @Schema(implementation = StatisticsStreamEventDto.class)))
|
||||
public ResponseEntity<ResponseBodyEmitter> result(
|
||||
@PathVariable ProjectType projectType,
|
||||
@PathVariable String pkey,
|
||||
@Valid @RequestBody StatisticsBatchRequestDto request,
|
||||
@Parameter(hidden = true) RequestUserContext ctx,
|
||||
HttpServletRequest servletRequest,
|
||||
HttpServletResponse servletResponse) {
|
||||
if (isCrosstabPageLink(servletRequest) && !STANDARD_MODE.equals(request.getMode())) {
|
||||
throw BusinessException.forbidden(
|
||||
"EXTERNAL_SCOPE_DENIED", "Cross Tab 공유 링크에서는 Cross Tab 집계만 허용됩니다.");
|
||||
}
|
||||
StatisticsBatchDto statisticsBatch =
|
||||
statisticsService.prepare(
|
||||
new ProjectRefDto(projectType, pkey),
|
||||
request.requests(),
|
||||
ctx);
|
||||
// Common authentication is stateless; retain only this request's identity for ASYNC dispatch.
|
||||
securityContextRepository.saveContext(
|
||||
SecurityContextHolder.getContext(), servletRequest, servletResponse);
|
||||
return ResponseEntity.ok()
|
||||
.header("Cache-Control", "no-store")
|
||||
.header("X-Accel-Buffering", "no")
|
||||
.header("Content-Type", "application/x-ndjson;charset=UTF-8")
|
||||
.body(statisticsStreamService.stream(statisticsBatch));
|
||||
}
|
||||
|
||||
/** A page-only Cross Tab share link may request Cross Tab (STANDARD) results only. */
|
||||
private boolean isCrosstabPageLink(HttpServletRequest servletRequest) {
|
||||
ShareLinkDto link =
|
||||
(ShareLinkDto) servletRequest.getAttribute(ShareLinkService.REQUEST_LINK_ATTRIBUTE);
|
||||
return link != null
|
||||
&& link.isPageOnly()
|
||||
&& URI.create(link.getRealUrl()).getPath().equals(CROSSTAB_PAGE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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;
|
||||
|
||||
@NotBlank
|
||||
@Schema(accessMode = Schema.AccessMode.WRITE_ONLY)
|
||||
private String userPw;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.kri.kart.server.dto.auth;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ReportMemberDto {
|
||||
private String userId;
|
||||
private String userName;
|
||||
private String memberRedirect;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.kri.kart.server.dto.bookmark;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class BookmarkDto {
|
||||
private String bookmarkId;
|
||||
private String bookmarkTitle;
|
||||
private String bookmarkInfo;
|
||||
private String bookmarkJson;
|
||||
private String gkey;
|
||||
private String mkey;
|
||||
private Integer isOpen;
|
||||
private String isMine;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.kri.kart.server.dto.bookmark;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
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 {}
|
||||
|
||||
@Schema(description = "생성 시 필수. 수정 시 페이지는 변경하지 않음")
|
||||
@NotNull(groups = Create.class)
|
||||
@Pattern(regexp = "TABULATION|CROSSTAB")
|
||||
private String bookmarkPage;
|
||||
|
||||
@NotNull
|
||||
private String bookmarkTitle;
|
||||
@NotNull
|
||||
private String bookmarkInfo;
|
||||
|
||||
@Schema(description = "기존 북마크 설정 JSON 문자열. 저장 시 원문 유지")
|
||||
@NotNull
|
||||
private String bookmarkJson;
|
||||
|
||||
@NotNull
|
||||
@Min(0)
|
||||
@Max(1)
|
||||
private Integer isOpen;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.kri.kart.server.dto.derived;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class DerivedCalculationDto {
|
||||
int variableCount;
|
||||
int matchedRespondents;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.kri.kart.server.dto.derived;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class DerivedDataDto {
|
||||
private String idkey;
|
||||
private String datjson;
|
||||
private String derivedJson;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.kri.kart.server.dto.derived;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class DerivedDefinitionDto {
|
||||
private String qid;
|
||||
private String questionJson;
|
||||
private String derivedJson;
|
||||
private Integer qOrder;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.kri.kart.server.dto.derived;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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 {
|
||||
@NotBlank
|
||||
@Size(max = 128)
|
||||
@Pattern(regexp = "[A-Za-z][A-Za-z0-9_]*")
|
||||
private String variableId;
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 4000)
|
||||
private String variableTitle;
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "single|multi|num")
|
||||
private String variableType;
|
||||
|
||||
@NotNull private JsonNode variableInfo;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.kri.kart.server.dto.derived;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class DerivedVariableDto {
|
||||
private String qid;
|
||||
|
||||
@Getter(onMethod_ = @JsonProperty("qOrder"))
|
||||
private Integer qOrder;
|
||||
|
||||
private String variable;
|
||||
private String title;
|
||||
private String explain;
|
||||
private String vtype;
|
||||
private String qtype;
|
||||
private String isNps;
|
||||
private String attrInfo;
|
||||
private String rankInfo;
|
||||
private String labelInfo;
|
||||
private String afterLogic;
|
||||
private String isDerived;
|
||||
private String derivedJson;
|
||||
private String gkey;
|
||||
private String mkey;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
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 {
|
||||
@Valid
|
||||
@NotEmpty
|
||||
@Size(max = 1000)
|
||||
private List<@NotNull AggregateExcelTableDto> tables;
|
||||
|
||||
private boolean turn;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAnySetter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class AggregateExcelTableDto {
|
||||
@NotNull
|
||||
@Size(max = 4000)
|
||||
private String head;
|
||||
|
||||
private String vname = "";
|
||||
private String qtype = "";
|
||||
|
||||
@NotEmpty
|
||||
@Size(min = 2, max = 10000)
|
||||
private List<@NotNull LinkedHashMap<@NotBlank String, @NotNull @Size(max = 32767) String>> body;
|
||||
|
||||
@Size(max = 7000000)
|
||||
private String imagePng;
|
||||
|
||||
@JsonAnySetter
|
||||
public void rejectUnknownField(String name, JsonNode value) {
|
||||
throw new IllegalArgumentException("지원하지 않는 Excel 표 속성입니다. 워드클라우드는 imagePng를 사용해 주세요.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ExportDataDto {
|
||||
private String dat;
|
||||
private String status;
|
||||
private String startDate;
|
||||
private String endDate;
|
||||
private String intervalMin;
|
||||
private String interviewerInfo;
|
||||
private String interviewerCode;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ExportDerivedHeaderDto {
|
||||
private String qid;
|
||||
private String qtype;
|
||||
private String linfo;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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 {
|
||||
@ExcelColumn(header = "문항 타입", order = 0)
|
||||
private String questionType;
|
||||
|
||||
@ExcelColumn(header = "문항 / 보기번호", order = 1)
|
||||
private String variable;
|
||||
|
||||
@ExcelColumn(header = "내용", order = 2)
|
||||
private String content;
|
||||
|
||||
@ExcelColumn(header = "VALUE LABEL", order = 3)
|
||||
private String valueLabel;
|
||||
|
||||
@ExcelColumn(header = "VARIABLE LABEL", order = 4)
|
||||
private String variableLabel;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ExportHeaderDto {
|
||||
private String qid;
|
||||
private String variable;
|
||||
private String value;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import com.kri.common.feature.excel.ExcelColumn;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ExportTitleDto {
|
||||
@ExcelColumn(header = "QID", order = 0)
|
||||
private String qid;
|
||||
|
||||
@ExcelColumn(header = "문번", order = 1)
|
||||
private String variable;
|
||||
|
||||
@ExcelColumn(header = "문항", order = 2)
|
||||
private String title;
|
||||
|
||||
@ExcelColumn(header = "Title", order = 3)
|
||||
private String explain;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.kri.kart.server.dto.export;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import java.time.LocalDate;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class RawDataExportRequestDto {
|
||||
@NotNull
|
||||
@Pattern(regexp = "COMPLETE|INCOMPLETE")
|
||||
@Schema(description = "COMPLETE: 완료(Status=10), INCOMPLETE: 미완료(Status<>10). TEST 응답 제외")
|
||||
private String type = "COMPLETE";
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private LocalDate startDate;
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private LocalDate endDate;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.kri.kart.server.dto.log;
|
||||
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
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;
|
||||
|
||||
@Size(max = 20)
|
||||
@Pattern(regexp = "^[^|]*$")
|
||||
private String pkey;
|
||||
|
||||
@NotBlank
|
||||
@Schema(description = "방문한 화면 URL 또는 페이지 정보")
|
||||
private String logContent;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.kri.kart.server.dto.project;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder(toBuilder = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CustomProgressDto {
|
||||
private Integer appendOrder;
|
||||
private Integer appendType;
|
||||
private String fileName;
|
||||
}
|
||||
14
src/main/java/com/kri/kart/server/dto/project/LoiDto.java
Normal file
14
src/main/java/com/kri/kart/server/dto/project/LoiDto.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.kri.kart.server.dto.project;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class LoiDto {
|
||||
private Integer cnt;
|
||||
private String avgLoi;
|
||||
private String avgLoiModify;
|
||||
private String minLoi;
|
||||
private String maxLoi;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.kri.kart.server.dto.project;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProgressDayDto {
|
||||
// Legacy SQL returns style 112 in CHAR(10): yyyyMMdd plus two trailing spaces.
|
||||
private String surveyDate;
|
||||
private Integer totalCount;
|
||||
private Integer completeCount;
|
||||
private Integer screenCount;
|
||||
private Integer quotaCount;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.kri.kart.server.dto.project;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProgressScreenDto {
|
||||
@Getter(onMethod_ = @JsonProperty("qOrder"))
|
||||
private Integer qOrder;
|
||||
|
||||
private String viewTitle;
|
||||
private String pageName;
|
||||
private Long cnt;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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 {
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
private LocalDate startDate;
|
||||
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
private LocalDate endDate;
|
||||
|
||||
public void validateRange() {
|
||||
if ((startDate == null) != (endDate == null)
|
||||
|| (startDate != null && startDate.isAfter(endDate))) {
|
||||
throw BusinessException.badRequest("시작일과 종료일을 함께 입력하고 시작일을 종료일 이전으로 지정해 주세요.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.kri.kart.server.dto.project;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProgressTypeDto {
|
||||
private Integer totalCount;
|
||||
private Integer completeCount;
|
||||
private Integer screenCount;
|
||||
private Integer quotaCount;
|
||||
private Integer goingCount;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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;
|
||||
|
||||
@Size(max = 128)
|
||||
@Schema(description = "서비스 연동 조회용 인트라넷 프로젝트 코드. 첫 _ 앞 부분으로 검색")
|
||||
private String intranetCode;
|
||||
|
||||
@Size(max = 32)
|
||||
private String userTeam;
|
||||
|
||||
@Size(max = 512)
|
||||
private String keyword;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.kri.kart.server.dto.project;
|
||||
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProjectListDto {
|
||||
private ProjectType projectType;
|
||||
private String rowNumber;
|
||||
private String pkey;
|
||||
private String title;
|
||||
private String surveyType;
|
||||
private String status;
|
||||
private String gkey;
|
||||
private String mkey;
|
||||
private LocalDateTime createDate;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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 {
|
||||
@Schema(description = "프로젝트 유형: 0=KON, 1=KIWI")
|
||||
private final ProjectType projectType;
|
||||
|
||||
@Schema(description = "프로젝트 키", maxLength = 20)
|
||||
private final String pkey;
|
||||
|
||||
public ProjectRefDto(ProjectType projectType, String pkey) {
|
||||
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,22 @@
|
||||
package com.kri.kart.server.dto.project;
|
||||
|
||||
import com.kri.kart.server.common.enums.ProjectType;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProjectSummaryDto {
|
||||
private ProjectType projectType;
|
||||
private String pkey;
|
||||
private String title;
|
||||
private String surveyType;
|
||||
private String status;
|
||||
private LocalDateTime createDate;
|
||||
private Long allCount;
|
||||
private Long ongoingCount;
|
||||
private Long screenCount;
|
||||
private Long quotaCount;
|
||||
private Long completeCount;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.kri.kart.server.dto.question;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder(toBuilder = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class QuestionDto {
|
||||
private String qid;
|
||||
|
||||
@Getter(onMethod_ = @JsonProperty("qOrder"))
|
||||
private Integer qOrder;
|
||||
|
||||
private String variable;
|
||||
private String title;
|
||||
private String explain;
|
||||
private String vtype;
|
||||
private String qtype;
|
||||
private String isNps;
|
||||
private String isReverse;
|
||||
private String missingValue;
|
||||
private String attrInfo;
|
||||
private String rankInfo;
|
||||
private String labelInfo;
|
||||
private String afterLogic;
|
||||
private String isDerived;
|
||||
private String derivedJson;
|
||||
private String gkey;
|
||||
private String mkey;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.kri.kart.server.dto.quota;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class QuotaEntryDto {
|
||||
private Long id;
|
||||
private Long cnt;
|
||||
private Long oriCnt;
|
||||
private String quotaJson;
|
||||
private String isUse;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.kri.kart.server.dto.quota;
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.kri.kart.server.dto.quota;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import java.time.LocalDate;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class QuotaResultRequestDto {
|
||||
@NotNull
|
||||
@Pattern(regexp = "ACTUAL|TEST|ALL")
|
||||
private String dataScope = "ACTUAL";
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private LocalDate startDate;
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private LocalDate endDate;
|
||||
}
|
||||
14
src/main/java/com/kri/kart/server/dto/quota/QuotaRowDto.java
Normal file
14
src/main/java/com/kri/kart/server/dto/quota/QuotaRowDto.java
Normal file
@@ -0,0 +1,14 @@
|
||||
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;
|
||||
}
|
||||
14
src/main/java/com/kri/kart/server/dto/quota/QuotaSetDto.java
Normal file
14
src/main/java/com/kri/kart/server/dto/quota/QuotaSetDto.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.kri.kart.server.dto.quota;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class QuotaSetDto {
|
||||
private Long id;
|
||||
private Integer qsOrder;
|
||||
private String qsTitle;
|
||||
// Preserve saved configuration verbatim; quota result interprets it without modifying the DB.
|
||||
private String qsJson;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.kri.kart.server.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
|
||||
public record CreateExampleRequest(
|
||||
@NotNull @Positive Long groupId,
|
||||
@NotNull @Positive Integer sequence,
|
||||
@NotBlank String name
|
||||
) {
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.kri.kart.server.dto.response;
|
||||
|
||||
import com.kri.kart.server.persistence.entity.ExampleEntity;
|
||||
|
||||
public record ExampleResponse(
|
||||
Long groupId,
|
||||
Integer sequence,
|
||||
String name,
|
||||
String status
|
||||
) {
|
||||
public static ExampleResponse from(ExampleEntity entity) {
|
||||
return new ExampleResponse(
|
||||
entity.getId().getGroupId(),
|
||||
entity.getId().getSequence(),
|
||||
entity.getName(),
|
||||
entity.getStatus().name()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.kri.kart.server.dto.share;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class ExternalLoginResponseDto {
|
||||
String accessToken;
|
||||
ShareLinkDto link;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.kri.kart.server.dto.share;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/** REPORT_URL 내부 저장 DTO. SKEY는 API 응답에 포함하지 않는다. */
|
||||
@Getter
|
||||
@Setter
|
||||
public class ShareLinkRecordDto {
|
||||
private Long id;
|
||||
private String urlKey;
|
||||
private String realUrl;
|
||||
private Integer isPageOnly;
|
||||
private String skey;
|
||||
private String pkey;
|
||||
private Integer projectType;
|
||||
private String projectTitle;
|
||||
private String urlOwner;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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 {
|
||||
@NotBlank
|
||||
@Size(max = 4096)
|
||||
private String realUrl;
|
||||
|
||||
@NotBlank
|
||||
@Pattern(regexp = "P|U")
|
||||
private String mode;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class NlpDictionaryWordDto {
|
||||
private String wordText;
|
||||
private String wordTag;
|
||||
private Integer wordScore;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
public record NlpTokenDto(String text, String tag) {}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import com.kri.kart.server.dto.project.ProjectRefDto;
|
||||
import com.kri.kart.server.dto.question.QuestionDto;
|
||||
import java.util.List;
|
||||
|
||||
/** Questions and filtered responses loaded once and shared by every index in one request. */
|
||||
public record StatisticsBatchDto(
|
||||
ProjectRefDto project,
|
||||
List<StatisticsRequestDto> requests,
|
||||
List<QuestionDto> questions,
|
||||
List<SurveyResponseDto> responses) {}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class StatisticsBatchRequestDto extends StatisticsOptionsDto {
|
||||
@NotEmpty
|
||||
@Schema(description = "요청 순서대로 집계할 QID 배열. TABULATION 모드는 [\"\"] 사용")
|
||||
private List<@NotNull String> indexes;
|
||||
|
||||
public List<StatisticsRequestDto> requests() {
|
||||
return indexes.stream()
|
||||
.map(
|
||||
index -> {
|
||||
StatisticsRequestDto request = new StatisticsRequestDto();
|
||||
BeanUtils.copyProperties(this, request);
|
||||
request.setIndex(index);
|
||||
return request;
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@Builder(toBuilder = true)
|
||||
public class StatisticsCellDto {
|
||||
private int columnIndex;
|
||||
@Builder.Default private int rowSpan = 1;
|
||||
@Builder.Default private int colSpan = 1;
|
||||
private String kind;
|
||||
private String textValue;
|
||||
private Long count;
|
||||
private Double percent;
|
||||
|
||||
@Schema(description = "해당 셀의 백분율 분모")
|
||||
private Long base;
|
||||
|
||||
private Double statisticValue;
|
||||
private String measurement;
|
||||
private String countDisplayText;
|
||||
private String percentDisplayText;
|
||||
private String statisticDisplayText;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class StatisticsDataDto {
|
||||
private String idkey;
|
||||
private String dat;
|
||||
private String filterDat;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Schema(description = "AND/OR/NOT는 children, 조건은 dimensionId와 values 사용. 숫자 JSON 값은 수치 비교")
|
||||
public class StatisticsFilterDto {
|
||||
private String operator;
|
||||
private String dimensionId;
|
||||
private String reference = "QID";
|
||||
private List<JsonNode> values = new ArrayList<>();
|
||||
private List<StatisticsFilterDto> children = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class StatisticsOptionsDto {
|
||||
@NotNull
|
||||
@Schema(description = "가로 배너 묶음과 묶음별 중첩 문항. 한 묶음 최대 5단계")
|
||||
private List<@NotNull @Size(min = 1, max = 5) List<@NotNull String>> banners = new ArrayList<>();
|
||||
|
||||
@Valid private StatisticsFilterDto filter;
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "STANDARD|TABULATION_0|TABULATION_1")
|
||||
private String mode = "STANDARD";
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "ACTUAL|TEST|ALL")
|
||||
private String dataScope = "ACTUAL";
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private LocalDate startDate;
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private LocalDate endDate;
|
||||
|
||||
@Min(0)
|
||||
@Max(14)
|
||||
private int percentageDecimals = 14;
|
||||
|
||||
@Min(0)
|
||||
@Max(14)
|
||||
private int statisticDecimals = 14;
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "NONE|FLAT|MERGED")
|
||||
private String headerMode = "MERGED";
|
||||
|
||||
private boolean transpose;
|
||||
private boolean showSubtotals = true;
|
||||
private boolean showValueCodes;
|
||||
private boolean showNumericSum;
|
||||
|
||||
@Valid @NotNull private List<StatisticsValueGroupDto> valueGroups = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class StatisticsRequestDto extends StatisticsOptionsDto {
|
||||
@NotNull
|
||||
@Schema(description = "집계 문항 QID. 속성 투영은 #A. TABULATION 모드만 빈 값 허용", example = "Q1")
|
||||
private String index;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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;
|
||||
|
||||
@NotEmpty private List<@NotBlank String> values;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.kri.kart.server.dto.statistics;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Internal flattened survey response. Never returned by report APIs. */
|
||||
public record SurveyResponseDto(
|
||||
String idkey, Map<String, String> values, Map<String, String> filterValues) {
|
||||
public SurveyResponseDto(String idkey, Map<String, String> values) {
|
||||
this(idkey, values, values);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.kri.kart.server.dto.upload;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class ImportQuestionDto {
|
||||
String qid;
|
||||
int qOrder;
|
||||
String questionJson;
|
||||
String qinfo;
|
||||
String linfo;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user