From a964dcbee3a99d9ff0abfaa32904b10aeacbc288 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Thu, 22 Oct 2026 10:25:41 +0900 Subject: [PATCH 1/8] =?UTF-8?q?261022=5F02=5FENH:=20git=EC=97=90=20env=20?= =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=ED=8F=AC=ED=95=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env | 3 +++ .env.development | 3 +++ .env.example | 9 --------- .env.local | 3 +++ .env.production | 3 +++ .gitignore | 7 +------ 6 files changed, 13 insertions(+), 15 deletions(-) create mode 100644 .env create mode 100644 .env.development delete mode 100644 .env.example create mode 100644 .env.local create mode 100644 .env.production diff --git a/.env b/.env new file mode 100644 index 0000000..7b7d94a --- /dev/null +++ b/.env @@ -0,0 +1,3 @@ +NEXT_PUBLIC_API_BASE=/api +NEXT_PUBLIC_STORE_KEY=kri-local-storage-key-32-bytes!! +NEXT_PUBLIC_STORE_IV=kri-local-iv-16! diff --git a/.env.development b/.env.development new file mode 100644 index 0000000..8903406 --- /dev/null +++ b/.env.development @@ -0,0 +1,3 @@ +NEXT_PUBLIC_ENV=development +ENV=development +API_SERVER=http://127.0.0.1:4015/api/v1 diff --git a/.env.example b/.env.example deleted file mode 100644 index 4277422..0000000 --- a/.env.example +++ /dev/null @@ -1,9 +0,0 @@ -# 모든 환경 공통 -NEXT_PUBLIC_API_BASE=/api -NEXT_PUBLIC_STORE_KEY=change-this-storage-key-32-bytes -NEXT_PUBLIC_STORE_IV=change-this-iv-16 - -# 환경별 값 (.env.local / .env.development / .env.production) -NEXT_PUBLIC_ENV=local -ENV=local -API_SERVER=http://localhost:4015/api/v1 diff --git a/.env.local b/.env.local new file mode 100644 index 0000000..f50767d --- /dev/null +++ b/.env.local @@ -0,0 +1,3 @@ +NEXT_PUBLIC_ENV=local +ENV=local +API_SERVER=http://localhost:4015/api/v1 diff --git a/.env.production b/.env.production new file mode 100644 index 0000000..d834dd5 --- /dev/null +++ b/.env.production @@ -0,0 +1,3 @@ +NEXT_PUBLIC_ENV=production +ENV=production +API_SERVER=http://127.0.0.1/api/v1 diff --git a/.gitignore b/.gitignore index 5efe7ee..2552bca 100644 --- a/.gitignore +++ b/.gitignore @@ -15,9 +15,4 @@ yarn-debug.log* yarn-error.log* .pnpm-debug.log* .idea/ -*.iml - -# Local environment files -.env -.env.* -!.env.example +*.iml \ No newline at end of file -- 2.49.0.windows.1 From 86e7ce3e3236fb1966849cfb03728d75ad309511 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Thu, 22 Oct 2026 10:42:40 +0900 Subject: [PATCH 2/8] =?UTF-8?q?261022=5F03=5FENH:=20env=20=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.production | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.env.production b/.env.production index d834dd5..1edf253 100644 --- a/.env.production +++ b/.env.production @@ -1,3 +1,3 @@ NEXT_PUBLIC_ENV=production ENV=production -API_SERVER=http://127.0.0.1/api/v1 +API_SERVER=http://127.0.0.1:4015/api/v1 -- 2.49.0.windows.1 From 642350bc6cae3748a36931629a6f5ec4d8b99972 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Thu, 22 Oct 2026 11:54:39 +0900 Subject: [PATCH 3/8] =?UTF-8?q?261022=5F04=5FENH:=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EC=A0=9D=ED=8A=B8=20=EC=A0=9C=EB=AA=A9=20=EC=BD=94=EB=93=9C?= =?UTF-8?q?=C2=B7=EB=AA=85=20=EB=B3=91=ED=96=89=20=ED=91=9C=EA=B8=B0=20?= =?UTF-8?q?=EB=B0=8F=20URL=20=ED=8C=8C=EB=9D=BC=EB=AF=B8=ED=84=B0=20?= =?UTF-8?q?=ED=94=84=EB=A1=9C=EC=A0=9D=ED=8A=B8=20=EC=84=A0=ED=83=9D=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .agent/references/repository-rules.md | 2 +- src/components/app-shell/AppHeader.tsx | 11 ++++++--- src/hooks/useSelectedProject.ts | 34 ++++---------------------- src/types/kart.ts | 10 -------- 4 files changed, 14 insertions(+), 43 deletions(-) diff --git a/.agent/references/repository-rules.md b/.agent/references/repository-rules.md index 4fd16ba..b070004 100644 --- a/.agent/references/repository-rules.md +++ b/.agent/references/repository-rules.md @@ -13,7 +13,7 @@ - New backend only; development front 4014/backend 4015/api/v1. Use published @kri/common HTTP and persistent hydratedAtom plus TanStack Query; do not add axios or duplicate common storage/auth helpers. Repository package.json and lockfile are authoritative for versions. Add dependencies only after user approval; preserve existing chart, drag-and-drop and registry integrations. - Next stores the 24-hour token in an HttpOnly cookie and returns validated LoginUser only. Secure for ENV prod/production. Backend logout/session endpoints do not exist: Next logout clears its cookie, client auth and query cache. BFF accepts only fixed implemented project reads and whitelisted query fields; never trust browser role/id headers or send API keys to the browser. -- Basic routes are /, /login, /logout and project pages without query parameters (/Report/Current, /Report/Quota, /Report/Tabulation, /Report/Crosstab, /Management/Derived, /Management/Exim). The selected project {projectType, pkey} lives in the user-scoped persistent atom `useSelectedProject` (localStorage, like legacy ptokenState); home, login and logout clear it, and old `?projectType=0|1&pkey=rawKey` links are stored and stripped. Preserve pkey case and use projectType+pkey in query keys and BFF paths, with current user id/role/team in query keys. Runtime-validate data, use existing UI components, retain raw server count/LOI semantics and display-only padded date cleanup. Keep loading/error/empty/retry states. +- Basic routes are /, /login, /logout and project pages without query parameters (/Report/Current, /Report/Quota, /Report/Tabulation, /Report/Crosstab, /Management/Derived, /Management/Exim). The selected project {projectType, pkey} lives in the user-scoped persistent atom `useSelectedProject` (localStorage, like legacy ptokenState); home, login and logout clear it. Address parameters never select a project: old `?projectType=0|1&pkey=rawKey` links are ignored, and sharing is only through generated Page Copy/URL Copy links. This is not access control; server project scope is authoritative. Preserve pkey case and use projectType+pkey in query keys and BFF paths, with current user id/role/team in query keys. Runtime-validate data, use existing UI components, retain raw server count/LOI semantics and display-only padded date cleanup. Keep loading/error/empty/retry states. - Basic progress uses type/loi/day/screen; date filters affect type/loi/screen, never day, matching the server. Logging is a best-effort /log/visit call with server cookie identity, no /log/site HTTP. - The second migration phase is closed. Until the user explicitly announces launch, this application is unlaunched and old External token compatibility is unnecessary. The user performs every operation that writes to the shared database (live login, bookmark/derived saves, imports, share issuance and External login) and live Excel generation checks. No shared DB calls in local validation. Phase closure does not certify unexecuted live checks. - ReportMember/URL Copy/Page Copy roles are 9001/9002/9003. External login replaces the prior identity; validate the server-returned user and link together. Keep the link's project and page scope, disable project-list/summary reads, and use the link title. Page Copy has no GNB menus; URL Copy has only the four report menus. Hide logo navigation, Logout, project selection, Copy and bookmark writes. Bookmark reads and aggregate/Quota Excel remain allowed; server scope enforcement is authoritative. diff --git a/src/components/app-shell/AppHeader.tsx b/src/components/app-shell/AppHeader.tsx index a23b1da..1ccb4f0 100644 --- a/src/components/app-shell/AppHeader.tsx +++ b/src/components/app-shell/AppHeader.tsx @@ -10,7 +10,7 @@ import { kartMenus } from "@/config/menu.data"; import type { KartMenuItem } from "@/config/menu.type"; import { ProjectSelector } from "@/components/project/ProjectSelector"; import { useProjectTitle } from "@/query/project"; -import { useProjectParamsMigration, useSelectedProject } from "@/hooks/useSelectedProject"; +import { useSelectedProject } from "@/hooks/useSelectedProject"; import { projectPagePath } from "@/lib/report-navigation"; import { useAuth } from "@/hooks/useAuth"; import { useMutation } from "@tanstack/react-query"; @@ -28,13 +28,18 @@ export function AppHeader({ user }: AppHeaderProps) { const { auth } = useAuth(); const external = isExternalUser(user); const { project } = useSelectedProject(); - useProjectParamsMigration(); const title = useProjectTitle(project); const [mobileOpen, setMobileOpen] = useState(false); const menus = project && !(external && auth.external?.pageOnly) ? kartMenus.filter((menu) => !menu.visible || menu.visible(user)) : []; - const projectTitle = project ? title : "Project Overview TOP 6"; + // "(code) name" like the project selector; the code alone until the project list provides the + // name (useProjectTitle falls back to pkey). External links keep their link title. + const projectTitle = !project + ? "Project Overview TOP 6" + : external || title === project.pkey + ? title + : "(" + project.pkey + ") " + title; const canCopyUrl = !!project && user.userRole < REPORT_MEMBER_ROLE; const copy = useMutation({ mutationFn: async (mode: "P" | "U") => { diff --git a/src/hooks/useSelectedProject.ts b/src/hooks/useSelectedProject.ts index db5c04a..043159e 100644 --- a/src/hooks/useSelectedProject.ts +++ b/src/hooks/useSelectedProject.ts @@ -1,9 +1,7 @@ "use client"; -import { useCallback, useEffect } from "react"; +import { useCallback } from "react"; import { useAtom, useAtomValue } from "jotai"; -import { usePathname, useRouter, useSearchParams } from "next/navigation"; -import type { Route } from "next"; import { createPersistentAtom } from "@kri/common/jotai"; import { useAuth } from "@/hooks/useAuth"; import { isExternalUser } from "@/types/share"; @@ -13,7 +11,7 @@ import { setLocalStorage, } from "@/store/storage/secure-storage"; import { StorageKeys } from "@/store/storage/storage-keys"; -import { isProjectRef, isRecord, readProjectParams, type ProjectRef } from "@/types/kart"; +import { isProjectRef, isRecord, type ProjectRef } from "@/types/kart"; /** The project chosen for the project pages, owned by the user who chose it. */ export type SelectedProject = { userId: string; project: ProjectRef } | null; @@ -46,16 +44,14 @@ export const selectedProjectAtom = createPersistentAtom( ); /** - * Current project for the signed-in user. An old `?projectType=&pkey=` link takes precedence - * until ProjectParamsMigration stores it and removes the parameters from the address. + * Current project for the signed-in user. Address parameters (old `?projectType=&pkey=` links) + * never select a project; links are shared only through generated Page Copy / URL Copy links. */ export function useSelectedProject() { const { auth, hydrated: authHydrated } = useAuth(); const [selected, setSelected] = useAtom(selectedProjectAtom); const storeHydrated = useAtomValue(selectedProjectAtom.hydratedAtom); - const urlProject = readProjectParams(useSearchParams()); const external = isExternalUser(auth.user); - const fromUrl = external ? null : urlProject; const userId = auth.user?.userId; const stored = selected && userId && selected.userId === userId @@ -73,30 +69,10 @@ export function useSelectedProject() { ); const clear = useCallback(() => setSelected(null), [setSelected]); return { - project: external ? auth.external ?? null : fromUrl ?? stored, - fromUrl, + project: external ? auth.external ?? null : stored, /** False until both the login state and the stored selection have been read. */ hydrated: authHydrated && storeHydrated, select, clear, } as const; } - -/** - * Old bookmarks and shared links still carry `?projectType=&pkey=`: store that project and - * replace the address with the bare path. Mounted once in the app header. - */ -export function useProjectParamsMigration() { - const router = useRouter(); - const pathname = usePathname(); - const { auth, hydrated } = useAuth(); - const { fromUrl, select } = useSelectedProject(); - const projectType = fromUrl?.projectType; - const pkey = fromUrl?.pkey; - const signedIn = hydrated && !!auth.user; - useEffect(() => { - if (!signedIn || projectType === undefined || pkey === undefined) return; - select({ projectType, pkey }); - router.replace(pathname as Route); - }, [signedIn, projectType, pkey, select, router, pathname]); -} diff --git a/src/types/kart.ts b/src/types/kart.ts index 54bca85..0ccb62c 100644 --- a/src/types/kart.ts +++ b/src/types/kart.ts @@ -141,16 +141,6 @@ export function readRows( export function projectKey(project: ProjectRef): string { return project.projectType + ":" + project.pkey; } -export function readProjectParams( - params: Pick, -): ProjectRef | null { - const type = params.get("projectType"); - const project = { - projectType: type === "0" ? 0 : type === "1" ? 1 : null, - pkey: params.get("pkey"), - }; - return isProjectRef(project) ? project : null; -} export function validDateRange(range: DateRange): boolean { const validDate = (date: string) => /^\d{4}-\d{2}-\d{2}$/.test(date) && -- 2.49.0.windows.1 From 6f1b7423ecaa2087171811f066412f63820f35b1 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Fri, 23 Oct 2026 11:52:59 +0900 Subject: [PATCH 4/8] =?UTF-8?q?261023=5F01=5FENH:=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EC=A0=9D=ED=8A=B8=C2=B7=ED=95=84=ED=84=B0=20=EC=84=A0=ED=83=9D?= =?UTF-8?q?=20=EC=98=B5=EC=85=98=20=EC=A0=84=EC=B2=B4=20=EC=A0=9C=EB=AA=A9?= =?UTF-8?q?=20=ED=88=B4=ED=8C=81=20=EB=B3=B5=EC=9B=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 32 ++++++++++++ src/components/common/KriAutoComplete.tsx | 14 +++++- .../common/multi-select/MultiSelect.tsx | 4 ++ .../multi-select/MultiSelectContent.tsx | 49 +++++++++++++++++-- src/components/common/multi-select/index.ts | 1 + src/components/common/multi-select/types.ts | 3 ++ src/components/project/ProjectSelector.tsx | 3 ++ src/components/report/FilterPopup.tsx | 6 +++ 8 files changed, 107 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 21df77f..5d5b5bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -265,6 +265,26 @@ Before each related task, read the current contents of every matching reference, If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriFrontCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead. +## Noti-hub SMS Types + +- `MessageType.SMS = 21`, `LMS = 22`, `MMS = 23`; `ChannelType.SMS = 2` is unchanged. `SMS_TYPE_ARRAY` and `SmsType` include all three. +- `LMS_MMS = 22` remains a deprecated source-compatibility alias for LMS only. It does not represent MMS. Enum reverse lookup for 22 returns LMS. Use numeric bulk-list paths; the server no longer accepts LMS_MMS in paths. Numeric 21/22/23 bulk-list requests all return the entire SMS channel, not type-filtered lists. +- Requests retain their existing URLs/body shapes. The server chooses the actual type per recipient after substitution: attachment -> MMS; otherwise title or UTF-8 body >= 90 bytes -> LMS; otherwise SMS. +- Refresh templates from the save response (`tmplatTy`); display actual delivery types from `sendTy`, not the template or result code. A bulk can contain multiple SMS types. LMS/MMS share result codes; use existing server result labels. +- SMS, LMS, MMS and KKO use cancellation code 9998. Verify with `npm run typecheck`, `npm run build`, and `node --test tests/noti-hub-sms.test.mjs`. + +## Noti-hub Reservation Cancellation + +- Import cancellation types, constants, and helpers from `@kri/common/noti-hub` only. They are runtime-neutral and require no optional peers. +- Individual current cancellation state is determined by resultCode via isReserveCanceledResult; bulk current state is cancellationStatus (NONE/PARTIAL/ALL). These describe current cancellation state, not cancellation eligibility. cancelDt and cancelUser are request history, not current state. +- SendResultInfo, SendInfo, and BulkSendInfo expose optional cancelable. Use isSendCancelable(item), which returns true only for cancelable === true, for cancellation eligibility; missing values from older responses are treated as false. Never infer eligibility from cancelDt, result labels, or result codes. +- cancelable reflects query-time state and may change before cancellation. Determine the final outcome from SendCancelResponse counts. +- sendIdx is the single-cancel identifier, not cmid. It is absent from the latest abbreviated report (/api/v1/report/last/send/...). Request sendIdx must be a positive integer; bulkSendKey is required and at most 32 characters. +- EMAIL_RESERVE_CANCELED_RESULT_CODE is 108 for EMAIL. SMS_KKO_RESERVE_CANCELED_RESULT_CODE is 9998 for SMS, LMS, MMS, and KKO. Unknown message types are not recognized as canceled. +- Display the server's resultViewLabel/resultLabel ("예약 취소"). There is no separate result-code list API. +- HTTP 200 can contain notCancelableCount. parseSendCancelResponse validates nonnegative integer counts and targetCount = canceledCount + alreadyCanceledCount + notCancelableCount, throwing TypeError on invalid data. Bulk targetCount counts currently registered detail rows; response canceledCount counts only cancellations made by that request. +- Existing response fields are unchanged; all added fields on existing types are optional. Verify with npm run typecheck and npm run build. + ## HTTP Streaming - `@kri/common/http` HTTP clients expose streamGet/streamPost/streamPut/streamPatch/streamDel, returning HttpStreamResponse (status, statusText, headers, url, nullable body). @@ -288,6 +308,18 @@ When implementing or changing frontend UI, use this order: - `kri-auto-complete` exposes `resetScrollOnSearch?: boolean` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `false`, preserving existing behavior. - When enabled, a search value change (including clearing it) resets the option list scroll to the top on the next animation frame in both `filter` and `inputOnly` modes. Async result updates alone do not trigger another reset. +### KriAutoComplete Option Tooltip + +- `kri-auto-complete` exposes `optionTooltip?: 'singleLine' | 'wrap'` and `optionTooltipClassName?: string` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It is off by default, preserving existing behavior. +- When enabled, hovering an option shows its full `label` in a right-side tooltip. `singleLine` stays on one line until the available viewport width; `wrap` wraps at 28rem. The item depends on the shadcn `tooltip` component and provides its own `TooltipProvider`. + +### KriEditor SMS Preview + +- `changeSmsType` reports `SMS | LMS | MMS`. Update consumer callbacks to handle `MMS`; this widens the previous callback contract. +- Attachment presence (`smsHasAttachment`) takes priority and reports MMS. Otherwise a title or UTF-8 preview size >= `smsMaxBytes` (default 90) reports LMS; the remainder reports SMS. LMS/MMS share `lmsMaxBytes` (default 2000). +- UTF-8 byte counting includes `smsPreviewSuffix` and its separating newline, without storing the suffix in the body. +- This is a preview. Use the template-save response for saved `tmplatTy` and delivery-result `sendTy` for actual per-recipient type after server substitution. Registry updates require updating installed consumer copies. + ### Required Shared References Before each related task, read the current contents of every matching reference, even if it was read earlier in the session. diff --git a/src/components/common/KriAutoComplete.tsx b/src/components/common/KriAutoComplete.tsx index 5212f97..cec733e 100644 --- a/src/components/common/KriAutoComplete.tsx +++ b/src/components/common/KriAutoComplete.tsx @@ -3,9 +3,9 @@ import * as React from 'react' import { cn } from '@/lib/utils' import { MultiSelect } from '@/components/common/multi-select' -import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select' +import type { MultiSelectOption, MultiSelectOptionTooltip, MultiSelectRef } from '@/components/common/multi-select' -export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select' +export type { MultiSelectOption, MultiSelectOptionTooltip, MultiSelectRef } from '@/components/common/multi-select' export interface KriAutoCompleteBaseProps { items: T[] @@ -26,6 +26,8 @@ export interface KriAutoCompleteBaseProps { disabled?: boolean 'aria-invalid'?: boolean modalPopover?: boolean + optionTooltip?: MultiSelectOptionTooltip + optionTooltipClassName?: string } export interface KriMultiSelectProps extends KriAutoCompleteBaseProps { @@ -77,6 +79,8 @@ export function KriMultiSelect({ disabled, 'aria-invalid': ariaInvalid, modalPopover = true, + optionTooltip, + optionTooltipClassName, }: KriMultiSelectProps) { const options = React.useMemo( () => toOptions(items, getValue, getLabel, withInfo), @@ -110,6 +114,8 @@ export function KriMultiSelect({ disabled={disabled} aria-invalid={ariaInvalid} modalPopover={modalPopover} + optionTooltip={optionTooltip} + optionTooltipClassName={optionTooltipClassName} /> ) @@ -157,6 +163,8 @@ function KriSingleSelectInner({ disabled, 'aria-invalid': ariaInvalid, modalPopover = true, + optionTooltip, + optionTooltipClassName, }: KriSingleSelectProps, forwardedRef: React.ForwardedRef) { const ref = React.useRef(null) React.useImperativeHandle( @@ -227,6 +235,8 @@ function KriSingleSelectInner({ aria-invalid={ariaInvalid} title={showSelectedTooltip ? selectedLabel ?? value : undefined} modalPopover={modalPopover} + optionTooltip={optionTooltip} + optionTooltipClassName={optionTooltipClassName} /> ) diff --git a/src/components/common/multi-select/MultiSelect.tsx b/src/components/common/multi-select/MultiSelect.tsx index b4731d7..53c7207 100644 --- a/src/components/common/multi-select/MultiSelect.tsx +++ b/src/components/common/multi-select/MultiSelect.tsx @@ -46,6 +46,8 @@ function MultiSelectInner( closeOnSelect = false, preventDeselect = false, hideOptionCheck = false, + optionTooltip, + optionTooltipClassName, style, ...buttonProps }: MultiSelectProps, @@ -205,6 +207,8 @@ function MultiSelectInner( onSearchValueChange={handleSearchChange} hideSelectAll={hideSelectAll} hideOptionCheck={hideOptionCheck} + optionTooltip={optionTooltip} + optionTooltipClassName={optionTooltipClassName} selectionMode={selectionMode} emptyIndicator={emptyIndicator} onToggleOption={toggleOption} diff --git a/src/components/common/multi-select/MultiSelectContent.tsx b/src/components/common/multi-select/MultiSelectContent.tsx index df0cec8..27957f5 100644 --- a/src/components/common/multi-select/MultiSelectContent.tsx +++ b/src/components/common/multi-select/MultiSelectContent.tsx @@ -11,8 +11,9 @@ import { CommandList, CommandSeparator, } from '@/components/ui/command' +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' -import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types' +import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptionTooltip, MultiSelectOptions } from './types' import { isGroupedOptions } from './utils' interface MultiSelectContentProps { @@ -25,25 +26,57 @@ interface MultiSelectContentProps { onSearchValueChange: (value: string) => void hideSelectAll: boolean hideOptionCheck: boolean + optionTooltip?: MultiSelectOptionTooltip + optionTooltipClassName?: string selectionMode: 'single' | 'multiple' emptyIndicator: React.ReactNode onToggleOption: (option: MultiSelectOption) => void onToggleAll: () => void } +interface OptionTooltipSettings { + mode: MultiSelectOptionTooltip + className?: string +} + function OptionItem({ option, selected, hideOptionCheck, + tooltip, onToggle, }: { option: MultiSelectOption selected: boolean hideOptionCheck: boolean + tooltip?: OptionTooltipSettings onToggle: () => void }) { const Icon = option.icon + // cmdk's CommandItem overrides onPointerMove, so the label (not the item) is the tooltip trigger. + const label = tooltip ? ( + + + {option.label} + + + {option.label} + + + ) : ( + {option.label} + ) + return ( ({ ) : null} {Icon ? : null} - {option.label} + {label} ) } @@ -71,11 +104,13 @@ function OptionsGroup({ group, selectedValues, hideOptionCheck, + tooltip, onToggleOption, }: { group: MultiSelectGroup selectedValues: string[] hideOptionCheck: boolean + tooltip?: OptionTooltipSettings onToggleOption: (option: MultiSelectOption) => void }) { return ( @@ -86,6 +121,7 @@ function OptionsGroup({ option={option} selected={selectedValues.includes(option.value)} hideOptionCheck={hideOptionCheck} + tooltip={tooltip} onToggle={() => onToggleOption(option)} /> ))} @@ -103,6 +139,8 @@ export function MultiSelectContent({ onSearchValueChange, hideSelectAll, hideOptionCheck, + optionTooltip, + optionTooltipClassName, selectionMode, emptyIndicator, onToggleOption, @@ -123,8 +161,9 @@ export function MultiSelectContent({ const flatOptions = grouped ? options.flatMap((group) => group.options) : options const selectableOptions = flatOptions.filter((option) => !option.disabled) const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value)) + const tooltip = optionTooltip ? { mode: optionTooltip, className: optionTooltipClassName } : undefined - return ( + const content = ( {searchable ? ( ({ group={group} selectedValues={selectedValues} hideOptionCheck={hideOptionCheck} + tooltip={tooltip} onToggleOption={onToggleOption} /> )) @@ -172,6 +212,7 @@ export function MultiSelectContent({ option={option} selected={selectedValues.includes(option.value)} hideOptionCheck={hideOptionCheck} + tooltip={tooltip} onToggle={() => onToggleOption(option)} /> ))} @@ -180,4 +221,6 @@ export function MultiSelectContent({ ) + + return tooltip ? {content} : content } diff --git a/src/components/common/multi-select/index.ts b/src/components/common/multi-select/index.ts index 6392afd..a630b2f 100644 --- a/src/components/common/multi-select/index.ts +++ b/src/components/common/multi-select/index.ts @@ -3,6 +3,7 @@ export type { AnimationConfig, MultiSelectGroup, MultiSelectOption, + MultiSelectOptionTooltip, MultiSelectOptions, MultiSelectProps, MultiSelectRef, diff --git a/src/components/common/multi-select/types.ts b/src/components/common/multi-select/types.ts index 7d6abbb..4fedf04 100644 --- a/src/components/common/multi-select/types.ts +++ b/src/components/common/multi-select/types.ts @@ -29,6 +29,7 @@ export interface MultiSelectGroup { export type MultiSelectOptions = MultiSelectOption[] | MultiSelectGroup[] export type MultiSelectSelectionMode = 'single' | 'multiple' export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted' +export type MultiSelectOptionTooltip = 'singleLine' | 'wrap' export interface MultiSelectResponsiveSettings { maxCount?: number @@ -79,6 +80,8 @@ export interface MultiSelectProps closeOnSelect?: boolean preventDeselect?: boolean hideOptionCheck?: boolean + optionTooltip?: MultiSelectOptionTooltip + optionTooltipClassName?: string } export interface MultiSelectRef { diff --git a/src/components/project/ProjectSelector.tsx b/src/components/project/ProjectSelector.tsx index 7a8f93e..12375eb 100644 --- a/src/components/project/ProjectSelector.tsx +++ b/src/components/project/ProjectSelector.tsx @@ -50,6 +50,9 @@ export function ProjectSelector() { spanClassName="text-sm [&_span]:text-kart-text" searchable resetScrollOnSearch + // Legacy react-tooltip: full "(pkey) title" on hover, right side, 65% opacity. + optionTooltip="singleLine" + optionTooltipClassName="opacity-65" preventDeselect hideOptionCheck disabled={projects.isPending} diff --git a/src/components/report/FilterPopup.tsx b/src/components/report/FilterPopup.tsx index 0150d42..92a894d 100644 --- a/src/components/report/FilterPopup.tsx +++ b/src/components/report/FilterPopup.tsx @@ -245,6 +245,9 @@ function FilterLineRow({ searchable preventDeselect hideOptionCheck + // Legacy QuestionSelect tooltip: full title on hover. + optionTooltip="singleLine" + optionTooltipClassName="opacity-65" onChange={(qid) => { const selected = questions.find((item) => item.qid === qid); if (!selected) return; @@ -302,6 +305,9 @@ function FilterLineRow({ badgeClassName="text-xs" maxSelected={multi ? undefined : 1} hideSelectAll={!multi} + // Legacy ValueSelect tooltip: full label on hover. + optionTooltip="singleLine" + optionTooltipClassName="opacity-65" onChange={(next) => { // Legacy keeps codes sorted and comma-joined. const value = [...next].sort().join(","); -- 2.49.0.windows.1 From 0d6cdd1eaa6239f0a4438357bfc1d1d630a957d9 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Fri, 23 Oct 2026 15:02:46 +0900 Subject: [PATCH 5/8] =?UTF-8?q?261023=5F02=5FENH:=20Data=20Import=20?= =?UTF-8?q?=ED=8C=8C=EC=83=9D=EB=B3=80=EC=88=98=20=EB=AF=B8=EC=A0=80?= =?UTF-8?q?=EC=9E=A5=C2=B7=EC=9E=AC=EA=B3=84=EC=82=B0=20=EC=95=88=EB=82=B4?= =?UTF-8?q?=EB=AC=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/exim/EximWorkspace.tsx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/components/exim/EximWorkspace.tsx b/src/components/exim/EximWorkspace.tsx index 9763d71..333f806 100644 --- a/src/components/exim/EximWorkspace.tsx +++ b/src/components/exim/EximWorkspace.tsx @@ -142,6 +142,7 @@ function Workspace({ project }: { project: ProjectRef }) { id="import_data" title="Data Import" info="Data를 교체 할수 있습니다." + notice="※ 파생변수 데이터는 저장되지 않으며, Data Import 직후 파생변수 값이 재계산됩니다." formTitle="Export Header" onForm={() => save({ kind: "form/data", project, name: { prefix: EXPORT_PREFIX.header, title } })} confirmText={title + " 프로젝트의 모든 완료 데이터를 삭제 후 진행됩니다.\r\n진행 하시겠습니까?"} @@ -194,11 +195,14 @@ function Column({ icon, title, children }: { icon: string; title: string; childr function EximBox({ title, info, + notice, action, children, }: { title: string; info: string; + /** Optional caution shown under the header row. */ + notice?: string; action?: ReactNode; children: ReactNode; }) { @@ -211,6 +215,7 @@ function EximBox({ {action} + {notice ?

{notice}

: null}
{children}
); @@ -247,6 +252,7 @@ function ImportBox({ id, title, info, + notice, formTitle, onForm, confirmText, @@ -257,6 +263,7 @@ function ImportBox({ id: string; title: string; info: string; + notice?: string; formTitle: string; onForm: () => void; confirmText: string; @@ -281,6 +288,7 @@ function ImportBox({ Date: Fri, 23 Oct 2026 15:26:12 +0900 Subject: [PATCH 6/8] =?UTF-8?q?261023=5F03=5FENH:=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EC=A0=9D=ED=8A=B8=C2=B7=ED=95=84=ED=84=B0=20=EC=84=A0=ED=83=9D?= =?UTF-8?q?=20=EA=B2=80=EC=83=89=EC=9D=84=20=EB=B6=80=EB=B6=84=20=EB=AC=B8?= =?UTF-8?q?=EC=9E=90=EC=97=B4=20=EC=9D=BC=EC=B9=98=EB=A1=9C=20=EB=B3=80?= =?UTF-8?q?=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 5 +++++ src/components/common/KriAutoComplete.tsx | 19 ++++++++++++++++-- .../common/multi-select/MultiSelect.tsx | 2 ++ .../multi-select/MultiSelectContent.tsx | 20 +++++++++++++++++-- src/components/common/multi-select/index.ts | 1 + src/components/common/multi-select/types.ts | 2 ++ src/components/project/ProjectSelector.tsx | 2 ++ src/components/report/FilterPopup.tsx | 4 ++++ 8 files changed, 51 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5d5b5bc..ea8c723 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -313,6 +313,11 @@ When implementing or changing frontend UI, use this order: - `kri-auto-complete` exposes `optionTooltip?: 'singleLine' | 'wrap'` and `optionTooltipClassName?: string` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It is off by default, preserving existing behavior. - When enabled, hovering an option shows its full `label` in a right-side tooltip. `singleLine` stays on one line until the available viewport width; `wrap` wraps at 28rem. The item depends on the shadcn `tooltip` component and provides its own `TooltipProvider`. +### KriAutoComplete Search Match + +- `kri-auto-complete` exposes `searchMatch?: 'fuzzy' | 'contains'` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `fuzzy` (cmdk's default subsequence scoring), preserving existing behavior. +- `contains` keeps only options whose label or value contains the search text as a case-insensitive substring, in the original option order. It applies only when `searchMode` is `filter`. + ### KriEditor SMS Preview - `changeSmsType` reports `SMS | LMS | MMS`. Update consumer callbacks to handle `MMS`; this widens the previous callback contract. diff --git a/src/components/common/KriAutoComplete.tsx b/src/components/common/KriAutoComplete.tsx index cec733e..a070c18 100644 --- a/src/components/common/KriAutoComplete.tsx +++ b/src/components/common/KriAutoComplete.tsx @@ -3,14 +3,25 @@ import * as React from 'react' import { cn } from '@/lib/utils' import { MultiSelect } from '@/components/common/multi-select' -import type { MultiSelectOption, MultiSelectOptionTooltip, MultiSelectRef } from '@/components/common/multi-select' +import type { + MultiSelectOption, + MultiSelectOptionTooltip, + MultiSelectRef, + MultiSelectSearchMatch, +} from '@/components/common/multi-select' -export type { MultiSelectOption, MultiSelectOptionTooltip, MultiSelectRef } from '@/components/common/multi-select' +export type { + MultiSelectOption, + MultiSelectOptionTooltip, + MultiSelectRef, + MultiSelectSearchMatch, +} from '@/components/common/multi-select' export interface KriAutoCompleteBaseProps { items: T[] searchable?: boolean searchMode?: 'filter' | 'inputOnly' + searchMatch?: MultiSelectSearchMatch resetScrollOnSearch?: boolean defaultSearchValue?: string onSearchValueChange?: (value: string) => void @@ -59,6 +70,7 @@ export function KriMultiSelect({ onChange, searchable = true, searchMode = 'filter', + searchMatch = 'fuzzy', resetScrollOnSearch = false, defaultSearchValue = '', onSearchValueChange, @@ -102,6 +114,7 @@ export function KriMultiSelect({ badgeClassName={badgeClassName} searchable={searchable} searchMode={searchMode} + searchMatch={searchMatch} resetScrollOnSearch={resetScrollOnSearch} defaultSearchValue={defaultSearchValue} onSearchValueChange={onSearchValueChange} @@ -140,6 +153,7 @@ function KriSingleSelectInner({ onChange, searchable = true, searchMode = 'filter', + searchMatch = 'fuzzy', resetScrollOnSearch = false, defaultSearchValue = '', onSearchValueChange, @@ -220,6 +234,7 @@ function KriSingleSelectInner({ badgeClassName={badgeClassName} searchable={searchable} searchMode={searchMode} + searchMatch={searchMatch} resetScrollOnSearch={resetScrollOnSearch} defaultSearchValue={defaultSearchValue} onSearchValueChange={onSearchValueChange} diff --git a/src/components/common/multi-select/MultiSelect.tsx b/src/components/common/multi-select/MultiSelect.tsx index 53c7207..0a13d0c 100644 --- a/src/components/common/multi-select/MultiSelect.tsx +++ b/src/components/common/multi-select/MultiSelect.tsx @@ -30,6 +30,7 @@ function MultiSelectInner( hideSelectAll = false, searchable = true, searchMode = 'filter', + searchMatch = 'fuzzy', resetScrollOnSearch = false, defaultSearchValue = '', onSearchValueChange, @@ -202,6 +203,7 @@ function MultiSelectInner( selectedValues={selectedValues} searchable={searchable} searchMode={searchMode} + searchMatch={searchMatch} resetScrollOnSearch={resetScrollOnSearch} searchValue={searchValue} onSearchValueChange={handleSearchChange} diff --git a/src/components/common/multi-select/MultiSelectContent.tsx b/src/components/common/multi-select/MultiSelectContent.tsx index 27957f5..98e3fda 100644 --- a/src/components/common/multi-select/MultiSelectContent.tsx +++ b/src/components/common/multi-select/MultiSelectContent.tsx @@ -13,14 +13,26 @@ import { } from '@/components/ui/command' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' -import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptionTooltip, MultiSelectOptions } from './types' +import type { + MultiSelectGroup, + MultiSelectOption, + MultiSelectOptionTooltip, + MultiSelectOptions, + MultiSelectSearchMatch, +} from './types' import { isGroupedOptions } from './utils' +// Case-insensitive substring match; equal scores keep the original option order. +function containsFilter(value: string, search: string) { + return value.toLowerCase().includes(search.toLowerCase()) ? 1 : 0 +} + interface MultiSelectContentProps { options: MultiSelectOptions selectedValues: string[] searchable: boolean searchMode: 'filter' | 'inputOnly' + searchMatch?: MultiSelectSearchMatch searchValue: string resetScrollOnSearch?: boolean onSearchValueChange: (value: string) => void @@ -134,6 +146,7 @@ export function MultiSelectContent({ selectedValues, searchable, searchMode, + searchMatch = 'fuzzy', searchValue, resetScrollOnSearch = false, onSearchValueChange, @@ -164,7 +177,10 @@ export function MultiSelectContent({ const tooltip = optionTooltip ? { mode: optionTooltip, className: optionTooltipClassName } : undefined const content = ( - + {searchable ? ( = MultiSelectOption[] | MultiSele export type MultiSelectSelectionMode = 'single' | 'multiple' export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted' export type MultiSelectOptionTooltip = 'singleLine' | 'wrap' +export type MultiSelectSearchMatch = 'fuzzy' | 'contains' export interface MultiSelectResponsiveSettings { maxCount?: number @@ -65,6 +66,7 @@ export interface MultiSelectProps hideSelectAll?: boolean searchable?: boolean searchMode?: 'filter' | 'inputOnly' + searchMatch?: MultiSelectSearchMatch resetScrollOnSearch?: boolean defaultSearchValue?: string onSearchValueChange?: (value: string) => void diff --git a/src/components/project/ProjectSelector.tsx b/src/components/project/ProjectSelector.tsx index 12375eb..f5b3f19 100644 --- a/src/components/project/ProjectSelector.tsx +++ b/src/components/project/ProjectSelector.tsx @@ -49,6 +49,8 @@ export function ProjectSelector() { className="h-8 min-h-8 rounded-[39px] border-[#d0d0d0] bg-kart-soft px-[22px] py-0 text-sm shadow-none" spanClassName="text-sm [&_span]:text-kart-text" searchable + // Legacy Dropdown search: case-insensitive substring, not fuzzy. + searchMatch="contains" resetScrollOnSearch // Legacy react-tooltip: full "(pkey) title" on hover, right side, 65% opacity. optionTooltip="singleLine" diff --git a/src/components/report/FilterPopup.tsx b/src/components/report/FilterPopup.tsx index 92a894d..36ace14 100644 --- a/src/components/report/FilterPopup.tsx +++ b/src/components/report/FilterPopup.tsx @@ -243,6 +243,8 @@ function FilterLineRow({ className="h-[38px] min-h-[38px] rounded-[4px] border-[#d0d0d0] text-sm" spanClassName="text-sm" searchable + // Legacy Dropdown search: case-insensitive substring, not fuzzy. + searchMatch="contains" preventDeselect hideOptionCheck // Legacy QuestionSelect tooltip: full title on hover. @@ -305,6 +307,8 @@ function FilterLineRow({ badgeClassName="text-xs" maxSelected={multi ? undefined : 1} hideSelectAll={!multi} + // Legacy ValueSelect search: case-insensitive substring. + searchMatch="contains" // Legacy ValueSelect tooltip: full label on hover. optionTooltip="singleLine" optionTooltipClassName="opacity-65" -- 2.49.0.windows.1 From d4747b0ea0e17d33ef85b94896850a18112d951f Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 26 Oct 2026 11:57:21 +0900 Subject: [PATCH 7/8] =?UTF-8?q?261026=5F01=5FENH:=20=EC=82=AC=EB=82=B4=20?= =?UTF-8?q?=EC=97=B0=EB=8F=99=20API=20=EC=B6=94=EA=B0=80=20=EB=B0=8F=20Sur?= =?UTF-8?q?veyProgress=20=EC=A0=84=ED=99=98=C2=B7=EB=AC=B8=EC=9E=90?= =?UTF-8?q?=EC=97=B4=20=ED=95=84=ED=84=B0=20=EC=A7=80=EC=9B=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- next.config.ts | 22 +- .../api/kric-internal/[[...slug]]/route.ts | 97 ++++++++ src/lib/filter-expression.ts | 220 ++++++++++++++++++ src/lib/http-server.ts | 10 + src/lib/kric-internal-policy.ts | 59 +++++ 5 files changed, 407 insertions(+), 1 deletion(-) create mode 100644 src/app/api/kric-internal/[[...slug]]/route.ts create mode 100644 src/lib/filter-expression.ts create mode 100644 src/lib/kric-internal-policy.ts diff --git a/next.config.ts b/next.config.ts index 7d7957e..301ab29 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,6 +1,26 @@ import type { NextConfig } from "next"; import { createKriNextConfig } from "@kri/common/config"; -const nextConfig = createKriNextConfig({}) satisfies NextConfig; +const nextConfig = createKriNextConfig({ + async headers() { + return [ + { + source: "/api/kric-internal/:path*", + headers: [ + { key: "Access-Control-Allow-Origin", value: "*" }, + { key: "Access-Control-Allow-Methods", value: "GET, POST, OPTIONS" }, + { + key: "Access-Control-Allow-Headers", + value: "Content-Type, X-API-Key", + }, + { + key: "Access-Control-Expose-Headers", + value: "Content-Disposition", + }, + ], + }, + ]; + }, +}) satisfies NextConfig; export default nextConfig; diff --git a/src/app/api/kric-internal/[[...slug]]/route.ts b/src/app/api/kric-internal/[[...slug]]/route.ts new file mode 100644 index 0000000..5b23c51 --- /dev/null +++ b/src/app/api/kric-internal/[[...slug]]/route.ts @@ -0,0 +1,97 @@ +import { NextRequest, NextResponse } from "next/server"; +import { errorToResponse } from "@kri/common/http"; +import { createServerApiWithApiKey } from "@/lib/http-server"; +import { + internalTarget, + readInternalQuotaRequest, + readInternalReportBatch, +} from "@/lib/kric-internal-policy"; +import { readExcelRequest } from "@/types/export"; +import type { RouteContext } from "@/types/common"; + +export const maxDuration = 660; +const noStore = { "Cache-Control": "no-store" }; +const jsonError = (message: string, status: number) => + NextResponse.json({ message }, { status, headers: noStore }); + +async function handle(request: NextRequest, context: RouteContext) { + const { slug = [] } = await context.params; + const target = internalTarget(request.method, slug); + if (!target) return jsonError("지원하지 않는 경로입니다.", 404); + const apiKey = request.headers.get("x-api-key")?.trim(); + if (!apiKey) return jsonError("X-API-Key는 필수입니다.", 401); + + let body: unknown; + if (target.kind !== "list") { + try { + const input: unknown = await request.json(); + body = + target.kind === "report" + ? readInternalReportBatch(input) + : target.kind === "quota" + ? readInternalQuotaRequest(input) + : readExcelRequest(input); + } catch (error) { + return jsonError( + error instanceof SyntaxError + ? "요청 JSON을 확인해 주세요." + : error instanceof Error + ? error.message + : "요청 내용을 확인해 주세요.", + 400, + ); + } + } + + try { + const api = createServerApiWithApiKey(apiKey); + const options = { signal: request.signal, cache: "no-store" as const }; + if (target.kind === "list" || target.kind === "quota") { + const result = + target.kind === "list" + ? await api.get(target.path, options) + : await api.post(target.path, body, options); + return NextResponse.json(result, { headers: noStore }); + } + const upstream = await api.streamPost(target.path, body, { + ...options, + timeoutMs: 600_000, + idleTimeoutMs: 600_000, + ...(target.kind === "report" + ? { headers: { Accept: "application/x-ndjson" } } + : {}), + }); + const contentType = + upstream.headers.get("content-type") ?? "application/octet-stream"; + const disposition = upstream.headers.get("content-disposition"); + if ( + !upstream.body || + (target.kind === "report" + ? !contentType.includes("application/x-ndjson") + : !disposition || /json|text\/html/i.test(contentType)) + ) { + await upstream.body?.cancel(); + return jsonError("서버 응답 형식을 확인해 주세요.", 502); + } + return new Response(upstream.body, { + headers: { + ...noStore, + "Content-Type": contentType, + ...(target.kind === "report" + ? { "X-Accel-Buffering": "no" } + : disposition + ? { "Content-Disposition": disposition } + : {}), + }, + }); + } catch (error: unknown) { + const response = errorToResponse(error); + response.headers.set("Cache-Control", "no-store"); + return response; + } +} + +export const GET = handle; +export const POST = handle; +export const OPTIONS = () => + new NextResponse(null, { status: 204, headers: noStore }); diff --git a/src/lib/filter-expression.ts b/src/lib/filter-expression.ts new file mode 100644 index 0000000..cd4d25c --- /dev/null +++ b/src/lib/filter-expression.ts @@ -0,0 +1,220 @@ +import type { ReportFilter } from "@/types/report"; + +type Token = { text: string; position: number } & ( + | { kind: "word" | "symbol" | "end" } + | { kind: "value"; value: string | number } +); + +const fail = (position: number, message: string): never => { + throw new Error(`필터 ${position + 1}번째 문자: ${message}`); +}; + +/** A bounded expression grammar, never SQL or JavaScript execution. */ +function tokenize(source: string): Token[] { + if (source.length > 8192) fail(0, "조건식은 8192자 이내로 작성해 주세요."); + const tokens: Token[] = []; + let position = 0; + while (position < source.length) { + if (/\s/.test(source[position])) { + position++; + continue; + } + if (tokens.length >= 2048) fail(position, "조건식이 너무 복잡합니다."); + const start = position; + const char = source[position]; + if (char === "'" || char === '"') { + position++; + let value = "", + closed = false; + while (position < source.length) { + const next = source[position++]; + if (next !== char) { + value += next; + continue; + } + if (source[position] === char) { + value += char; + position++; + } else { + closed = true; + break; + } + } + if (!closed) fail(start, "문자열의 닫는 따옴표가 필요합니다."); + tokens.push({ + kind: "value", + text: source.slice(start, position), + value, + position: start, + }); + continue; + } + const rest = source.slice(position); + const number = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(rest); + if (number) { + const value = Number(number[0]); + if ( + !Number.isFinite(value) || + (Number.isInteger(value) && !Number.isSafeInteger(value)) + ) + fail( + start, + "숫자 범위를 확인해 주세요. 큰 코드값은 따옴표로 감싸 주세요.", + ); + tokens.push({ kind: "value", text: number[0], value, position: start }); + position += number[0].length; + continue; + } + const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest); + const symbol = /^(?:>=|<=|<>|!=|[=><(),])/.exec(rest); + const match = word ?? symbol; + if (!match) + return fail( + start, + "지원하지 않는 문자입니다. 문항 ID, 비교식, AND·OR·괄호를 사용해 주세요.", + ); + tokens.push({ + kind: word ? "word" : "symbol", + text: match[0], + position: start, + }); + position += match[0].length; + } + tokens.push({ kind: "end", text: "", position }); + return tokens; +} + +/** Precedence: parentheses, NOT, AND, OR. Identifiers refer to QIDs. */ +export function parseFilterExpression(source: string): ReportFilter | null { + const tokens = tokenize(source); + let cursor = 0; + const peek = () => tokens[cursor]; + const take = (text: string) => { + const token = peek(); + if (token.kind !== "value" && token.text.toUpperCase() === text) { + cursor++; + return true; + } + return false; + }; + const expect = (text: string) => { + if (!take(text)) fail(peek().position, `${text} 토큰이 필요합니다.`); + }; + const value = (): string | number => { + const token = peek(); + if (token.kind !== "value") + return fail( + token.position, + "비교할 숫자 또는 따옴표로 감싼 문자열이 필요합니다.", + ); + cursor++; + return token.value; + }; + const group = ( + operator: "AND" | "OR", + children: ReportFilter[], + ): ReportFilter => + children.length === 1 ? children[0] : { operator, children }; + + function condition(): ReportFilter { + const id = peek(); + if ( + id.kind !== "word" || + /^(AND|OR|NOT|IN|BETWEEN|IS|NULL)$/i.test(id.text) + ) + return fail(id.position, "비교할 문항 ID가 필요합니다."); + cursor++; + const base = { dimensionId: id.text, reference: "QID" as const }; + if (take("IS")) { + const not = take("NOT"); + expect("NULL"); + return { + ...base, + operator: not ? "IS_ANSWERED" : "IS_UNANSWERED", + values: [], + }; + } + const not = take("NOT"); + if (take("IN")) { + expect("("); + const values = [value()]; + while (take(",")) { + if (values.length >= 128) + fail(peek().position, "IN 목록은 128개 이내로 작성해 주세요."); + values.push(value()); + } + expect(")"); + return { ...base, operator: not ? "NOT_IN" : "IN", values }; + } + if (take("BETWEEN")) { + const low = value(); + expect("AND"); + const result: ReportFilter = { + ...base, + operator: "BETWEEN", + values: [low, value()], + }; + return not ? { operator: "NOT", children: [result] } : result; + } + if (not) + return fail(peek().position, "NOT 뒤에는 IN 또는 BETWEEN이 필요합니다."); + const token = peek(); + const operators: Record = { + "=": "EQ", + "!=": "NE", + "<>": "NE", + ">": "GT", + ">=": "GE", + "<": "LT", + "<=": "LE", + }; + const operator = + token.kind === "symbol" ? operators[token.text] : undefined; + if (!operator) + return fail( + token.position, + "비교 연산자(=, !=, <>, >, >=, <, <=, IN 등)가 필요합니다.", + ); + cursor++; + return { ...base, operator, values: [value()] }; + } + + function primary(depth: number): ReportFilter { + if (depth > 32) + return fail(peek().position, "괄호와 NOT은 32단계 이내로 작성해 주세요."); + if (take("NOT")) return { operator: "NOT", children: [primary(depth + 1)] }; + if (!take("(")) return condition(); + const result = expression(depth + 1); + expect(")"); + return result; + } + function and(depth: number): ReportFilter { + const children = [primary(depth)]; + while (take("AND")) { + if (children.length >= 128) + fail( + peek().position, + "AND 조건은 한 그룹에 128개 이내로 작성해 주세요.", + ); + children.push(primary(depth)); + } + return group("AND", children); + } + function expression(depth: number): ReportFilter { + const children = [and(depth)]; + while (take("OR")) { + if (children.length >= 128) + fail( + peek().position, + "OR 조건은 한 그룹에 128개 이내로 작성해 주세요.", + ); + children.push(and(depth)); + } + return group("OR", children); + } + if (peek().kind === "end") return null; + const result = expression(0); + if (peek().kind !== "end") + fail(peek().position, "조건 사이의 AND·OR 또는 괄호를 확인해 주세요."); + return result; +} diff --git a/src/lib/http-server.ts b/src/lib/http-server.ts index 39fe43f..cf0fa11 100644 --- a/src/lib/http-server.ts +++ b/src/lib/http-server.ts @@ -14,3 +14,13 @@ export async function createServerApi(authenticated = true) { onResponseError: false, }); } + +/** Internal integrations authenticate with their supplied key, never the browser session. */ +export function createServerApiWithApiKey(apiKey: string) { + return createHttpClient(serverEnv.API_SERVER, { + defaultHeaders: { "content-type": "application/json", "X-API-Key": apiKey }, + onUnauthorized: false, + onForbidden: false, + onResponseError: false, + }); +} diff --git a/src/lib/kric-internal-policy.ts b/src/lib/kric-internal-policy.ts new file mode 100644 index 0000000..77c54d0 --- /dev/null +++ b/src/lib/kric-internal-policy.ts @@ -0,0 +1,59 @@ +import { + exportTarget, + isQuotaListPath, + isQuotaResultPath, + isReportStreamPath, +} from "@/lib/project-proxy-policy"; +import { isRecord, validDateRange } from "@/types/kart"; +import { readReportBatch } from "@/lib/report-contract"; +import { parseFilterExpression } from "@/lib/filter-expression"; + +type Target = { path: string; kind: "list" | "quota" | "report" | "excel" }; + +/** Adapt integration input to the existing report contract without coupling the parser to HTTP. */ +export function readInternalReportBatch(value: unknown) { + return readReportBatch( + isRecord(value) && typeof value.filter === "string" + ? { ...value, filter: parseFilterExpression(value.filter) } + : value, + ); +} + +/** Only the five approved integration operations; no arbitrary upstream forwarding. */ +export function internalTarget(method: string, slug: string[]): Target | null { + const [area, ...parts] = slug; + const path = "/" + slug.map(encodeURIComponent).join("/"); + if (method === "GET" && area === "quota" && isQuotaListPath(parts)) + return { path, kind: "list" }; + if (method !== "POST") return null; + if (area === "project" && isReportStreamPath(parts)) + return { path, kind: "report" }; + if (area === "quota" && isQuotaResultPath(parts)) + return { path, kind: "quota" }; + if ( + area === "export" && + parts.length === 3 && + ["table", "quota"].includes(parts[2]) + ) { + const target = exportTarget("POST", parts); + if (target) return { path: target.path, kind: "excel" }; + } + return null; +} + +/** Broader backend quota contract, without changing the ordinary screen's request policy. */ +export function readInternalQuotaRequest(value: unknown) { + if (!isRecord(value)) throw new Error("쿼터 조회 조건을 확인해 주세요."); + const dataScope = value.dataScope ?? "ACTUAL"; + const startDate = value.startDate ?? ""; + const endDate = value.endDate ?? ""; + if ( + !["ACTUAL", "TEST", "ALL"].includes(String(dataScope)) || + typeof dataScope !== "string" || + typeof startDate !== "string" || + typeof endDate !== "string" || + !validDateRange({ startDate, endDate }) + ) + throw new Error("쿼터 데이터 범위와 조회 날짜를 확인해 주세요."); + return { dataScope, ...(startDate ? { startDate, endDate } : {}) }; +} -- 2.49.0.windows.1 From a1f39c74deed86f2f153a3e66d907e2c5e88cf1d Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Tue, 27 Oct 2026 09:03:18 +0900 Subject: [PATCH 8/8] =?UTF-8?q?261027=5F01=5FENH:=20=EC=82=AC=EB=82=B4=20?= =?UTF-8?q?=EC=97=B0=EB=8F=99=20API=EC=97=90=20url=20copy=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package-lock.json | 98 +++++++++---------- package.json | 4 +- .../api/kric-internal/[[...slug]]/route.ts | 26 ++++- src/lib/kric-internal-policy.ts | 46 ++++++++- 4 files changed, 118 insertions(+), 56 deletions(-) diff --git a/package-lock.json b/package-lock.json index d132611..93d75dc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -41,7 +41,7 @@ "embla-carousel-react": "^8.6.0", "jotai": "latest", "lucide-react": "latest", - "next": "latest", + "next": "~16.4.1", "prettier": "^3.9.10", "radix-ui": "^1.8.0", "react": "latest", @@ -59,7 +59,7 @@ "@types/react-dom": "latest", "babel-plugin-react-compiler": "latest", "eslint": "^9", - "eslint-config-next": "latest", + "eslint-config-next": "~16.4.1", "playwright": "^1.64.1", "tailwindcss": "latest", "tw-animate-css": "latest", @@ -1260,15 +1260,15 @@ } }, "node_modules/@next/env": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.0.tgz", - "integrity": "sha512-pyLlT5oafGlX8X7xjgGNXz5dNIDSxREm+qD6i9VLSZiZFopA/XWl8NM/KPmLx/8EG/++c49iid3gNWSQW1+2dQ==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.3.tgz", + "integrity": "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==", "license": "MIT" }, "node_modules/@next/eslint-plugin-next": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.0.tgz", - "integrity": "sha512-ffeflB/dL8RrvWejQximw01pOpKHN692Y3FjDB82DCd0YVvXvBD6vY7mcZp27yvSVFVM6wA73xVodEKF4spizA==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.3.tgz", + "integrity": "sha512-oxuC06wt/71h6ACYCV9GbKOfnf5a7VlRe/p80YHTut15TNgDEmynDnaq8t/xhy5rlvk7dhItIPs6H3rvIM4kyw==", "dev": true, "license": "MIT", "dependencies": { @@ -1309,9 +1309,9 @@ } }, "node_modules/@next/swc-darwin-arm64": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.0.tgz", - "integrity": "sha512-yyZ+9MgViAKLLb5l1gPBGjRwnq3teNLb5Zx6JEw8LzNSTjlsnp+baUHFxTgl7PpjCmKf48VQfyipG1eBflb48Q==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.3.tgz", + "integrity": "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==", "cpu": [ "arm64" ], @@ -1325,9 +1325,9 @@ } }, "node_modules/@next/swc-darwin-x64": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.0.tgz", - "integrity": "sha512-RePEEejEj1Auf5s9qEcG0JbcDP3ceNUS/ofNX8AhxzgIjTVlZIHMatlp16YplcSMpsVo/ZMQHJTjbMYJznjGUg==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.3.tgz", + "integrity": "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==", "cpu": [ "x64" ], @@ -1341,9 +1341,9 @@ } }, "node_modules/@next/swc-linux-arm64-gnu": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.0.tgz", - "integrity": "sha512-HhsyCqd+NpmvDDVY/LqkAN24f+QVvXh3ie+PfcwKinWL2Mu826JymQxJXGjAIfmJ4VlHjp4Pe/nZtXtUoEMAqw==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.3.tgz", + "integrity": "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==", "cpu": [ "arm64" ], @@ -1357,9 +1357,9 @@ } }, "node_modules/@next/swc-linux-arm64-musl": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.0.tgz", - "integrity": "sha512-sN9Pf+Zh+RpZAOmbR7d8KAA8T61CVhawtbEJ2Bk6QrRzx6Z/6haaF4UiwBzytM96GRRRWZh9/WALIEO3npMamA==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.3.tgz", + "integrity": "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==", "cpu": [ "arm64" ], @@ -1373,9 +1373,9 @@ } }, "node_modules/@next/swc-linux-x64-gnu": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.0.tgz", - "integrity": "sha512-D5M5xLWQVd1CvR+L7BickM1weRfmM41x3L1NWcnKY/oyJJqr1qwaCgmu3dMAhLBOMdZwSuDCRV6DJRRpiUkbDQ==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.3.tgz", + "integrity": "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==", "cpu": [ "x64" ], @@ -1389,9 +1389,9 @@ } }, "node_modules/@next/swc-linux-x64-musl": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.0.tgz", - "integrity": "sha512-8d5WLS6a9YalqpOgXdlbvonFu+sIgjA+CO6tGzetrpPVcUL56foa7B7664h41rAlbLi5fJwK4vWji3zf4QDy+w==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.3.tgz", + "integrity": "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==", "cpu": [ "x64" ], @@ -1405,9 +1405,9 @@ } }, "node_modules/@next/swc-win32-arm64-msvc": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.0.tgz", - "integrity": "sha512-sQuOIiW3snb48UwrBcDMvFA/u03qtw2LeuSIxFIQ9AJuW9UG/4Ddsfo+eV73PnZwBhyncMtsKVh7PrzMol2/fA==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.3.tgz", + "integrity": "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==", "cpu": [ "arm64" ], @@ -1421,9 +1421,9 @@ } }, "node_modules/@next/swc-win32-x64-msvc": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.0.tgz", - "integrity": "sha512-6/33lCuxpdHUy27RegyGM/5uTpF7YZd3UR4D0gpkOA/tWY5YR7msbQjqPgCZmSmxrrTLGCXYA4A8vT2H5DPGTQ==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.3.tgz", + "integrity": "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==", "cpu": [ "x64" ], @@ -5785,13 +5785,13 @@ } }, "node_modules/eslint-config-next": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.0.tgz", - "integrity": "sha512-2RHLYswzc+hNRktWAjIL6XAvwb1cKcjLawJ5KWywAxn/JivNHtG42ZigL1yobVXDqsimuuL2F9jcEcnHFzbppQ==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.3.tgz", + "integrity": "sha512-j9IqBma6abp800frdUURaizYMgXOK+jNGyq6CsYcM9AxpSJs5D/TgMNGeAmRUilZvA7g9V1Tr71gNg9/SVTuMQ==", "dev": true, "license": "MIT", "dependencies": { - "@next/eslint-plugin-next": "16.4.0", + "@next/eslint-plugin-next": "16.4.3", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", @@ -7723,12 +7723,12 @@ "license": "MIT" }, "node_modules/next": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/next/-/next-16.4.0.tgz", - "integrity": "sha512-N2C+9q89Z/oLrsepSRS4jRMtwmUZAoZuAHU0e9T6+sAB5DdhADmrnOW+zjYijlrYFmVfmQhGVGy9eMFoB7UgKg==", + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/next/-/next-16.4.3.tgz", + "integrity": "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==", "license": "MIT", "dependencies": { - "@next/env": "16.4.0", + "@next/env": "16.4.3", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -7742,15 +7742,15 @@ "node": ">=20.9.0" }, "optionalDependencies": { - "@next/swc-darwin-arm64": "16.4.0", - "@next/swc-darwin-x64": "16.4.0", - "@next/swc-linux-arm64-gnu": "16.4.0", - "@next/swc-linux-arm64-musl": "16.4.0", - "@next/swc-linux-x64-gnu": "16.4.0", - "@next/swc-linux-x64-musl": "16.4.0", - "@next/swc-win32-arm64-msvc": "16.4.0", - "@next/swc-win32-x64-msvc": "16.4.0", - "sharp": "^0.35.4" + "@next/swc-darwin-arm64": "16.4.3", + "@next/swc-darwin-x64": "16.4.3", + "@next/swc-linux-arm64-gnu": "16.4.3", + "@next/swc-linux-arm64-musl": "16.4.3", + "@next/swc-linux-x64-gnu": "16.4.3", + "@next/swc-linux-x64-musl": "16.4.3", + "@next/swc-win32-arm64-msvc": "16.4.3", + "@next/swc-win32-x64-msvc": "16.4.3", + "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", diff --git a/package.json b/package.json index 9cd1118..3e28256 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "embla-carousel-react": "^8.6.0", "jotai": "latest", "lucide-react": "latest", - "next": "latest", + "next": "~16.4.1", "prettier": "^3.9.10", "radix-ui": "^1.8.0", "react": "latest", @@ -61,7 +61,7 @@ "@types/react-dom": "latest", "babel-plugin-react-compiler": "latest", "eslint": "^9", - "eslint-config-next": "latest", + "eslint-config-next": "~16.4.1", "playwright": "^1.64.1", "tailwindcss": "latest", "tw-animate-css": "latest", diff --git a/src/app/api/kric-internal/[[...slug]]/route.ts b/src/app/api/kric-internal/[[...slug]]/route.ts index 5b23c51..a402756 100644 --- a/src/app/api/kric-internal/[[...slug]]/route.ts +++ b/src/app/api/kric-internal/[[...slug]]/route.ts @@ -5,8 +5,11 @@ import { internalTarget, readInternalQuotaRequest, readInternalReportBatch, + readInternalShareRequest, } from "@/lib/kric-internal-policy"; import { readExcelRequest } from "@/types/export"; +import { isRecord } from "@/types/kart"; +import { isShareLink } from "@/types/share"; import type { RouteContext } from "@/types/common"; export const maxDuration = 660; @@ -22,7 +25,7 @@ async function handle(request: NextRequest, context: RouteContext) { if (!apiKey) return jsonError("X-API-Key는 필수입니다.", 401); let body: unknown; - if (target.kind !== "list") { + if (target.kind !== "list" && target.kind !== "respondent") { try { const input: unknown = await request.json(); body = @@ -30,7 +33,9 @@ async function handle(request: NextRequest, context: RouteContext) { ? readInternalReportBatch(input) : target.kind === "quota" ? readInternalQuotaRequest(input) - : readExcelRequest(input); + : target.kind === "share" + ? readInternalShareRequest(input) + : readExcelRequest(input); } catch (error) { return jsonError( error instanceof SyntaxError @@ -46,11 +51,26 @@ async function handle(request: NextRequest, context: RouteContext) { try { const api = createServerApiWithApiKey(apiKey); const options = { signal: request.signal, cache: "no-store" as const }; - if (target.kind === "list" || target.kind === "quota") { + if ( + target.kind === "list" || + target.kind === "quota" || + target.kind === "respondent" || + target.kind === "share" + ) { const result = target.kind === "list" ? await api.get(target.path, options) : await api.post(target.path, body, options); + if ( + target.kind === "share" && + (!isShareLink(result) || + result.projectType !== Number(slug[1]) || + result.pkey !== slug[2] || + result.pageOnly || + !isRecord(body) || + result.realUrl !== body.realUrl) + ) + return jsonError("공유 링크 응답을 확인해 주세요.", 502); return NextResponse.json(result, { headers: noStore }); } const upstream = await api.streamPost(target.path, body, { diff --git a/src/lib/kric-internal-policy.ts b/src/lib/kric-internal-policy.ts index 77c54d0..8943fc4 100644 --- a/src/lib/kric-internal-policy.ts +++ b/src/lib/kric-internal-policy.ts @@ -3,12 +3,26 @@ import { isQuotaListPath, isQuotaResultPath, isReportStreamPath, + isProjectReadPath, } from "@/lib/project-proxy-policy"; import { isRecord, validDateRange } from "@/types/kart"; import { readReportBatch } from "@/lib/report-contract"; import { parseFilterExpression } from "@/lib/filter-expression"; +import { reportUrl } from "@/types/share"; -type Target = { path: string; kind: "list" | "quota" | "report" | "excel" }; +type Target = { + path: string; + kind: "list" | "quota" | "report" | "excel" | "respondent" | "share"; +}; + +/** URL Copy only: the server resolves the project from the authenticated path. */ +export function readInternalShareRequest(value: unknown) { + if (!isRecord(value) || value.mode !== "U") + throw new Error("URL Copy 요청은 mode를 U로 지정해 주세요."); + const realUrl = reportUrl(value.realUrl); + if (!realUrl) throw new Error("공유할 보고서 화면 경로를 확인해 주세요."); + return { realUrl, mode: "U" as const }; +} /** Adapt integration input to the existing report contract without coupling the parser to HTTP. */ export function readInternalReportBatch(value: unknown) { @@ -19,13 +33,41 @@ export function readInternalReportBatch(value: unknown) { ); } -/** Only the five approved integration operations; no arbitrary upstream forwarding. */ +/** Fixed integration operations only; no arbitrary upstream forwarding. */ export function internalTarget(method: string, slug: string[]): Target | null { const [area, ...parts] = slug; const path = "/" + slug.map(encodeURIComponent).join("/"); if (method === "GET" && area === "quota" && isQuotaListPath(parts)) return { path, kind: "list" }; if (method !== "POST") return null; + if ( + area === "project" && + parts.length === 3 && + parts[2] === "share" && + isProjectReadPath([parts[0], parts[1], "question", "list"]) + ) + return { path, kind: "share" }; + if ( + area === "project" && + parts.length === 6 && + parts[2] === "derived" && + parts[3] === "respondent" && + parts[5] === "recalculate" && + isProjectReadPath([parts[0], parts[1], "question", "list"]) + ) { + const id = parts[4]; + if ( + id.trim() && + id.length <= 512 && + id !== "." && + id !== ".." && + !/[\/\\]/.test(id) && + !Array.from(id).some( + (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127, + ) + ) + return { path, kind: "respondent" }; + } if (area === "project" && isReportStreamPath(parts)) return { path, kind: "report" }; if (area === "quota" && isQuotaResultPath(parts)) -- 2.49.0.windows.1