Files
KART-SERVER-JAVA/.agent/references/repository-rules.md

201 lines
36 KiB
Markdown

## KART Server Repository Rules
- Java 17, Spring Boot 3.5.7, KriCommon `com.kri.common:starter:beta.1.7.1`.
- Use MyBatis with explicit KON, KONKIWI and kart (Report DB) SQL Server sessions and transaction managers. Do not infer a source from pkey alone.
- ProjectType codes are 0=KON and 1=KIWI; reject unsupported types and legacy key markers in new project identifiers.
- This API is for the new system. Legacy API compatibility is not required; shared database compatibility is required.
- 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.
- Place Spring MVC interceptors under the interceptor package. Inject KriCommon RequestUserContextProvider to resolve request identity; keep project and share-link authorization policies in KART.
- Do not introduce separate PrincipalKind/ProjectPermission/ReportPage enums or generic grant models for this purpose.
- External authentication must still enforce its stored project/page scope and restrict access to report reads and aggregate Excel; role/team alone must not authorize access outside the link scope.
## 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.
- Per user decision, bookmark update/delete require stored MKEY to exactly match RequestUserContext.userId; team membership and administrator role grant no exception. Enforce ownership before audit/reordering and in mutation SQL. Deletion order adjustment applies only within the same pkey and the deleted bookmark's stored BOOKMARK_PAGE; never trust a request-supplied page for this scope. 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.
- Keep the KON question-upload workbook as an external file under kri.kart.export.form-directory (default ./file_forms, beside ./upload_data relative to the process working directory). Read it on every download so file replacement needs no restart. Deploy file_forms separately from the JAR, preserve the supplied workbook bytes, and do not regenerate it from metadata or fall back to a bundled copy.
- 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. Stopwords exist only as the REPORT_NLP_WORD STOP rows described under Kiwi NLP accuracy; add no other stopword rules.
- Configure kri.kart.nlp.model-directory as ./nlp_model/v0.24.0, install model separately, ignore runtime models in Git, and choose the platform-specific official jar at build time. Do not claim Ubuntu execution from Windows tests. Missing native/model infrastructure is explicit 503, not empty successful NLP output.
- Per user decision, the legacy external-Referer condition is removed: every general statistics batch writes Get Report Data once through LogService. Quota results write QUOTA VIEW only, never Get Report Data. Do not add a separate logging endpoint.
- Validate through original C# synthetic calculation fixtures, authenticated API/Swagger tests, source-bound MyBatis tests and opt-in actual native analysis with -PkiwiModelDirectory. Actual SQL Server equivalence and deployment performance remain separate checks.
## 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
- Role constants: REPORT_MEMBER_ROLE=9001 preserves account assignment policies; EXTERNAL_URL_COPY_ROLE=9002 for pageOnly=false (four report screens); EXTERNAL_PAGE_COPY_ROLE=9003 for pageOnly=true (specified screen). External login returns accessToken/user/link, using the same user claims for signing and response. Keep EXTERNAL:{urlKey}, CLIENT name, KART_EXTERNAL team and empty company. Frontend validates returned identity and does not calculate roles. Any External role/team/id marker enters External validation; require all markers and stored link type to match, preserving project/page/API allowlists, bookmark read/application and aggregate/Quota Excel. Reject old 9001 External identities. No DB schema/data change or new ordinary Export/Import role restriction.
- 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.
- Per user decision (2026-10-23), derived values take precedence over raw DATA keys with the same derived ID: derived calculation ignores raw DATA keys of every stored derived ID. Statistics/Export SQL is unchanged (approach C2: keep such keys out of DATA instead of rewriting read queries). An update whose variable ID equals originId (case-insensitive) skips the duplicate check; renames and creates keep the full check.
- Aggregate Excel POST routes are /project/{projectType}/{pkey}/export/excel/table and /quota/{projectType}/{pkey}/export/excel. Accept typed ordered tables/turn and legacy cell display/span strings, retaining frontend N/% presentation choice; do not requery raw data. Keep original workbook layout, multiple quota sheets and complete/target output. Link scopes must allow only their matching aggregate paths.
- Use KriCommon ExcelMapper then format with current POI, without new dependencies. Wordcloud input is validated PNG Base64 from frontend, preserving original 1000x512 position; no SVG or external URL loading. Use static measured Malgun Gothic glyph advances to avoid platform autoSize changes. Compare original EPPlus workbooks: cells/styles/merged ranges/row sizes exact, column rounding within one 1/256-character unit and image anchor rounding within one pixel. Actual production files, shaping/emoji, frontend PNG/render/download and live SQL checks remain separate.
## 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. Per user decision (2026-10-22), O/N questions with no input rows (none, attribute-only or blank titles) get one open input {label:"", option all/num, must 1} instead of failing; other types still require choices.
- Data upload deletes UPLOAD responses, moves actual completed responses to DEL_+PKEY, and inserts UPLOAD rows; do not mutate TEST/incomplete/other projects. Per user decision (2026-10-23), columns equal to a stored derived ID or starting with "{ID}_" (case-insensitive) are not uploaded, and after all rows are inserted every derived variable is recalculated in the same KON/KONKIWI transaction (no role check or extra SiteLog; failure rolls back the upload). Preserve two header rows, six distinct fixed-group skip, multi pull-up keys including duplicates, INDEX and midpoint/final timestamps, empty defaults and original text normalization.
- Parse/convert the entire file before destructive SQL; all changes use the selected KON/KONKIWI transaction with a project lock and rollback. SQL values/JSON paths are bound. No shared DB execution or schema changes are authorized.
- Preserve xlsx first-sheet/positional columns/blank rows/cached formulas and csv/txt simple delimiter plus EUC-KR/BOM behavior. Use Common ExcelUtil; its map reader drops rows and changes positional/formula rules, so a domain-specific POI reader is necessary. Existing 20MB limit applies.
- Keep original file archives under kri.kart.upload.directory (./upload_data, Git ignored) and Upload File logging through LogService with authenticated context. Archives and best-effort audit attempts may remain after database rollback; do not expose stored paths or raw content on parse errors.
- 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 non-TEST responses regardless of Status (user decision 2026-10-27, allowing calculation before completion status is saved) and uses the selected survey transaction. Whole-project recalculation retains Status = 10. Preserve historical date values on no match and add no new SiteLog point.
- Local prefix search did not locate a PRJCT_/KRIC_SYS_ caller; do not claim production non-use or remove legacy registrations. Existing Common API Key auth covers new server-to-server calls; verified REPORT_URL covers CLIENT. Do not add unauthenticated system-name/prefix-to-JWT exchange or trust request-supplied identity. Incoming service-code kart-server API Key registration is separate from the outgoing Intranet key.
- Existing browser survey hooks need a server-side proxy/API Key integration at later cutover. Caller conversion, real API Key registration/traffic, shared DB checks, general authorization and deployment remain separate work.
## 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: M101 team only own GKEY, all other teams exclude M101, and (user decision 2026-10-22, replacing the legacy else-if) R-prefixed teams additionally require own GKEY, matching the list. Per the same user decision, summary candidates also apply the list's title NOT LIKE '%사례비%' and status IN (2, 3) before TOP 50; the list's date/surveyclass/must-view window is intentionally not added.
- Role 9001 additionally intersects REPORT_ASSIGN by exact member_mail=verified userId. Query the kart session (Report DB) once per request for both survey sources, do not add is_use (not used by original), do not append email domains, and empty assignments return no rows. REPORT_MEMBER emits exact member_mail as userId; other authentication also uses verified userId verbatim.
- Apply team/assignment before candidate TOP 50 and ordering, never after Java merge/TOP 6. Must-view does not override authorization. Linked list retains its business query team and adds separately named authenticated-team/role/assignment constraints.
- Derived management list: role 1001 sees all project definitions; others see matching GKEY only. Keep normal questions/report metadata unfiltered by this management rule.
- Scope is these read conditions only. Do not add generic per-project/mutation/owner authorization, change original aggregations/Excel, or weaken External scope. Validate actual bound mapper SQL and H2 results on both sources, empty assignments, precise id routing, trusted JWT/API Key context versus forged query fields; no shared DB execution.
## Kiwi NLP accuracy (user decisions 2026-11-10)
- The legacy C# report services are retired; REPORT_NLP_WORD/TAG are no longer read by them.
- KiwiNlpService builds with BuildOption.default_ and analyzes with Match.allWithNormalizing | oovChrModel plus basicTypoSetWithContinual typo correction (threshold 2.5). Do not revert to AnalyzeOption(0).
- User dictionary: register each (text, tag) once with its highest scope score, because Kiwi keeps the last duplicate score and the query has no order. Trim/uppercase tags. Log only registered/skipped/rejected counts, never words.
- Statistics options: wordMergeMode 1=ALL, 2=NOUN (default; NNG/NNP/NNB/NR/NP/SL/SH), 3=NONE sums the same text across tags, keeping the most frequent tag (first on ties) and first-appearance order. compoundNounMaxTokens 1-5 (default 3; 1 disables) joins noun prefixes/suffixes and merges NNG/NNP/SL runs attached within one word when they contain a Korean noun; NNP if any part is NNP; longer runs stay separate.
- Synonyms (user decision 2026-11-11, replacing the separate REPORT_NLP_SYNONYM table): a REPORT_NLP_WORD row with SOURCE_TEXT (NVARCHAR(128), nullable; WORD_TEXT is NVARCHAR(128)) replaces SOURCE_TEXT with WORD_TEXT/WORD_TAG. WORD_TEXT always means the result word. Scope priority question > project > ALL uses the 100/50/10 scores. The column must exist before deployment. Sources are pre-analyzed (score 200, above every user word) after registering the target as a word with score 0 unless a plain row for the same target already registered it with its scope score, because Kiwi rejects a target morpheme missing from its dictionary such as LG/NNP; a failing row is skipped, never a 503; a spaced source also covers its spaceless form and replaces whole token runs only when no noun of the same word continues the run.
- Stopwords (불용어): REPORT_NLP_WORD rows with WORD_TAG STOP (case-insensitive) are never registered in Kiwi. Any scope excludes the final word (after synonyms and compound merging) for every tag, comparing trimmed, space-collapsed text case-insensitively; SOURCE_TEXT is ignored on STOP rows.
- User dictionary words and synonym targets take precedence over everything: they are never merged with neighbors.
- The original analyze(project, qid, responses) and tokenize(texts, dictionary) overloads keep the previous behavior (synonym rows ignored; no stopwords or merging). Only the statistics API uses the new options.