260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋
This commit is contained in:
87
src/components/app-shell/AppHeader.tsx
Normal file
87
src/components/app-shell/AppHeader.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { LogOut, ZoomIn, ZoomOut } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { KriHeader } from "@/components/layout/KriHeader";
|
||||
import type { TopMenuItem } from "@/config/menu.types";
|
||||
import type { LoginUser } from "@kri/common";
|
||||
|
||||
interface AppHeaderProps {
|
||||
isMain: boolean;
|
||||
menuOpen: boolean;
|
||||
activeTopId: string;
|
||||
topMenus: TopMenuItem[];
|
||||
isViewProjectTitle: boolean;
|
||||
projectName?: string;
|
||||
userInfo?: LoginUser;
|
||||
fontSize: number;
|
||||
onToggleMenu: () => void;
|
||||
onNavigate: (path: string) => void;
|
||||
decreaseFontSize: () => void;
|
||||
increaseFontSize: () => void;
|
||||
}
|
||||
|
||||
export function AppHeader({
|
||||
isMain,
|
||||
menuOpen,
|
||||
activeTopId,
|
||||
topMenus,
|
||||
isViewProjectTitle,
|
||||
projectName,
|
||||
userInfo,
|
||||
fontSize,
|
||||
onToggleMenu,
|
||||
onNavigate,
|
||||
decreaseFontSize,
|
||||
increaseFontSize,
|
||||
}: AppHeaderProps) {
|
||||
return (
|
||||
<KriHeader
|
||||
logo={
|
||||
<div className="flex h-10 w-20 items-center justify-center">
|
||||
<Image
|
||||
src="/kri_logo.png"
|
||||
alt="KRI 로고"
|
||||
width={120}
|
||||
height={40}
|
||||
className="object-contain"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
homePath="/"
|
||||
menus={topMenus}
|
||||
activeMenuId={activeTopId}
|
||||
menuOpen={menuOpen}
|
||||
showMenuButton={!isMain}
|
||||
onToggleMenu={onToggleMenu}
|
||||
onNavigate={(path) => onNavigate(path)}
|
||||
className="border-gray-200 bg-white"
|
||||
innerClassName="h-16 px-4"
|
||||
center={
|
||||
isViewProjectTitle && projectName ? (
|
||||
<h1 className="ml-3 text-2xl font-bold">{projectName}</h1>
|
||||
) : null
|
||||
}
|
||||
right={
|
||||
<>
|
||||
<div className="flex items-center gap-1 border-r pr-4">
|
||||
<Button variant="ghost" size="icon" onClick={decreaseFontSize} title="폰트 작게">
|
||||
<ZoomOut className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="min-w-[3rem] text-center text-xs text-gray-500">{fontSize}px</span>
|
||||
<Button variant="ghost" size="icon" onClick={increaseFontSize} title="폰트 크게">
|
||||
<ZoomIn className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<span className="hidden text-sm text-gray-600 sm:inline">{userInfo?.userName || ""}</span>
|
||||
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
|
||||
<LogOut className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">로그아웃</span>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
219
src/components/app-shell/AppMainLayout.tsx
Normal file
219
src/components/app-shell/AppMainLayout.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
"use client";
|
||||
|
||||
import { ReactNode, useEffect, useMemo, useState } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
||||
import { AppHeader } from "@/components/app-shell/AppHeader";
|
||||
import { AppSidebar } from "@/components/app-shell/AppSidebar";
|
||||
import { useFontSize } from "@/hooks/useFontSize";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data";
|
||||
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { FONT_SIZE } from "@/const/commonConst";
|
||||
|
||||
type AppMainLayoutProps = {
|
||||
children: ReactNode;
|
||||
initialFontSize: number;
|
||||
};
|
||||
|
||||
type AccessControlledItem = {
|
||||
path?: string;
|
||||
accessRole: number[];
|
||||
children?: AccessControlledItem[];
|
||||
match?: (pathname: string) => boolean;
|
||||
};
|
||||
|
||||
function canAccess(accessRole: number[], userRole: number | undefined): boolean {
|
||||
return accessRole.length === 0 || (userRole !== undefined && accessRole.includes(userRole));
|
||||
}
|
||||
|
||||
function filterTopMenusByRole(menus: TopMenuItem[], userRole: number | undefined): TopMenuItem[] {
|
||||
return menus.filter((menu) => canAccess(menu.accessRole, userRole));
|
||||
}
|
||||
|
||||
function filterSubMenusByRole(children: SideSubMenuItem[] | undefined, userRole: number | undefined): SideSubMenuItem[] | undefined {
|
||||
const filtered = children?.filter((child) => canAccess(child.accessRole, userRole));
|
||||
return filtered?.length ? filtered : undefined;
|
||||
}
|
||||
|
||||
function filterSideMenusByRole(menus: SideMenuItem[], userRole: number | undefined): SideMenuItem[] {
|
||||
return menus.reduce<SideMenuItem[]>((acc, menu) => {
|
||||
if (!canAccess(menu.accessRole, userRole)) return acc;
|
||||
|
||||
const children = filterSubMenusByRole(menu.children, userRole);
|
||||
if (!menu.path && menu.children?.length && !children?.length) return acc;
|
||||
|
||||
acc.push({
|
||||
...menu,
|
||||
...(children ? { children } : { children: undefined }),
|
||||
});
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function pathMatches(item: AccessControlledItem, pathname: string): boolean {
|
||||
if (item.match?.(pathname)) return true;
|
||||
return Boolean(item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)));
|
||||
}
|
||||
|
||||
function findSideAccessChain(pathname: string, menus: SideMenuItem[]): AccessControlledItem[] | null {
|
||||
const matches: AccessControlledItem[][] = [];
|
||||
|
||||
menus.forEach((menu) => {
|
||||
if (menu.path && pathMatches(menu, pathname)) {
|
||||
matches.push([menu]);
|
||||
}
|
||||
|
||||
menu.children?.forEach((child) => {
|
||||
if (pathMatches(child, pathname)) {
|
||||
matches.push([menu, child]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (!matches.length) return null;
|
||||
|
||||
return matches.sort((a, b) => {
|
||||
const aPath = a.at(-1)?.path ?? "";
|
||||
const bPath = b.at(-1)?.path ?? "";
|
||||
return bPath.length - aPath.length;
|
||||
})[0];
|
||||
}
|
||||
|
||||
function findTopAccessChain(pathname: string, menus: TopMenuItem[]): AccessControlledItem[] | null {
|
||||
const match = menus.find((menu) => pathMatches(menu, pathname));
|
||||
return match ? [match] : null;
|
||||
}
|
||||
|
||||
function findAccessChain(pathname: string): AccessControlledItem[] | null {
|
||||
return (
|
||||
findSideAccessChain(pathname, [...projectSideMenus, ...manageSideMenus]) ??
|
||||
findTopAccessChain(pathname, topMenus)
|
||||
);
|
||||
}
|
||||
|
||||
export default function AppMainLayout({ children, initialFontSize }: AppMainLayoutProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const mounted = useMounted();
|
||||
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject();
|
||||
const [menuOpen, setMenuOpen] = useState(true);
|
||||
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
|
||||
const userRole = auth.user?.userRole;
|
||||
|
||||
const isMain = pathname === "/";
|
||||
const isProjectMenu = !pathname.startsWith("/manage");
|
||||
const isViewProjectTitle = !isMain && isProjectMenu && !pathname.startsWith("/project/info");
|
||||
const visibleTopMenus = useMemo(() => filterTopMenusByRole(topMenus, userRole), [userRole]);
|
||||
const visibleProjectSideMenus = useMemo(() => filterSideMenusByRole(projectSideMenus, userRole), [userRole]);
|
||||
const visibleManageSideMenus = useMemo(() => filterSideMenusByRole(manageSideMenus, userRole), [userRole]);
|
||||
const activeTop = visibleTopMenus.find((menu) => menu.match?.(pathname)) ?? visibleTopMenus[0] ?? topMenus[0];
|
||||
const sideMenus = isProjectMenu ? visibleProjectSideMenus : visibleManageSideMenus;
|
||||
const hasRouteAccess = useMemo(() => {
|
||||
if (!auth.user) return true;
|
||||
|
||||
const accessChain = findAccessChain(pathname);
|
||||
if (!accessChain) return true;
|
||||
|
||||
return accessChain.every((item) => canAccess(item.accessRole, userRole));
|
||||
}, [auth.user, pathname, userRole]);
|
||||
|
||||
const [openMenus, setOpenMenus] = useState<Record<string, boolean>>(() => {
|
||||
const initial: Record<string, boolean> = {};
|
||||
|
||||
sideMenus.forEach((item) => {
|
||||
if (item.children?.some((child) => pathname === child.path || pathname.startsWith(`${child.path}/`))) {
|
||||
initial[item.id] = true;
|
||||
}
|
||||
});
|
||||
|
||||
return initial;
|
||||
});
|
||||
|
||||
const movePage = (path: string) => {
|
||||
router.push(path);
|
||||
};
|
||||
|
||||
const decreaseFontSize = () => {
|
||||
setFontSize(Math.max(FONT_SIZE.MIN, fontSize - 2));
|
||||
};
|
||||
|
||||
const increaseFontSize = () => {
|
||||
setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
if (!auth.user) {
|
||||
router.replace("/logout");
|
||||
}
|
||||
}, [auth.user, mounted, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted || !auth.user || hasRouteAccess) return;
|
||||
|
||||
alert("접근 권한이 없습니다.");
|
||||
router.replace("/");
|
||||
}, [auth.user, hasRouteAccess, mounted, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSelectedProjectHydrated) return;
|
||||
if (!hasRouteAccess) return;
|
||||
|
||||
if (!isMain && isProjectMenu && !selectedProject) {
|
||||
alert("선택된 프로젝트가 없습니다.");
|
||||
router.replace("/");
|
||||
}
|
||||
}, [hasRouteAccess, isMain, isProjectMenu, isSelectedProjectHydrated, router, selectedProject]);
|
||||
|
||||
if (mounted && auth.user && !hasRouteAccess) return null;
|
||||
|
||||
return (
|
||||
<KriMainLayout
|
||||
fullHeight={false}
|
||||
className={cn("bg-gray-50", "h-screen overflow-hidden")}
|
||||
bodyClassName={cn(!isMain && "min-h-0")}
|
||||
mainClassName={cn("p-4", "min-h-0")}
|
||||
mainStyle={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
|
||||
sidebarOpen={!isMain && menuOpen}
|
||||
onSidebarOpenChange={setMenuOpen}
|
||||
header={
|
||||
<AppHeader
|
||||
isMain={isMain}
|
||||
menuOpen={menuOpen}
|
||||
activeTopId={activeTop.id}
|
||||
topMenus={visibleTopMenus}
|
||||
isViewProjectTitle={isViewProjectTitle}
|
||||
projectName={selectedProject?.prjctName}
|
||||
userInfo={auth.user ?? undefined}
|
||||
fontSize={fontSize}
|
||||
onToggleMenu={() => setMenuOpen((prev) => !prev)}
|
||||
onNavigate={movePage}
|
||||
decreaseFontSize={decreaseFontSize}
|
||||
increaseFontSize={increaseFontSize}
|
||||
/>
|
||||
}
|
||||
sidebar={
|
||||
!isMain ? (
|
||||
<AppSidebar
|
||||
isProjectMenu={isProjectMenu}
|
||||
sideMenus={sideMenus}
|
||||
isOpen={menuOpen}
|
||||
pathname={pathname}
|
||||
openMenus={openMenus}
|
||||
onOpenMenusChange={setOpenMenus}
|
||||
onNavigate={movePage}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</KriMainLayout>
|
||||
);
|
||||
}
|
||||
10
src/components/app-shell/AppPageTitle.tsx
Normal file
10
src/components/app-shell/AppPageTitle.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { KriPageTitle } from "@/components/layout/KriPageTitle";
|
||||
|
||||
interface AppPageTitleProps {
|
||||
titleText: string;
|
||||
}
|
||||
|
||||
export default function AppPageTitle({ titleText }: AppPageTitleProps) {
|
||||
return <KriPageTitle title={titleText} />;
|
||||
}
|
||||
|
||||
50
src/components/app-shell/AppSidebar.tsx
Normal file
50
src/components/app-shell/AppSidebar.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import { KriSidebar } from "@/components/layout/KriSidebar";
|
||||
import { AppSidebarProjectSearch } from "@/components/app-shell/AppSidebarProjectSearch";
|
||||
import type { SideMenuItem } from "@/config/menu.types";
|
||||
|
||||
interface AppSidebarProps {
|
||||
isProjectMenu: boolean;
|
||||
sideMenus: SideMenuItem[];
|
||||
isOpen: boolean;
|
||||
pathname: string;
|
||||
openMenus: Record<string, boolean>;
|
||||
onOpenMenusChange: (openMenus: Record<string, boolean>) => void;
|
||||
onNavigate: (path: string) => void;
|
||||
}
|
||||
|
||||
export function AppSidebar({
|
||||
isProjectMenu,
|
||||
sideMenus,
|
||||
isOpen,
|
||||
pathname,
|
||||
openMenus,
|
||||
onOpenMenusChange,
|
||||
onNavigate,
|
||||
}: AppSidebarProps) {
|
||||
const openItemIds = Object.entries(openMenus)
|
||||
.filter(([, open]) => open)
|
||||
.map(([id]) => id);
|
||||
|
||||
return (
|
||||
<KriSidebar
|
||||
items={sideMenus}
|
||||
isOpen={isOpen}
|
||||
pathname={pathname}
|
||||
header={isProjectMenu ? <AppSidebarProjectSearch /> : null}
|
||||
openItemIds={openItemIds}
|
||||
onOpenItemIdsChange={(ids) => {
|
||||
onOpenMenusChange(
|
||||
sideMenus.reduce<Record<string, boolean>>((acc, item) => {
|
||||
acc[item.id] = ids.includes(item.id);
|
||||
return acc;
|
||||
}, {}),
|
||||
);
|
||||
}}
|
||||
onNavigate={(path) => onNavigate(path)}
|
||||
className="border-gray-200 bg-white"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,17 +6,20 @@ import {PROJECT_SEARCH_COUNT} from "@/const/projectConst";
|
||||
import {SelectedProject} from "@/store/jotai/project";
|
||||
import {useProjectTopQuery} from "@/query/project";
|
||||
|
||||
export const SidebarProjectSearch = () =>{
|
||||
export const AppSidebarProjectSearch = () =>{
|
||||
const mounted = useMounted();
|
||||
const { selectedProject, setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [searchKeyword, setSearchKeyword] = useState(selectedProject?.prjctCd || "");
|
||||
const [searchKeyword, setSearchKeyword] = useState("");
|
||||
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
|
||||
|
||||
const enabled = mounted && !!selectedProject;
|
||||
const topQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, enabled);
|
||||
|
||||
const projectArray = useMemo(() => topQuery.data ?? [] ,[topQuery.data]);
|
||||
const projectArray = useMemo(() => {
|
||||
const data = topQuery.data ?? [];
|
||||
return selectedProject ? [selectedProject, ...data] : data;
|
||||
}, [topQuery.data, selectedProject]);
|
||||
|
||||
const handleSelectProject = (info: SelectedProject | null) => {
|
||||
if (!info) return;
|
||||
@@ -36,7 +39,6 @@ export const SidebarProjectSearch = () =>{
|
||||
searchMode="inputOnly"
|
||||
onSearchValueChange={setSearchKeyword}
|
||||
placeholder="프로젝트 검색..."
|
||||
spanClassName="text-sm"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
preventDeselect
|
||||
15
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
15
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { KriLoadingOverlay, type KriLoadingOverlayProps } from "@/components/common/KriLoadingOverlay";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export type LoadingOverlayAdapterProps = Omit<KriLoadingOverlayProps, "open"> & {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export function LoadingOverlayAdapter({ force = false, ...props }: LoadingOverlayAdapterProps) {
|
||||
const open = useAtomValue(loadingAtom);
|
||||
|
||||
return <KriLoadingOverlay open={force || open} {...props} />;
|
||||
}
|
||||
6
src/components/app-shell/index.ts
Normal file
6
src/components/app-shell/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export { AppHeader } from "./AppHeader";
|
||||
export { AppSidebar } from "./AppSidebar";
|
||||
export { LoadingOverlayAdapter } from "./LoadingOverlayAdapter";
|
||||
export { default as AppMainLayout } from "./AppMainLayout";
|
||||
export { default as AppPageTitle } from "./AppPageTitle";
|
||||
|
||||
101
src/components/assign/AssignTargetList.tsx
Normal file
101
src/components/assign/AssignTargetList.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { useCmpnListQuery } from '@/query/cmpn'
|
||||
import { useFieldworkUsersQuery } from '@/query/user'
|
||||
import { useAssignedCmpnIdsQuery, useAssignedFieldworkIdsQuery } from '@/query/project'
|
||||
import { ListHeaderAssignConst } from '@/const/listConst'
|
||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
||||
import type { ListHeaderAssignType } from '@/types/list'
|
||||
|
||||
export type AssignTargetListProps = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
assignType: ListHeaderAssignType
|
||||
selectedId?: string
|
||||
onSelect: (id: string) => void
|
||||
}
|
||||
|
||||
export type AssignTargetRow = {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type UseAssignTargetRowsArgs = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
assignType: ListHeaderAssignType
|
||||
}
|
||||
|
||||
export function useAssignTargetRows({ prjctIdx, enabled, assignType }: UseAssignTargetRowsArgs): AssignTargetRow[] {
|
||||
const isOutsource = assignType === ListHeaderAssignConst.OUTSOURCE
|
||||
|
||||
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled && isOutsource)
|
||||
const cmpnListQuery = useCmpnListQuery()
|
||||
|
||||
const assignedFieldworkIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled && !isOutsource)
|
||||
const fieldworkUsersQuery = useFieldworkUsersQuery(enabled && !isOutsource)
|
||||
|
||||
return useMemo<AssignTargetRow[]>(() => {
|
||||
if (isOutsource) {
|
||||
const assignedIds = new Set(assignedCmpnIdsQuery.data ?? [])
|
||||
return (cmpnListQuery.data ?? [])
|
||||
.filter((cmpn) => assignedIds.has(cmpn.cmpnId))
|
||||
.map((cmpn) => ({ id: cmpn.cmpnId, name: cmpn.cmpnAlias || cmpn.cmpnId }))
|
||||
}
|
||||
|
||||
const targetRole =
|
||||
assignType === ListHeaderAssignConst.CONTACT_INTERVIEWER ? CONTACT_INTERVIEWER_ROLE : FIELD_INTERVIEWER_ROLE
|
||||
const assignedIds = new Set(assignedFieldworkIdsQuery.data ?? [])
|
||||
|
||||
return (fieldworkUsersQuery.data ?? [])
|
||||
.filter((user) => assignedIds.has(user.userId) && user.userRole === targetRole)
|
||||
.map((user) => ({ id: user.userId, name: user.userName }))
|
||||
}, [
|
||||
assignType,
|
||||
isOutsource,
|
||||
assignedCmpnIdsQuery.data,
|
||||
cmpnListQuery.data,
|
||||
assignedFieldworkIdsQuery.data,
|
||||
fieldworkUsersQuery.data,
|
||||
])
|
||||
}
|
||||
|
||||
export function AssignTargetList({ prjctIdx, enabled, assignType, selectedId, onSelect }: AssignTargetListProps) {
|
||||
const rows = useAssignTargetRows({ prjctIdx, enabled, assignType })
|
||||
|
||||
return (
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="h-[78vh] overflow-y-auto">
|
||||
<table className="w-full table-fixed">
|
||||
<colgroup>
|
||||
<col className="w-28" />
|
||||
<col />
|
||||
</colgroup>
|
||||
<thead className="bg-primary text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-2 text-left text-base font-medium">ID</th>
|
||||
<th className="p-2 text-left text-base font-medium">이름</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
selectedId === row.id ? 'bg-accent' : ''
|
||||
}`}
|
||||
onClick={() => onSelect(row.id)}
|
||||
>
|
||||
<td className="p-2 text-base truncate">{row.id}</td>
|
||||
<td className="p-2 text-base truncate">{row.name}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AssignTargetList
|
||||
147
src/components/chart/BaseEChart.tsx
Normal file
147
src/components/chart/BaseEChart.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { ComponentType, CSSProperties } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { CHART_HEIGHTS } from './chart.config'
|
||||
import { useResizeKey } from './useResizeKey'
|
||||
|
||||
type EChartsSeries = NonNullable<EChartsOption['series']>
|
||||
type ReactEChartsProps = {
|
||||
option: EChartsOption
|
||||
className?: string
|
||||
style?: CSSProperties
|
||||
notMerge?: boolean
|
||||
lazyUpdate?: boolean
|
||||
onEvents?: Record<string, (params: unknown) => void>
|
||||
}
|
||||
|
||||
export type BaseEChartProps = {
|
||||
option: EChartsOption
|
||||
height?: number | string
|
||||
className?: string
|
||||
contentClassName?: string
|
||||
chartClassName?: string
|
||||
style?: CSSProperties
|
||||
contentStyle?: CSSProperties
|
||||
chartStyle?: CSSProperties
|
||||
notMerge?: boolean
|
||||
lazyUpdate?: boolean
|
||||
onEvents?: Record<string, (params: unknown) => void>
|
||||
resizeDebounceMs?: number
|
||||
normalizeValues?: boolean
|
||||
decimalPlaces?: number
|
||||
}
|
||||
|
||||
const roundNumber = (value: number, decimalPlaces: number) => {
|
||||
const factor = 10 ** decimalPlaces
|
||||
return Math.round((value + Number.EPSILON) * factor) / factor
|
||||
}
|
||||
|
||||
const normalizeDataValue = (value: unknown, decimalPlaces: number): unknown => {
|
||||
if (typeof value === 'number') {
|
||||
return roundNumber(value, decimalPlaces)
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => normalizeDataValue(item, decimalPlaces))
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object' && 'value' in value) {
|
||||
const dataItem = value as Record<string, unknown>
|
||||
|
||||
return {
|
||||
...dataItem,
|
||||
value: normalizeDataValue(dataItem.value, decimalPlaces),
|
||||
}
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const normalizeSeries = (
|
||||
series: EChartsOption['series'] | undefined,
|
||||
decimalPlaces: number,
|
||||
): EChartsOption['series'] => {
|
||||
if (!series) return series
|
||||
|
||||
const normalizeOne = (seriesOption: EChartsSeries): EChartsSeries => {
|
||||
const candidate = seriesOption as Record<string, unknown>
|
||||
const data = candidate.data
|
||||
|
||||
if (!Array.isArray(data)) {
|
||||
return seriesOption
|
||||
}
|
||||
|
||||
return {
|
||||
...candidate,
|
||||
data: data.map((value) => normalizeDataValue(value, decimalPlaces)),
|
||||
} as EChartsSeries
|
||||
}
|
||||
|
||||
return (Array.isArray(series) ? series.map((item) => normalizeOne(item as EChartsSeries)) : normalizeOne(series)) as EChartsOption['series']
|
||||
}
|
||||
|
||||
export function BaseEChart({
|
||||
option,
|
||||
height = CHART_HEIGHTS.DEFAULT,
|
||||
className,
|
||||
contentClassName,
|
||||
chartClassName,
|
||||
style,
|
||||
contentStyle,
|
||||
chartStyle,
|
||||
notMerge = true,
|
||||
lazyUpdate = false,
|
||||
onEvents,
|
||||
resizeDebounceMs = 150,
|
||||
normalizeValues = true,
|
||||
decimalPlaces = 2,
|
||||
}: BaseEChartProps) {
|
||||
const resizeKey = useResizeKey(resizeDebounceMs)
|
||||
const [ReactECharts, setReactECharts] = useState<ComponentType<ReactEChartsProps> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
void import('echarts-for-react').then((module) => {
|
||||
if (!cancelled) {
|
||||
setReactECharts(() => module.default as ComponentType<ReactEChartsProps>)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const normalizedOption = useMemo<EChartsOption>(() => {
|
||||
if (!normalizeValues) return option
|
||||
|
||||
return {
|
||||
...option,
|
||||
series: normalizeSeries(option.series, decimalPlaces),
|
||||
}
|
||||
}, [decimalPlaces, normalizeValues, option])
|
||||
|
||||
return (
|
||||
<div className={className} style={{ display: 'flex', flexDirection: 'column', height, ...style }}>
|
||||
<div className={contentClassName} style={{ flex: 1, minHeight: 0, ...contentStyle }}>
|
||||
{ReactECharts ? (
|
||||
<ReactECharts
|
||||
key={resizeKey}
|
||||
option={normalizedOption}
|
||||
className={chartClassName}
|
||||
style={{ width: '100%', height: '100%', ...chartStyle }}
|
||||
notMerge={notMerge}
|
||||
lazyUpdate={lazyUpdate}
|
||||
onEvents={onEvents}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default BaseEChart
|
||||
59
src/components/chart/KriBarChart.tsx
Normal file
59
src/components/chart/KriBarChart.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriBarChartProps = KriCartesianChartProps & {
|
||||
isHorizontal?: boolean
|
||||
barWidth?: number | string
|
||||
barMaxWidth?: number | string
|
||||
}
|
||||
|
||||
export function KriBarChart({
|
||||
categories,
|
||||
series,
|
||||
isHorizontal = false,
|
||||
barWidth,
|
||||
barMaxWidth,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriBarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const categoryAxis = { type: 'category', data: categories }
|
||||
const valueAxis = { type: 'value' }
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'bar',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
...(barWidth ? { barWidth } : {}),
|
||||
...(barMaxWidth ? { barMaxWidth } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriBarChart
|
||||
|
||||
58
src/components/chart/KriLineChart.tsx
Normal file
58
src/components/chart/KriLineChart.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriLineChartProps = KriCartesianChartProps & {
|
||||
smooth?: boolean
|
||||
area?: boolean
|
||||
showSymbol?: boolean
|
||||
}
|
||||
|
||||
export function KriLineChart({
|
||||
categories,
|
||||
series,
|
||||
smooth = false,
|
||||
area = false,
|
||||
showSymbol = true,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriLineChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption({ type: 'category', data: categories, boundaryGap: false }, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'line',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
smooth,
|
||||
showSymbol,
|
||||
...(area ? { areaStyle: {} } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [area, categories, grid, legend, option, series, showSymbol, smooth, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriLineChart
|
||||
|
||||
50
src/components/chart/KriPieChart.tsx
Normal file
50
src/components/chart/KriPieChart.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriPieChartSeries } from './chart.types'
|
||||
import { defaultLegend, mergeChartOptions } from './chart.utils'
|
||||
|
||||
export type KriPieChartProps = KriChartBaseProps & {
|
||||
series: KriPieChartSeries[]
|
||||
}
|
||||
|
||||
const getPieCenter = (index: number, count: number) => {
|
||||
if (count === 1) return ['50%', '55%']
|
||||
|
||||
return [`${((index + 0.5) / count) * 100}%`, '55%']
|
||||
}
|
||||
|
||||
export function KriPieChart({
|
||||
series,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriPieChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
series: series.map((item, index) => ({
|
||||
type: 'pie',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
radius: item.radius ?? (series.length > 1 ? ['32%', '52%'] : '65%'),
|
||||
center: item.center ?? getPieCenter(index, series.length),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [legend, option, series, title, tooltip])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriPieChart
|
||||
|
||||
55
src/components/chart/KriRadarChart.tsx
Normal file
55
src/components/chart/KriRadarChart.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriRadarChartSeries, KriRadarDataItem, KriRadarIndicator } from './chart.types'
|
||||
import { defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriRadarChartProps = KriChartBaseProps & {
|
||||
indicators: KriRadarIndicator[]
|
||||
series: KriRadarChartSeries[]
|
||||
radar?: EChartsOption['radar']
|
||||
}
|
||||
|
||||
const normalizeRadarData = (series: KriRadarChartSeries): KriRadarDataItem[] => {
|
||||
if (series.data.every((value) => typeof value === 'number')) {
|
||||
return [{ name: series.name, value: series.data as number[] }]
|
||||
}
|
||||
|
||||
return series.data as KriRadarDataItem[]
|
||||
}
|
||||
|
||||
export function KriRadarChart({
|
||||
indicators,
|
||||
series,
|
||||
radar,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriRadarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
radar: mergeObjectOption({ indicator: indicators }, radar) as EChartsOption['radar'],
|
||||
series: series.map((item) => ({
|
||||
type: 'radar',
|
||||
name: item.name,
|
||||
data: normalizeRadarData(item),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [indicators, legend, option, radar, series, title, tooltip])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriRadarChart
|
||||
|
||||
55
src/components/chart/KriScatterChart.tsx
Normal file
55
src/components/chart/KriScatterChart.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriChartBaseProps, KriScatterChartSeries } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriScatterChartProps = KriChartBaseProps & {
|
||||
series: KriScatterChartSeries[]
|
||||
grid?: EChartsOption['grid']
|
||||
xAxis?: EChartsOption['xAxis']
|
||||
yAxis?: EChartsOption['yAxis']
|
||||
symbolSize?: number | ((value: unknown, params: unknown) => number)
|
||||
}
|
||||
|
||||
export function KriScatterChart({
|
||||
series,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
symbolSize,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriScatterChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'item' },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption({ type: 'value' }, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption({ type: 'value' }, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'scatter',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
...(symbolSize ? { symbolSize } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [grid, legend, option, series, symbolSize, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriScatterChart
|
||||
|
||||
62
src/components/chart/KriStackedBarChart.tsx
Normal file
62
src/components/chart/KriStackedBarChart.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { BaseEChart } from './BaseEChart'
|
||||
import type { KriCartesianChartProps } from './chart.types'
|
||||
import { defaultGrid, defaultLegend, mergeChartOptions, mergeObjectOption } from './chart.utils'
|
||||
|
||||
export type KriStackedBarChartProps = KriCartesianChartProps & {
|
||||
isHorizontal?: boolean
|
||||
stackName?: string
|
||||
barWidth?: number | string
|
||||
barMaxWidth?: number | string
|
||||
}
|
||||
|
||||
export function KriStackedBarChart({
|
||||
categories,
|
||||
series,
|
||||
isHorizontal = false,
|
||||
stackName = 'total',
|
||||
barWidth,
|
||||
barMaxWidth,
|
||||
title,
|
||||
legend,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
option,
|
||||
...baseChartProps
|
||||
}: KriStackedBarChartProps) {
|
||||
const chartOption = useMemo<EChartsOption>(() => {
|
||||
const categoryAxis = { type: 'category', data: categories }
|
||||
const valueAxis = { type: 'value' }
|
||||
const generated: EChartsOption = {
|
||||
title,
|
||||
tooltip: tooltip ?? { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: legend ?? defaultLegend(series.length),
|
||||
grid: grid ?? defaultGrid(series.length),
|
||||
xAxis: mergeObjectOption(isHorizontal ? valueAxis : categoryAxis, xAxis) as EChartsOption['xAxis'],
|
||||
yAxis: mergeObjectOption(isHorizontal ? categoryAxis : valueAxis, yAxis) as EChartsOption['yAxis'],
|
||||
series: series.map((item) => ({
|
||||
type: 'bar',
|
||||
name: item.name,
|
||||
data: item.data,
|
||||
stack: item.stack ?? stackName,
|
||||
...(barWidth ? { barWidth } : {}),
|
||||
...(barMaxWidth ? { barMaxWidth } : {}),
|
||||
...(item.color ? { color: item.color } : {}),
|
||||
...item.option,
|
||||
})) as EChartsOption['series'],
|
||||
}
|
||||
|
||||
return mergeChartOptions(generated, option)
|
||||
}, [barMaxWidth, barWidth, categories, grid, isHorizontal, legend, option, series, stackName, title, tooltip, xAxis, yAxis])
|
||||
|
||||
return <BaseEChart option={chartOption} {...baseChartProps} />
|
||||
}
|
||||
|
||||
export default KriStackedBarChart
|
||||
|
||||
6
src/components/chart/chart.config.ts
Normal file
6
src/components/chart/chart.config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export const CHART_HEIGHTS = {
|
||||
DEFAULT: 320,
|
||||
SMALL: 240,
|
||||
LARGE: 420,
|
||||
} as const
|
||||
|
||||
71
src/components/chart/chart.types.ts
Normal file
71
src/components/chart/chart.types.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import type { BaseEChartProps } from './BaseEChart'
|
||||
|
||||
export type KriChartBaseProps = Omit<BaseEChartProps, 'option'> & {
|
||||
option?: EChartsOption
|
||||
title?: EChartsOption['title']
|
||||
legend?: EChartsOption['legend']
|
||||
tooltip?: EChartsOption['tooltip']
|
||||
}
|
||||
|
||||
export type KriCategoryValue = string | number
|
||||
|
||||
export type KriCategoryChartSeries = {
|
||||
name: string
|
||||
data: unknown[]
|
||||
color?: string
|
||||
stack?: string
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriCartesianChartProps = KriChartBaseProps & {
|
||||
categories: KriCategoryValue[]
|
||||
series: KriCategoryChartSeries[]
|
||||
grid?: EChartsOption['grid']
|
||||
xAxis?: EChartsOption['xAxis']
|
||||
yAxis?: EChartsOption['yAxis']
|
||||
}
|
||||
|
||||
export type KriNamedChartData = {
|
||||
name: string
|
||||
value: unknown
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type KriPieChartSeries = {
|
||||
name?: string
|
||||
data: KriNamedChartData[]
|
||||
radius?: string | number | Array<string | number>
|
||||
center?: Array<string | number>
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriRadarIndicator = {
|
||||
name: string
|
||||
max?: number
|
||||
min?: number
|
||||
color?: string
|
||||
}
|
||||
|
||||
export type KriRadarDataItem = {
|
||||
name?: string
|
||||
value: number[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type KriRadarChartSeries = {
|
||||
name: string
|
||||
data: number[] | KriRadarDataItem[]
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type KriScatterDataItem = [number, number] | [string, number] | KriNamedChartData
|
||||
|
||||
export type KriScatterChartSeries = {
|
||||
name: string
|
||||
data: KriScatterDataItem[]
|
||||
color?: string
|
||||
option?: Record<string, unknown>
|
||||
}
|
||||
|
||||
34
src/components/chart/chart.utils.ts
Normal file
34
src/components/chart/chart.utils.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
export const mergeChartOptions = (generated: EChartsOption, option?: EChartsOption): EChartsOption => {
|
||||
if (!option) return generated
|
||||
|
||||
return {
|
||||
...generated,
|
||||
...option,
|
||||
series: option.series ?? generated.series,
|
||||
}
|
||||
}
|
||||
|
||||
export const mergeObjectOption = <TOption>(defaults: Record<string, unknown>, option?: TOption): TOption | Record<string, unknown> => {
|
||||
if (!option) return defaults
|
||||
if (Array.isArray(option)) return option
|
||||
if (typeof option === 'object') return { ...defaults, ...(option as Record<string, unknown>) }
|
||||
|
||||
return option
|
||||
}
|
||||
|
||||
export const defaultLegend = (seriesCount: number): EChartsOption['legend'] | undefined => {
|
||||
return seriesCount > 1 ? { top: 0 } : undefined
|
||||
}
|
||||
|
||||
export const defaultGrid = (seriesCount: number): EChartsOption['grid'] => {
|
||||
return {
|
||||
top: seriesCount > 1 ? 44 : 24,
|
||||
right: 24,
|
||||
bottom: 24,
|
||||
left: 24,
|
||||
containLabel: true,
|
||||
}
|
||||
}
|
||||
|
||||
29
src/components/chart/index.ts
Normal file
29
src/components/chart/index.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export { BaseEChart, default } from './BaseEChart'
|
||||
export type { BaseEChartProps } from './BaseEChart'
|
||||
export { KriBarChart } from './KriBarChart'
|
||||
export type { KriBarChartProps } from './KriBarChart'
|
||||
export { KriLineChart } from './KriLineChart'
|
||||
export type { KriLineChartProps } from './KriLineChart'
|
||||
export { KriPieChart } from './KriPieChart'
|
||||
export type { KriPieChartProps } from './KriPieChart'
|
||||
export { KriRadarChart } from './KriRadarChart'
|
||||
export type { KriRadarChartProps } from './KriRadarChart'
|
||||
export { KriScatterChart } from './KriScatterChart'
|
||||
export type { KriScatterChartProps } from './KriScatterChart'
|
||||
export { KriStackedBarChart } from './KriStackedBarChart'
|
||||
export type { KriStackedBarChartProps } from './KriStackedBarChart'
|
||||
export { CHART_HEIGHTS } from './chart.config'
|
||||
export type {
|
||||
KriCartesianChartProps,
|
||||
KriCategoryChartSeries,
|
||||
KriCategoryValue,
|
||||
KriChartBaseProps,
|
||||
KriNamedChartData,
|
||||
KriPieChartSeries,
|
||||
KriRadarChartSeries,
|
||||
KriRadarDataItem,
|
||||
KriRadarIndicator,
|
||||
KriScatterChartSeries,
|
||||
KriScatterDataItem,
|
||||
} from './chart.types'
|
||||
export { useResizeKey } from './useResizeKey'
|
||||
31
src/components/chart/useResizeKey.ts
Normal file
31
src/components/chart/useResizeKey.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export function useResizeKey(delay = 150) {
|
||||
const [resizeKey, setResizeKey] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return
|
||||
|
||||
let timer: ReturnType<typeof window.setTimeout> | undefined
|
||||
|
||||
const handleResize = () => {
|
||||
if (timer) window.clearTimeout(timer)
|
||||
|
||||
timer = window.setTimeout(() => {
|
||||
setResizeKey((key) => key + 1)
|
||||
}, delay)
|
||||
}
|
||||
|
||||
window.addEventListener('resize', handleResize)
|
||||
|
||||
return () => {
|
||||
if (timer) window.clearTimeout(timer)
|
||||
window.removeEventListener('resize', handleResize)
|
||||
}
|
||||
}, [delay])
|
||||
|
||||
return resizeKey
|
||||
}
|
||||
|
||||
@@ -2,15 +2,17 @@
|
||||
|
||||
import * as React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {MultiSelect, MultiSelectRef} from '@/components/ui/multi-select'
|
||||
import type { MultiSelectOption } from '@/components/ui/multi-select'
|
||||
import { MultiSelect } from '@/components/common/multi-select'
|
||||
import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
||||
|
||||
type BaseProps<T> = {
|
||||
export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
||||
|
||||
export interface KriAutoCompleteBaseProps<T> {
|
||||
items: T[]
|
||||
searchable?: boolean
|
||||
searchMode?: "filter" | "inputOnly";
|
||||
defaultSearchValue?: string;
|
||||
onSearchValueChange?: (value: string) => void;
|
||||
searchMode?: 'filter' | 'inputOnly'
|
||||
defaultSearchValue?: string
|
||||
onSearchValueChange?: (value: string) => void
|
||||
placeholder?: string
|
||||
widthClassName?: string
|
||||
heightClassName?: string
|
||||
@@ -19,219 +21,185 @@ type BaseProps<T> = {
|
||||
className?: string
|
||||
getValue?: (item: T) => string
|
||||
getLabel?: (item: T) => string
|
||||
|
||||
/** ✅ 옵션: 원본 item을 option.info에 실어둘지 */
|
||||
withInfo?: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
type KriMultiSelectProps<T = unknown> = BaseProps<T> & {
|
||||
export interface KriMultiSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
||||
value: string[]
|
||||
onChange: (value: string[]) => void
|
||||
maxCount?: number
|
||||
maxSelected?: number
|
||||
hideSelectAll?: boolean
|
||||
|
||||
/** ✅ withInfo=true일 때만 의미 있게 쓰면 됨 */
|
||||
onItemsChange?: (items: T[]) => void
|
||||
onOptionsChange?: (options: MultiSelectOption<T>[]) => void
|
||||
}
|
||||
|
||||
function toOptions<T>(
|
||||
items: T[],
|
||||
getValue: ((item: T) => string) | undefined,
|
||||
getLabel: ((item: T) => string) | undefined,
|
||||
withInfo: boolean,
|
||||
): MultiSelectOption<T>[] {
|
||||
return items.map((item) => ({
|
||||
value: getValue ? getValue(item) : String(item),
|
||||
label: getLabel ? getLabel(item) : String(item),
|
||||
...(withInfo ? { info: item } : {}),
|
||||
}))
|
||||
}
|
||||
|
||||
export function KriMultiSelect<T = unknown>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = "filter",
|
||||
defaultSearchValue = "",
|
||||
onSearchValueChange,
|
||||
maxCount = 1,
|
||||
maxSelected,
|
||||
hideSelectAll = false,
|
||||
placeholder = 'Select options',
|
||||
widthClassName,
|
||||
heightClassName,
|
||||
spanClassName = "text-lg",
|
||||
badgeClassName = "text-lg",
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemsChange,
|
||||
onOptionsChange,
|
||||
}: KriMultiSelectProps<T>) {
|
||||
const msRef = React.useRef<MultiSelectRef>(null);
|
||||
|
||||
const extractValue = React.useCallback(
|
||||
(item: T) => (getValue ? getValue(item) : String(item)),
|
||||
[getValue]
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
maxCount = 1,
|
||||
maxSelected,
|
||||
hideSelectAll = false,
|
||||
placeholder = 'Select options',
|
||||
widthClassName,
|
||||
heightClassName,
|
||||
spanClassName = 'text-base',
|
||||
badgeClassName = 'text-base',
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemsChange,
|
||||
onOptionsChange,
|
||||
disabled,
|
||||
}: KriMultiSelectProps<T>) {
|
||||
const options = React.useMemo(
|
||||
() => toOptions(items, getValue, getLabel, withInfo),
|
||||
[getLabel, getValue, items, withInfo],
|
||||
)
|
||||
const extractLabel = React.useCallback(
|
||||
(item: T) => (getLabel ? getLabel(item) : String(item)),
|
||||
[getLabel]
|
||||
)
|
||||
|
||||
const options = React.useMemo<MultiSelectOption<T>[]>(() => {
|
||||
return items.map((item) => ({
|
||||
value: extractValue(item),
|
||||
label: extractLabel(item),
|
||||
...(withInfo ? { info: item } : {}), // ✅ 필요할 때만 info를 실음
|
||||
}))
|
||||
}, [items, extractValue, extractLabel, withInfo])
|
||||
|
||||
return (
|
||||
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
|
||||
<MultiSelect<T>
|
||||
ref={msRef}
|
||||
options={options}
|
||||
defaultValue={value}
|
||||
onValueChange={onChange}
|
||||
onOptionChange={onOptionsChange}
|
||||
onInfoChange={onItemsChange}
|
||||
maxSelected={maxSelected}
|
||||
placeholder={placeholder}
|
||||
className={cn("bg-white text-lg", className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
maxCount={maxCount}
|
||||
hideSelectAll={hideSelectAll}
|
||||
autoSize
|
||||
singleLine
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
options={options}
|
||||
defaultValue={value}
|
||||
onValueChange={onChange}
|
||||
onOptionChange={onOptionsChange}
|
||||
onInfoChange={onItemsChange}
|
||||
maxSelected={maxSelected}
|
||||
placeholder={placeholder}
|
||||
className={cn('bg-background text-base', !widthClassName && 'w-auto', className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
maxCount={maxCount}
|
||||
hideSelectAll={hideSelectAll}
|
||||
singleLine
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type KriSingleSelectProps<T = unknown> = BaseProps<T> & {
|
||||
export interface KriSingleSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onItemChange?: (item: T | null) => void
|
||||
onOptionChange?: (option: MultiSelectOption<T> | null) => void
|
||||
preventDeselect?: boolean;
|
||||
hideOptionCheck?: boolean;
|
||||
|
||||
preventDeselect?: boolean
|
||||
hideOptionCheck?: boolean
|
||||
useClear?: boolean
|
||||
clearLabel?: string
|
||||
clearValue?: string
|
||||
|
||||
showSelectedTooltip?: boolean
|
||||
}
|
||||
|
||||
export function KriSingleSelect<T = unknown>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = "filter",
|
||||
defaultSearchValue = "",
|
||||
onSearchValueChange,
|
||||
placeholder = 'Select an option',
|
||||
heightClassName,
|
||||
widthClassName,
|
||||
spanClassName = "text-lg",
|
||||
badgeClassName = "text-lg",
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemChange,
|
||||
onOptionChange,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
showSelectedTooltip = false,
|
||||
useClear = false,
|
||||
clearLabel = "선택 해제",
|
||||
clearValue = "__CLEAR__",
|
||||
}: KriSingleSelectProps<T>) {
|
||||
const msRef = React.useRef<MultiSelectRef>(null);
|
||||
|
||||
const extractValue = React.useCallback(
|
||||
(item: T) => (getValue ? getValue(item) : String(item)),
|
||||
[getValue]
|
||||
)
|
||||
const extractLabel = React.useCallback(
|
||||
(item: T) => (getLabel ? getLabel(item) : String(item)),
|
||||
[getLabel]
|
||||
)
|
||||
|
||||
const options = React.useMemo<MultiSelectOption<T>[]>(() => {
|
||||
const special: MultiSelectOption<T>[] = [];
|
||||
|
||||
if (useClear) special.push({ value: clearValue, label: clearLabel });
|
||||
|
||||
const normal = items.map((item) => ({
|
||||
value: extractValue(item),
|
||||
label: extractLabel(item),
|
||||
...(withInfo ? { info: item } : {}),
|
||||
}));
|
||||
|
||||
return [...special, ...normal]
|
||||
}, [items, extractValue, extractLabel, withInfo, useClear, clearLabel, clearValue])
|
||||
|
||||
const defaultValue = React.useMemo(() => (value ? [value] : []), [value])
|
||||
|
||||
const tooltipText = React.useMemo(() => {
|
||||
if (!showSelectedTooltip) return undefined;
|
||||
if (!value || !value) return undefined;
|
||||
if (useClear && value === clearValue) return undefined;
|
||||
|
||||
const label = options.find(o => o.value === value)?.label;
|
||||
return label ?? value; // options에 없으면 value라도 표시
|
||||
}, [showSelectedTooltip, value, options, useClear, clearValue]);
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
placeholder = 'Select an option',
|
||||
heightClassName,
|
||||
widthClassName,
|
||||
spanClassName = 'text-base',
|
||||
badgeClassName = 'text-base',
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
withInfo = false,
|
||||
onItemChange,
|
||||
onOptionChange,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
showSelectedTooltip = false,
|
||||
useClear = false,
|
||||
clearLabel = '선택 해제',
|
||||
clearValue = '__CLEAR__',
|
||||
disabled,
|
||||
}: KriSingleSelectProps<T>) {
|
||||
const ref = React.useRef<MultiSelectRef>(null)
|
||||
const options = React.useMemo(() => {
|
||||
const normal = toOptions(items, getValue, getLabel, withInfo)
|
||||
return useClear ? [{ value: clearValue, label: clearLabel }, ...normal] : normal
|
||||
}, [clearLabel, clearValue, getLabel, getValue, items, useClear, withInfo])
|
||||
const selectedLabel = options.find((option) => option.value === value)?.label
|
||||
|
||||
return (
|
||||
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
|
||||
<MultiSelect<T>
|
||||
ref={msRef}
|
||||
options={options}
|
||||
defaultValue={defaultValue}
|
||||
onValueChange={(next) => {
|
||||
const v = next[0] ?? ""
|
||||
|
||||
if (v === clearValue) {
|
||||
msRef.current?.clear();
|
||||
|
||||
onChange("")
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
onChange(v)
|
||||
}}
|
||||
onOptionChange={(opts) => {
|
||||
const opt = opts[0] ?? null
|
||||
const item = withInfo ? ((opt as any)?.info ?? null) : null
|
||||
|
||||
onOptionChange?.(opt)
|
||||
onItemChange?.(item)
|
||||
}}
|
||||
selectionMode="single"
|
||||
maxCount={1}
|
||||
maxSelected={1}
|
||||
placeholder={placeholder}
|
||||
className={cn("bg-white text-lg", className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
preventDeselect={preventDeselect}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
hideSelectAll
|
||||
autoSize
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
ref={ref}
|
||||
options={options}
|
||||
defaultValue={value ? [value] : []}
|
||||
onValueChange={(next) => {
|
||||
const selected = next[0] ?? ''
|
||||
if (selected === clearValue) {
|
||||
ref.current?.clear()
|
||||
onChange('')
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
return
|
||||
}
|
||||
onChange(selected)
|
||||
}}
|
||||
onOptionChange={(next) => {
|
||||
const option = next[0] ?? null
|
||||
if (option?.value === clearValue) {
|
||||
onOptionChange?.(null)
|
||||
onItemChange?.(null)
|
||||
return
|
||||
}
|
||||
onOptionChange?.(option)
|
||||
onItemChange?.(option?.info ?? null)
|
||||
}}
|
||||
selectionMode="single"
|
||||
maxCount={1}
|
||||
maxSelected={1}
|
||||
placeholder={placeholder}
|
||||
className={cn('bg-background text-base', !widthClassName && 'w-auto', className)}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
defaultSearchValue={defaultSearchValue}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
preventDeselect={preventDeselect}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
hideSelectAll
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
82
src/components/common/KriDatePicker.tsx
Normal file
82
src/components/common/KriDatePicker.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import {CalendarIcon, X} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Calendar} from "@/components/ui/calendar";
|
||||
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
|
||||
import {cn} from "@/lib/utils";
|
||||
|
||||
const parseDate = (value: string) => {
|
||||
if (!value) return undefined
|
||||
|
||||
const [year, month, day] = value.split('-').map(Number)
|
||||
if (!year || !month || !day) return undefined
|
||||
|
||||
const date = new Date(year, month - 1, day)
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return date
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | undefined) => {
|
||||
if (!date) return ''
|
||||
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
export function KriDatePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "날짜 선택",
|
||||
className,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const selected = parseDate(value);
|
||||
|
||||
return (
|
||||
<div className={cn("relative", className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={cn("h-9 w-full justify-start bg-white pr-8 text-left font-normal", !value && "text-muted-foreground")}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4" />
|
||||
{selected ? formatDate(selected) : placeholder}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={selected}
|
||||
onSelect={(date) => onChange(date ? formatDate(date) : "")}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{value && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onChange("");
|
||||
}}
|
||||
aria-label="날짜 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
'use client'
|
||||
|
||||
import { useRef } from 'react'
|
||||
import { CalendarDays, X } from 'lucide-react'
|
||||
import { CalendarIcon, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Calendar } from '@/components/ui/calendar'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -13,7 +11,7 @@ export type KriDateRange = {
|
||||
to: string
|
||||
}
|
||||
|
||||
type KriDateRangePickerProps = {
|
||||
export type KriDateRangePickerProps = {
|
||||
value: KriDateRange
|
||||
onChange: (value: KriDateRange) => void
|
||||
placeholder?: string
|
||||
@@ -23,97 +21,101 @@ type KriDateRangePickerProps = {
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function KriDateRangePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '조회 기간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
}: KriDateRangePickerProps) {
|
||||
const toInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const parseDate = (value: string) => {
|
||||
if (!value) return undefined
|
||||
|
||||
const displayText = value.from && value.to
|
||||
? `${value.from} ~ ${value.to}`
|
||||
: value.from
|
||||
? `${value.from} ~`
|
||||
: value.to
|
||||
? `~ ${value.to}`
|
||||
: placeholder
|
||||
const [year, month, day] = value.split('-').map(Number)
|
||||
if (!year || !month || !day) return undefined
|
||||
|
||||
const hasValue = value.from.length > 0 || value.to.length > 0
|
||||
const invalidRange = value.from.length > 0 && value.to.length > 0 && value.from > value.to
|
||||
|
||||
const focusAndOpenToDate = () => {
|
||||
const input = toInputRef.current
|
||||
if (!input) return
|
||||
|
||||
input.focus()
|
||||
const inputWithPicker = input as HTMLInputElement & { showPicker?: () => void }
|
||||
inputWithPicker.showPicker?.()
|
||||
if (!inputWithPicker.showPicker) {
|
||||
input.click()
|
||||
}
|
||||
const date = new Date(year, month - 1, day)
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return date
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | undefined) => {
|
||||
if (!date) return ''
|
||||
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
export function KriDateRangePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '조회 기간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
}: KriDateRangePickerProps) {
|
||||
const selected = {
|
||||
from: parseDate(value.from),
|
||||
to: parseDate(value.to),
|
||||
}
|
||||
const selectedRange = selected.from || selected.to ? selected : undefined
|
||||
|
||||
const displayText = value.from && value.to
|
||||
? `${value.from} ~ ${value.to}`
|
||||
: value.from
|
||||
? `${value.from} ~`
|
||||
: value.to
|
||||
? `~ ${value.to}`
|
||||
: placeholder
|
||||
|
||||
const hasValue = value.from.length > 0 || value.to.length > 0
|
||||
|
||||
return (
|
||||
<div className={cn('flex items-center gap-2', className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn('justify-start min-w-[260px] font-normal', triggerClassName)}
|
||||
>
|
||||
<CalendarDays className="w-4 h-4" />
|
||||
<span className="truncate">{displayText}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className={cn('w-[360px] space-y-3', contentClassName)}>
|
||||
<Label className="font-semibold">조회 기간</Label>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="date"
|
||||
value={value.from}
|
||||
onChange={(e) => {
|
||||
const nextFrom = e.target.value
|
||||
onChange({ ...value, from: nextFrom })
|
||||
if (nextFrom) {
|
||||
requestAnimationFrame(() => {
|
||||
focusAndOpenToDate()
|
||||
<div className={cn('relative', className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
||||
!hasValue && 'text-muted-foreground',
|
||||
triggerClassName,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4" />
|
||||
<span className="truncate">{displayText}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
||||
<Calendar
|
||||
mode="range"
|
||||
selected={selectedRange}
|
||||
onSelect={(range) => {
|
||||
onChange({
|
||||
from: formatDate(range?.from),
|
||||
to: formatDate(range?.to),
|
||||
})
|
||||
}
|
||||
}}
|
||||
}}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">~</span>
|
||||
<Input
|
||||
ref={toInputRef}
|
||||
type="date"
|
||||
value={value.to}
|
||||
onChange={(e) => onChange({ ...value, to: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{invalidRange && (
|
||||
<p className="text-xs text-red-600">조회 시작일은 종료일보다 이후일 수 없습니다.</p>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => onChange({ from: '', to: '' })}
|
||||
disabled={disabled || !hasValue}
|
||||
aria-label="조회 기간 초기화"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{hasValue && !disabled ? (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onChange({ from: '', to: '' })
|
||||
}}
|
||||
aria-label="조회 기간 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
136
src/components/common/KriDateTimePicker.tsx
Normal file
136
src/components/common/KriDateTimePicker.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { CalendarIcon, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Calendar } from '@/components/ui/calendar'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { KriTimePicker } from '@/components/common/KriTimePicker'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriDateTimePickerProps = {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string
|
||||
className?: string
|
||||
triggerClassName?: string
|
||||
contentClassName?: string
|
||||
disabled?: boolean
|
||||
modalPopover?: boolean
|
||||
}
|
||||
|
||||
const parseDateTime = (value: string): { date: Date | undefined; time: string } => {
|
||||
if (!value) return { date: undefined, time: '' }
|
||||
|
||||
const [datePart, timePart = ''] = value.split('T')
|
||||
const [year, month, day] = datePart.split('-').map(Number)
|
||||
if (!year || !month || !day) return { date: undefined, time: timePart }
|
||||
|
||||
const date = new Date(year, month - 1, day)
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return { date: undefined, time: timePart }
|
||||
}
|
||||
|
||||
return { date, time: timePart }
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | undefined) => {
|
||||
if (!date) return ''
|
||||
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
const toValue = (date: Date | undefined, time: string): string => {
|
||||
const dateText = formatDate(date)
|
||||
if (!dateText) return ''
|
||||
|
||||
return `${dateText}T${time || '00:00'}`
|
||||
}
|
||||
|
||||
const toDisplayText = (date: Date | undefined, time: string, placeholder: string) => {
|
||||
const dateText = formatDate(date)
|
||||
if (!dateText) return placeholder
|
||||
|
||||
return `${dateText} ${time || '00:00'}`
|
||||
}
|
||||
|
||||
export function KriDateTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '날짜/시간 선택',
|
||||
className,
|
||||
triggerClassName,
|
||||
contentClassName,
|
||||
disabled = false,
|
||||
modalPopover = true,
|
||||
}: KriDateTimePickerProps) {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const { date, time } = parseDateTime(value)
|
||||
const hasValue = date !== undefined
|
||||
|
||||
const handleDateSelect = (nextDate: Date | undefined) => {
|
||||
if (!nextDate) return
|
||||
onChange(toValue(nextDate, time || '00:00'))
|
||||
}
|
||||
|
||||
const handleTimeChange = (nextTime: string) => {
|
||||
if (!date) return
|
||||
onChange(toValue(date, nextTime))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)}>
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-9 w-full justify-start bg-white pr-8 text-left font-normal',
|
||||
!hasValue && 'text-muted-foreground',
|
||||
triggerClassName,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
<span className="truncate">{toDisplayText(date, time, placeholder)}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className={cn('w-auto p-0', contentClassName)} align="start">
|
||||
<div className="sm:flex">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={date}
|
||||
onSelect={handleDateSelect}
|
||||
/>
|
||||
<KriTimePicker
|
||||
value={time || '00:00'}
|
||||
onChange={handleTimeChange}
|
||||
disabled={!date}
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{hasValue && !disabled ? (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onChange('')
|
||||
}}
|
||||
aria-label="날짜/시간 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriDateTimePicker
|
||||
76
src/components/common/KriDialog.tsx
Normal file
76
src/components/common/KriDialog.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface KriDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
title: ReactNode
|
||||
description?: ReactNode
|
||||
children?: ReactNode
|
||||
footer?: ReactNode
|
||||
showDefaultFooter?: boolean
|
||||
closeLabel?: string
|
||||
showCloseButton?: boolean
|
||||
contentClassName?: string
|
||||
bodyClassName?: string
|
||||
footerClassName?: string
|
||||
}
|
||||
|
||||
export function KriDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
footer,
|
||||
showDefaultFooter = true,
|
||||
closeLabel = '닫기',
|
||||
showCloseButton = true,
|
||||
contentClassName,
|
||||
bodyClassName,
|
||||
footerClassName,
|
||||
}: KriDialogProps) {
|
||||
const renderFooter = () => {
|
||||
if (footer !== undefined) {
|
||||
if (footer === null) return null
|
||||
return <DialogFooter className={footerClassName}>{footer}</DialogFooter>
|
||||
}
|
||||
|
||||
if (!showDefaultFooter) return null
|
||||
|
||||
return (
|
||||
<DialogFooter className={footerClassName}>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
{closeLabel}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className={contentClassName} showCloseButton={showCloseButton}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
{description ? <DialogDescription>{description}</DialogDescription> : null}
|
||||
</DialogHeader>
|
||||
<div className={cn('min-h-0', bodyClassName)}>{children}</div>
|
||||
{renderFooter()}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
26
src/components/common/KriLoadingOverlay.tsx
Normal file
26
src/components/common/KriLoadingOverlay.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
'use client'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface KriLoadingOverlayProps {
|
||||
open: boolean
|
||||
label?: string
|
||||
className?: string
|
||||
spinnerClassName?: string
|
||||
}
|
||||
|
||||
export function KriLoadingOverlay({ open, label = '로딩 중', className, spinnerClassName }: KriLoadingOverlayProps) {
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label={label}
|
||||
className={cn('fixed inset-0 z-[9999] flex items-center justify-center bg-black/70', className)}
|
||||
>
|
||||
<div className={cn('size-12 animate-spin rounded-full border-4 border-gray-400 border-t-white', spinnerClassName)} />
|
||||
<span className="sr-only">{label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,32 +7,18 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// ✅ 화면에 보여줄 “허용 특수문자”
|
||||
export const ALLOWED_SPECIALS_TEXT =
|
||||
`! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
|
||||
|
||||
// ✅ “허용 문자만” 체크(공백/한글/기타 특수문자 차단)
|
||||
export const ONLY_ALLOWED_REGEX =
|
||||
/^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?\/]+$/
|
||||
|
||||
// ✅ 최종 비밀번호 규칙(특수문자 필수 아님)
|
||||
// - 8~20자
|
||||
// - 영문 1개 이상 + 숫자 1개 이상
|
||||
// - 구성 문자는 허용 문자만
|
||||
export const KRI_PW_REGEX =
|
||||
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?\/]{8,20}$/
|
||||
export const ALLOWED_SPECIALS_TEXT = `! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
|
||||
export const ONLY_ALLOWED_REGEX = /^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]+$/
|
||||
export const KRI_PW_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{8,20}$/
|
||||
|
||||
const requirements = [
|
||||
{ regex: /[A-Za-z]/, text: '영문 1개 이상 (A–Z 또는 a–z)' },
|
||||
{ regex: /\d/, text: '숫자 1개 이상' },
|
||||
{ regex: /^.{10,}$/, text: '10자 이상' },
|
||||
{
|
||||
regex: /[!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]/,
|
||||
text: `특수문자 사용 (허용: ${ALLOWED_SPECIALS_TEXT})`,
|
||||
},
|
||||
{ test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' },
|
||||
{ test: (value: string) => /\d/.test(value), text: '숫자 1개 이상' },
|
||||
{ test: (value: string) => value.length >= 8 && value.length <= 20, text: '8~20자' },
|
||||
{ test: (value: string) => !value || ONLY_ALLOWED_REGEX.test(value), text: '허용 문자만 사용' },
|
||||
]
|
||||
|
||||
type KriPasswordProps = {
|
||||
export interface KriPasswordProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
id?: string
|
||||
@@ -40,156 +26,92 @@ type KriPasswordProps = {
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
showStrength?: boolean
|
||||
}
|
||||
|
||||
const KriPassword = ({
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
label = '비밀번호',
|
||||
placeholder = '비밀번호를 입력하세요',
|
||||
disabled,
|
||||
className,
|
||||
}: KriPasswordProps) => {
|
||||
export function KriPassword({
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
label = '비밀번호',
|
||||
placeholder = '비밀번호를 입력하세요',
|
||||
disabled,
|
||||
className,
|
||||
showStrength = true,
|
||||
}: KriPasswordProps) {
|
||||
const [isVisible, setIsVisible] = useState(false)
|
||||
|
||||
const autoId = useId()
|
||||
const inputId = id ?? autoId
|
||||
const toggleVisibility = () => setIsVisible((prev) => !prev)
|
||||
const isValid = useMemo(() => KRI_PW_REGEX.test(value), [value])
|
||||
const hasOnlyAllowedChars = useMemo(
|
||||
() => (value ? ONLY_ALLOWED_REGEX.test(value) : true),
|
||||
[value]
|
||||
)
|
||||
|
||||
const checks = useMemo(
|
||||
() =>
|
||||
requirements.map((req) => ({
|
||||
met: req.regex.test(value),
|
||||
text: req.text,
|
||||
})),
|
||||
[value]
|
||||
)
|
||||
const hasOnlyAllowedChars = useMemo(() => (value ? ONLY_ALLOWED_REGEX.test(value) : true), [value])
|
||||
const checks = useMemo(() => requirements.map((item) => ({ met: item.test(value), text: item.text })), [value])
|
||||
const score = checks.filter((item) => item.met).length
|
||||
|
||||
const statusText = useMemo(() => {
|
||||
if (!value) return '비밀번호를 입력하세요'
|
||||
if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있어요'
|
||||
return isValid ? '사용 가능한 비밀번호입니다' : '비밀번호 규칙을 만족하지 않아요'
|
||||
}, [value, isValid, hasOnlyAllowedChars])
|
||||
return isValid ? '사용 가능한 비밀번호입니다' : '영문과 숫자를 포함한 8~20자로 입력하세요'
|
||||
}, [hasOnlyAllowedChars, isValid, value])
|
||||
|
||||
const score = useMemo(() => checks.filter((c) => c.met).length, [checks])
|
||||
|
||||
const getBarColor = (s: number) => {
|
||||
if (s === 0) return 'bg-border'
|
||||
if (s === 1) return 'bg-destructive'
|
||||
if (s === 2) return 'bg-orange-500'
|
||||
if (s === 3) return 'bg-yellow-400'
|
||||
return 'bg-green-500' // 4
|
||||
}
|
||||
|
||||
const getStrengthText = (s: number) => {
|
||||
if (s === 0) return '비밀번호를 입력하세요'
|
||||
if (s === 1) return '약함'
|
||||
if (s === 2) return '보통'
|
||||
if (s === 3) return '강함'
|
||||
return '매우 강함'
|
||||
}
|
||||
const barClass = score <= 1 ? 'bg-destructive' : score === 2 ? 'bg-orange-500' : score === 3 ? 'bg-yellow-400' : 'bg-green-500'
|
||||
|
||||
return (
|
||||
<div className={cn('w-full space-y-2', className)}>
|
||||
<Label htmlFor={inputId}>{label}</Label>
|
||||
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={inputId}
|
||||
type={isVisible ? 'text' : 'password'}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="pr-9"
|
||||
disabled={disabled}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleVisibility}
|
||||
disabled={disabled}
|
||||
className="text-muted-foreground focus-visible:ring-ring/50 absolute inset-y-0 right-0 rounded-l-none hover:bg-transparent"
|
||||
>
|
||||
{isVisible ? <EyeOffIcon /> : <EyeIcon />}
|
||||
<span className="sr-only">{isVisible ? '숨기기' : '보기'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Strength bars */}
|
||||
<div className="flex h-1 w-full gap-1">
|
||||
{Array.from({ length: requirements.length }).map((_, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className={cn(
|
||||
'h-full flex-1 rounded-full transition-all duration-300 ease-out',
|
||||
index < score ? getBarColor(score) : 'bg-border'
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-start gap-2">
|
||||
{value ? (
|
||||
isValid ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<XIcon className="mt-0.5 size-4 text-destructive" />
|
||||
)
|
||||
) : (
|
||||
<span className="mt-0.5 size-4" />
|
||||
)}
|
||||
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs',
|
||||
!value
|
||||
? 'text-muted-foreground'
|
||||
: isValid
|
||||
? 'text-green-600 dark:text-green-400'
|
||||
: 'text-destructive'
|
||||
)}
|
||||
>
|
||||
{statusText}
|
||||
</p>
|
||||
</div>
|
||||
{
|
||||
/*
|
||||
<p className="text-foreground text-sm font-medium">
|
||||
{getStrengthText(score)}.
|
||||
</p>
|
||||
<p className="text-foreground text-sm font-medium">
|
||||
포함 조건:
|
||||
</p>
|
||||
<ul className="space-y-1.5">
|
||||
{checks.map((c, idx) => (
|
||||
<li key={idx} className="flex items-start gap-2">
|
||||
{c.met ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<XIcon className="mt-0.5 size-4 text-muted-foreground" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs',
|
||||
c.met ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{c.text}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
*/
|
||||
}
|
||||
<div className={cn('w-full space-y-2', className)}>
|
||||
{label ? <Label htmlFor={inputId}>{label}</Label> : null}
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={inputId}
|
||||
type={isVisible ? 'text' : 'password'}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
className="pr-9"
|
||||
disabled={disabled}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setIsVisible((current) => !current)}
|
||||
disabled={disabled}
|
||||
className="text-muted-foreground absolute inset-y-0 right-0 rounded-l-none hover:bg-transparent"
|
||||
>
|
||||
{isVisible ? <EyeOffIcon /> : <EyeIcon />}
|
||||
<span className="sr-only">{isVisible ? '숨기기' : '보기'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showStrength ? (
|
||||
<>
|
||||
<div className="flex h-1 w-full gap-1">
|
||||
{requirements.map((item, index) => (
|
||||
<span
|
||||
key={item.text}
|
||||
className={cn(
|
||||
'h-full flex-1 rounded-full transition-colors',
|
||||
index < score && value ? barClass : 'bg-border',
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-start gap-2">
|
||||
{value ? (
|
||||
isValid ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600" />
|
||||
) : (
|
||||
<XIcon className="text-destructive mt-0.5 size-4" />
|
||||
)
|
||||
) : (
|
||||
<span className="mt-0.5 size-4" />
|
||||
)}
|
||||
<p className={cn('text-xs', !value ? 'text-muted-foreground' : isValid ? 'text-green-600' : 'text-destructive')}>
|
||||
{statusText}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export type KriSelectItem = {
|
||||
label: string
|
||||
}
|
||||
|
||||
type KriSelectProps<T> = {
|
||||
export type KriSelectProps<T> = {
|
||||
items: T[]
|
||||
value: string
|
||||
onChange?: (value: string) => void
|
||||
@@ -23,6 +23,7 @@ type KriSelectProps<T> = {
|
||||
getValue?: (item: T) => string
|
||||
getLabel?: (item: T) => string
|
||||
useAll?: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const HEIGHT_CLASS_VALUE: Record<string, CSSProperties['height']> = {
|
||||
@@ -41,12 +42,13 @@ export function KriSelect<T>({
|
||||
placeholder,
|
||||
className,
|
||||
heightClassName,
|
||||
triggerTextClassName = 'text-lg',
|
||||
triggerTextClassName,
|
||||
contentClassName,
|
||||
itemClassName,
|
||||
getValue,
|
||||
getLabel,
|
||||
useAll = true,
|
||||
disabled,
|
||||
}: KriSelectProps<T>) {
|
||||
const extractValue = (item: T) => (getValue ? getValue(item) : String(item))
|
||||
const extractLabel = (item: T) => (getLabel ? getLabel(item) : String(item))
|
||||
@@ -57,10 +59,11 @@ export function KriSelect<T>({
|
||||
return (
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={(v) => {
|
||||
onChange?.(v)
|
||||
disabled={disabled}
|
||||
onValueChange={(selectedValue) => {
|
||||
onChange?.(selectedValue)
|
||||
|
||||
const selected = items.find((item) => extractValue(item) === v)
|
||||
const selected = items.find((item) => extractValue(item) === selectedValue)
|
||||
if (selected) {
|
||||
onChangeOption?.(selected)
|
||||
}
|
||||
@@ -75,16 +78,16 @@ export function KriSelect<T>({
|
||||
</SelectTrigger>
|
||||
<SelectContent className={contentClassName}>
|
||||
{useAll ? (
|
||||
<SelectItem key="ALL" value="ALL" className={itemClassName}>
|
||||
<SelectItem value="ALL" className={itemClassName}>
|
||||
전체
|
||||
</SelectItem>
|
||||
) : null}
|
||||
{items.map((item, idx) => {
|
||||
const v = extractValue(item)
|
||||
{items.map((item, index) => {
|
||||
const itemValue = extractValue(item)
|
||||
const label = extractLabel(item)
|
||||
|
||||
return (
|
||||
<SelectItem key={v ?? idx} value={v} className={itemClassName}>
|
||||
<SelectItem key={itemValue || index} value={itemValue} className={itemClassName}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
)
|
||||
|
||||
99
src/components/common/KriTimePicker.tsx
Normal file
99
src/components/common/KriTimePicker.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriTimePickerProps = {
|
||||
value?: string
|
||||
onChange: (value: string) => void
|
||||
disabled?: boolean
|
||||
minuteStep?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
const parseTime = (value: string | undefined) => {
|
||||
if (!value) return { hour: undefined, minute: undefined }
|
||||
|
||||
const [hour, minute] = value.split(':').map(Number)
|
||||
|
||||
return {
|
||||
hour: Number.isInteger(hour) && hour >= 0 && hour < 24 ? hour : undefined,
|
||||
minute: Number.isInteger(minute) && minute >= 0 && minute < 60 ? minute : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
const formatTime = (hour: number, minute: number) => {
|
||||
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function KriTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
minuteStep = 5,
|
||||
className,
|
||||
}: KriTimePickerProps) {
|
||||
const { hour: selectedHour, minute: selectedMinute } = parseTime(value)
|
||||
const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0
|
||||
? Math.min(Math.floor(minuteStep), 60)
|
||||
: 5
|
||||
const hours = Array.from({ length: 24 }, (_, index) => index)
|
||||
const minutes = Array.from(
|
||||
{ length: Math.ceil(60 / normalizedMinuteStep) },
|
||||
(_, index) => index * normalizedMinuteStep,
|
||||
).filter((minute) => minute < 60)
|
||||
|
||||
const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => {
|
||||
if (disabled) return
|
||||
|
||||
const nextHour = type === 'hour' ? nextValue : selectedHour ?? 0
|
||||
const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0
|
||||
|
||||
onChange(formatTime(nextHour, nextMinute))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col divide-y sm:h-[300px] sm:flex-row sm:divide-x sm:divide-y-0', className)}>
|
||||
<ScrollArea className="w-64 sm:w-auto">
|
||||
<div className="flex p-2 sm:flex-col">
|
||||
{hours.map((hour) => (
|
||||
<Button
|
||||
key={hour}
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={selectedHour === hour ? 'default' : 'ghost'}
|
||||
className="aspect-square shrink-0 sm:w-full"
|
||||
disabled={disabled}
|
||||
onClick={() => handleTimeChange('hour', hour)}
|
||||
>
|
||||
{hour}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
|
||||
<ScrollArea className="w-64 sm:w-auto">
|
||||
<div className="flex p-2 sm:flex-col">
|
||||
{minutes.map((minute) => (
|
||||
<Button
|
||||
key={minute}
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={selectedMinute === minute ? 'default' : 'ghost'}
|
||||
className="aspect-square shrink-0 sm:w-full"
|
||||
disabled={disabled}
|
||||
onClick={() => handleTimeChange('minute', minute)}
|
||||
>
|
||||
{String(minute).padStart(2, '0')}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriTimePicker
|
||||
@@ -1,17 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export function LoadingOverlay({ force = false }: { force?: boolean }) {
|
||||
const isLoading = useAtomValue(loadingAtom);
|
||||
|
||||
if (!force && !isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
|
||||
{/* 심플 로딩 인디케이터 */}
|
||||
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MultiSelectContent } from './MultiSelectContent'
|
||||
import { MultiSelectTrigger } from './MultiSelectTrigger'
|
||||
import type { MultiSelectOption, MultiSelectProps, MultiSelectRef } from './types'
|
||||
import { arraysEqual, deduplicateOptions, flattenOptions } from './utils'
|
||||
import { useResponsiveSettings } from './use-responsive-settings'
|
||||
|
||||
function MultiSelectInner<T>(
|
||||
{
|
||||
options: rawOptions,
|
||||
onValueChange,
|
||||
onOptionChange,
|
||||
onInfoChange,
|
||||
defaultValue = [],
|
||||
stickySelectedOptions = [],
|
||||
onStickySelectedOptionsChange,
|
||||
placeholder = 'Select options',
|
||||
maxCount = 3,
|
||||
maxSelected,
|
||||
selectionMode = 'multiple',
|
||||
modalPopover = false,
|
||||
variant = 'default',
|
||||
className,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
hideSelectAll = false,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
emptyIndicator = '검색 결과가 없습니다.',
|
||||
autoSize = false,
|
||||
singleLine = false,
|
||||
popoverClassName,
|
||||
disabled = false,
|
||||
responsive,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
deduplicateOptions: shouldDeduplicate = false,
|
||||
resetOnDefaultValueChange = true,
|
||||
closeOnSelect = false,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
style,
|
||||
...buttonProps
|
||||
}: MultiSelectProps<T>,
|
||||
ref: React.ForwardedRef<MultiSelectRef>,
|
||||
) {
|
||||
const [selectedValues, setSelectedValues] = React.useState<string[]>(defaultValue)
|
||||
const [searchValue, setSearchValue] = React.useState(defaultSearchValue)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const buttonRef = React.useRef<HTMLButtonElement>(null)
|
||||
const [triggerWidth, setTriggerWidth] = React.useState<number>()
|
||||
|
||||
const options = React.useMemo(
|
||||
() => (shouldDeduplicate ? deduplicateOptions(rawOptions) : rawOptions),
|
||||
[rawOptions, shouldDeduplicate],
|
||||
)
|
||||
const flatOptions = React.useMemo(() => flattenOptions(options), [options])
|
||||
const responsiveSettings = useResponsiveSettings(responsive, maxCount)
|
||||
|
||||
const optionMap = React.useMemo(() => {
|
||||
const map = new Map<string, MultiSelectOption<T>>()
|
||||
for (const option of stickySelectedOptions) map.set(option.value, option)
|
||||
for (const option of flatOptions) map.set(option.value, option)
|
||||
return map
|
||||
}, [flatOptions, stickySelectedOptions])
|
||||
|
||||
const selectedOptions = React.useMemo(
|
||||
() => selectedValues.map((value) => optionMap.get(value) ?? { value, label: value }),
|
||||
[optionMap, selectedValues],
|
||||
)
|
||||
|
||||
const emit = React.useCallback(
|
||||
(next: string[]) => {
|
||||
setSelectedValues(next)
|
||||
onValueChange(next)
|
||||
const nextOptions = next.map((value) => optionMap.get(value) ?? { value, label: value })
|
||||
onOptionChange?.(nextOptions)
|
||||
onInfoChange?.(
|
||||
nextOptions.flatMap((option) => (option.info === undefined ? [] : [option.info])),
|
||||
)
|
||||
},
|
||||
[onInfoChange, onOptionChange, onValueChange, optionMap],
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!resetOnDefaultValueChange || arraysEqual(defaultValue, selectedValues)) return
|
||||
setSelectedValues(defaultValue)
|
||||
}, [defaultValue, resetOnDefaultValueChange, selectedValues])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!onStickySelectedOptionsChange) return
|
||||
const refreshed = selectedValues
|
||||
.map((value) => optionMap.get(value))
|
||||
.filter((option): option is MultiSelectOption<T> => Boolean(option))
|
||||
onStickySelectedOptionsChange(refreshed)
|
||||
}, [onStickySelectedOptionsChange, optionMap, selectedValues])
|
||||
|
||||
React.useEffect(() => {
|
||||
const element = buttonRef.current
|
||||
if (!element || !('ResizeObserver' in window)) return
|
||||
const update = () => setTriggerWidth(Math.round(element.getBoundingClientRect().width))
|
||||
update()
|
||||
const observer = new ResizeObserver(update)
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
React.useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
reset: () => {
|
||||
emit(defaultValue)
|
||||
setSearchValue(defaultSearchValue)
|
||||
setOpen(false)
|
||||
},
|
||||
getSelectedValues: () => selectedValues,
|
||||
setSelectedValues: emit,
|
||||
clear: () => emit([]),
|
||||
focus: () => buttonRef.current?.focus(),
|
||||
}),
|
||||
[defaultSearchValue, defaultValue, emit, selectedValues],
|
||||
)
|
||||
|
||||
const toggleOption = React.useCallback(
|
||||
(option: MultiSelectOption<T>) => {
|
||||
if (option.disabled) return
|
||||
const selected = selectedValues.includes(option.value)
|
||||
|
||||
if (selected) {
|
||||
if (preventDeselect) return
|
||||
emit(selectedValues.filter((value) => value !== option.value))
|
||||
return
|
||||
}
|
||||
|
||||
if (selectionMode === 'single') {
|
||||
emit([option.value])
|
||||
if (closeOnSelect) setOpen(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (maxSelected !== undefined && selectedValues.length >= maxSelected) return
|
||||
emit([...selectedValues, option.value])
|
||||
if (closeOnSelect) setOpen(false)
|
||||
},
|
||||
[closeOnSelect, emit, maxSelected, preventDeselect, selectedValues, selectionMode],
|
||||
)
|
||||
|
||||
const toggleAll = React.useCallback(() => {
|
||||
const values = flatOptions.filter((option) => !option.disabled).map((option) => option.value)
|
||||
const allSelected = values.length > 0 && values.every((value) => selectedValues.includes(value))
|
||||
if (allSelected) {
|
||||
if (!preventDeselect) emit([])
|
||||
return
|
||||
}
|
||||
emit(maxSelected === undefined ? values : values.slice(0, maxSelected))
|
||||
}, [emit, flatOptions, maxSelected, preventDeselect, selectedValues])
|
||||
|
||||
const handleSearchChange = (value: string) => {
|
||||
setSearchValue(value)
|
||||
onSearchValueChange?.(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<MultiSelectTrigger
|
||||
ref={buttonRef}
|
||||
selectedOptions={selectedOptions}
|
||||
placeholder={placeholder}
|
||||
maxCount={responsiveSettings.maxCount}
|
||||
compactMode={responsiveSettings.compactMode}
|
||||
hideIcons={responsiveSettings.hideIcons}
|
||||
singleLine={singleLine}
|
||||
preventDeselect={preventDeselect}
|
||||
variant={variant}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
onRemove={(value) => emit(selectedValues.filter((selected) => selected !== value))}
|
||||
onClear={() => emit([])}
|
||||
className={cn(autoSize && 'w-auto', className)}
|
||||
disabled={disabled}
|
||||
style={{ minWidth, maxWidth, ...style }}
|
||||
{...buttonProps}
|
||||
/>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className={cn('w-[var(--radix-popover-trigger-width)] min-w-64 p-0', popoverClassName)}
|
||||
style={{ width: triggerWidth ? `${triggerWidth}px` : undefined }}
|
||||
>
|
||||
<MultiSelectContent
|
||||
options={options}
|
||||
selectedValues={selectedValues}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
searchValue={searchValue}
|
||||
onSearchValueChange={handleSearchChange}
|
||||
hideSelectAll={hideSelectAll}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
selectionMode={selectionMode}
|
||||
emptyIndicator={emptyIndicator}
|
||||
onToggleOption={toggleOption}
|
||||
onToggleAll={toggleAll}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
const ForwardedMultiSelect = React.forwardRef(MultiSelectInner) as <T = unknown>(
|
||||
props: MultiSelectProps<T> & { ref?: React.ForwardedRef<MultiSelectRef> },
|
||||
) => React.ReactElement
|
||||
|
||||
export const MultiSelect = ForwardedMultiSelect
|
||||
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
169
src/components/common/multi-select/MultiSelectContent.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
'use client'
|
||||
|
||||
import { CheckIcon } from 'lucide-react'
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from '@/components/ui/command'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||
import { isGroupedOptions } from './utils'
|
||||
|
||||
interface MultiSelectContentProps<T> {
|
||||
options: MultiSelectOptions<T>
|
||||
selectedValues: string[]
|
||||
searchable: boolean
|
||||
searchMode: 'filter' | 'inputOnly'
|
||||
searchValue: string
|
||||
onSearchValueChange: (value: string) => void
|
||||
hideSelectAll: boolean
|
||||
hideOptionCheck: boolean
|
||||
selectionMode: 'single' | 'multiple'
|
||||
emptyIndicator: React.ReactNode
|
||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||
onToggleAll: () => void
|
||||
}
|
||||
|
||||
function OptionItem<T>({
|
||||
option,
|
||||
selected,
|
||||
hideOptionCheck,
|
||||
onToggle,
|
||||
}: {
|
||||
option: MultiSelectOption<T>
|
||||
selected: boolean
|
||||
hideOptionCheck: boolean
|
||||
onToggle: () => void
|
||||
}) {
|
||||
const Icon = option.icon
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
value={`${option.label} ${option.value}`}
|
||||
disabled={option.disabled}
|
||||
onSelect={onToggle}
|
||||
className="flex items-center cursor-pointer"
|
||||
>
|
||||
{!hideOptionCheck ? (
|
||||
<span
|
||||
className={cn(
|
||||
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||
selected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
) : null}
|
||||
{Icon ? <Icon className="size-4" style={{ color: option.style?.iconColor }} /> : null}
|
||||
<span className="truncate">{option.label}</span>
|
||||
</CommandItem>
|
||||
)
|
||||
}
|
||||
|
||||
function OptionsGroup<T>({
|
||||
group,
|
||||
selectedValues,
|
||||
hideOptionCheck,
|
||||
onToggleOption,
|
||||
}: {
|
||||
group: MultiSelectGroup<T>
|
||||
selectedValues: string[]
|
||||
hideOptionCheck: boolean
|
||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||
}) {
|
||||
return (
|
||||
<CommandGroup heading={group.heading}>
|
||||
{group.options.map((option) => (
|
||||
<OptionItem
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={selectedValues.includes(option.value)}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggle={() => onToggleOption(option)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export function MultiSelectContent<T>({
|
||||
options,
|
||||
selectedValues,
|
||||
searchable,
|
||||
searchMode,
|
||||
searchValue,
|
||||
onSearchValueChange,
|
||||
hideSelectAll,
|
||||
hideOptionCheck,
|
||||
selectionMode,
|
||||
emptyIndicator,
|
||||
onToggleOption,
|
||||
onToggleAll,
|
||||
}: MultiSelectContentProps<T>) {
|
||||
const grouped = isGroupedOptions(options)
|
||||
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))
|
||||
|
||||
return (
|
||||
<Command shouldFilter={searchMode === 'filter'}>
|
||||
{searchable ? (
|
||||
<CommandInput
|
||||
value={searchValue}
|
||||
onValueChange={onSearchValueChange}
|
||||
placeholder="검색..."
|
||||
/>
|
||||
) : null}
|
||||
<CommandList>
|
||||
<CommandEmpty>{emptyIndicator}</CommandEmpty>
|
||||
{selectionMode === 'multiple' && !hideSelectAll && selectableOptions.length > 0 ? (
|
||||
<>
|
||||
<CommandGroup>
|
||||
<CommandItem className="cursor-pointer" value="__kri_select_all__" onSelect={onToggleAll}>
|
||||
<span
|
||||
className={cn(
|
||||
'border-primary flex size-4 items-center justify-center rounded-sm border',
|
||||
allSelected ? 'bg-primary text-primary-foreground' : 'opacity-40 [&_svg]:invisible',
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
전체 선택
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
<CommandSeparator />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{grouped ? (
|
||||
options.map((group) => (
|
||||
<OptionsGroup
|
||||
key={group.heading}
|
||||
group={group}
|
||||
selectedValues={selectedValues}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggleOption={onToggleOption}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<CommandGroup>
|
||||
{options.map((option) => (
|
||||
<OptionItem
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={selectedValues.includes(option.value)}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
onToggle={() => onToggleOption(option)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
)
|
||||
}
|
||||
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
143
src/components/common/multi-select/MultiSelectTrigger.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { ChevronDown, XCircle, XIcon } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MultiSelectOption, MultiSelectVariant } from './types'
|
||||
import { getVariantClass } from './utils'
|
||||
|
||||
interface MultiSelectTriggerProps<T> extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onChange'> {
|
||||
selectedOptions: MultiSelectOption<T>[]
|
||||
placeholder: string
|
||||
maxCount: number
|
||||
singleLine: boolean
|
||||
compactMode: boolean
|
||||
hideIcons: boolean
|
||||
preventDeselect: boolean
|
||||
variant: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
onRemove: (value: string) => void
|
||||
onClear: () => void
|
||||
}
|
||||
|
||||
export const MultiSelectTrigger = React.forwardRef(function MultiSelectTriggerInner<T>(
|
||||
{
|
||||
selectedOptions,
|
||||
placeholder,
|
||||
maxCount,
|
||||
singleLine,
|
||||
compactMode,
|
||||
hideIcons,
|
||||
preventDeselect,
|
||||
variant,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
className,
|
||||
disabled,
|
||||
onRemove,
|
||||
onClear,
|
||||
...buttonProps
|
||||
}: MultiSelectTriggerProps<T>,
|
||||
ref: React.ForwardedRef<HTMLButtonElement>,
|
||||
) {
|
||||
const visible = selectedOptions.slice(0, maxCount)
|
||||
const hiddenCount = Math.max(0, selectedOptions.length - visible.length)
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-haspopup="listbox"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'h-auto min-h-9 w-full justify-between gap-2 px-3 py-1.5 font-normal',
|
||||
getVariantClass(variant),
|
||||
className,
|
||||
)}
|
||||
{...buttonProps}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'flex min-w-0 flex-1 items-center gap-1 text-left',
|
||||
singleLine ? 'overflow-x-auto whitespace-nowrap' : 'flex-wrap',
|
||||
spanClassName,
|
||||
)}
|
||||
>
|
||||
{selectedOptions.length === 0 ? (
|
||||
<span className="text-muted-foreground truncate">{placeholder}</span>
|
||||
) : compactMode ? (
|
||||
<span>{selectedOptions.length}개 선택</span>
|
||||
) : (
|
||||
<>
|
||||
{visible.map((option) => {
|
||||
const Icon = option.icon
|
||||
return (
|
||||
<Badge
|
||||
key={option.value}
|
||||
variant="secondary"
|
||||
className={cn('max-w-full gap-1', badgeClassName)}
|
||||
style={{ background: option.style?.gradient ?? option.style?.badgeColor }}
|
||||
>
|
||||
{!hideIcons && Icon ? <Icon className="size-3.5" /> : null}
|
||||
<span className="max-w-48 truncate">{option.label}</span>
|
||||
{!preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`${option.label} 선택 해제`}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onRemove(option.value)
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onRemove(option.value)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</span>
|
||||
) : null}
|
||||
</Badge>
|
||||
)
|
||||
})}
|
||||
{hiddenCount > 0 ? <Badge variant="secondary">+{hiddenCount}</Badge> : null}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<span className="flex shrink-0 items-center gap-1">
|
||||
{selectedOptions.length > 0 && !preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="전체 선택 해제"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClear()
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClear()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XCircle className="text-muted-foreground size-4" />
|
||||
</span>
|
||||
) : null}
|
||||
<ChevronDown className="text-muted-foreground size-4" />
|
||||
</span>
|
||||
</Button>
|
||||
)
|
||||
}) as <T>(props: MultiSelectTriggerProps<T> & { ref?: React.ForwardedRef<HTMLButtonElement> }) => React.ReactElement
|
||||
13
src/components/common/multi-select/index.ts
Normal file
13
src/components/common/multi-select/index.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export { MultiSelect } from './MultiSelect'
|
||||
export type {
|
||||
AnimationConfig,
|
||||
MultiSelectGroup,
|
||||
MultiSelectOption,
|
||||
MultiSelectOptions,
|
||||
MultiSelectProps,
|
||||
MultiSelectRef,
|
||||
MultiSelectResponsiveConfig,
|
||||
MultiSelectResponsiveSettings,
|
||||
MultiSelectSelectionMode,
|
||||
MultiSelectVariant,
|
||||
} from './types'
|
||||
89
src/components/common/multi-select/types.ts
Normal file
89
src/components/common/multi-select/types.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import type * as React from 'react'
|
||||
|
||||
export interface AnimationConfig {
|
||||
badgeAnimation?: 'bounce' | 'pulse' | 'wiggle' | 'fade' | 'slide' | 'none'
|
||||
popoverAnimation?: 'scale' | 'slide' | 'fade' | 'flip' | 'none'
|
||||
optionHoverAnimation?: 'highlight' | 'scale' | 'glow' | 'none'
|
||||
duration?: number
|
||||
delay?: number
|
||||
}
|
||||
|
||||
export interface MultiSelectOption<T = unknown> {
|
||||
label: string
|
||||
value: string
|
||||
info?: T
|
||||
icon?: React.ComponentType<React.SVGProps<SVGSVGElement>>
|
||||
disabled?: boolean
|
||||
style?: {
|
||||
badgeColor?: string
|
||||
iconColor?: string
|
||||
gradient?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface MultiSelectGroup<T = unknown> {
|
||||
heading: string
|
||||
options: MultiSelectOption<T>[]
|
||||
}
|
||||
|
||||
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
|
||||
export type MultiSelectSelectionMode = 'single' | 'multiple'
|
||||
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
|
||||
|
||||
export interface MultiSelectResponsiveSettings {
|
||||
maxCount?: number
|
||||
hideIcons?: boolean
|
||||
compactMode?: boolean
|
||||
}
|
||||
|
||||
export interface MultiSelectResponsiveConfig {
|
||||
mobile?: MultiSelectResponsiveSettings
|
||||
tablet?: MultiSelectResponsiveSettings
|
||||
desktop?: MultiSelectResponsiveSettings
|
||||
}
|
||||
|
||||
export interface MultiSelectProps<T = unknown>
|
||||
extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'defaultValue' | 'onChange'> {
|
||||
options: MultiSelectOptions<T>
|
||||
onValueChange: (value: string[]) => void
|
||||
onOptionChange?: (selectedOptions: MultiSelectOption<T>[]) => void
|
||||
onInfoChange?: (infos: T[]) => void
|
||||
defaultValue?: string[]
|
||||
stickySelectedOptions?: MultiSelectOption<T>[]
|
||||
onStickySelectedOptionsChange?: (options: MultiSelectOption<T>[]) => void
|
||||
placeholder?: string
|
||||
animation?: number
|
||||
animationConfig?: AnimationConfig
|
||||
maxCount?: number
|
||||
maxSelected?: number
|
||||
selectionMode?: MultiSelectSelectionMode
|
||||
modalPopover?: boolean
|
||||
variant?: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
hideSelectAll?: boolean
|
||||
searchable?: boolean
|
||||
searchMode?: 'filter' | 'inputOnly'
|
||||
defaultSearchValue?: string
|
||||
onSearchValueChange?: (value: string) => void
|
||||
emptyIndicator?: React.ReactNode
|
||||
autoSize?: boolean
|
||||
singleLine?: boolean
|
||||
popoverClassName?: string
|
||||
responsive?: boolean | MultiSelectResponsiveConfig
|
||||
minWidth?: string
|
||||
maxWidth?: string
|
||||
deduplicateOptions?: boolean
|
||||
resetOnDefaultValueChange?: boolean
|
||||
closeOnSelect?: boolean
|
||||
preventDeselect?: boolean
|
||||
hideOptionCheck?: boolean
|
||||
}
|
||||
|
||||
export interface MultiSelectRef {
|
||||
reset: () => void
|
||||
getSelectedValues: () => string[]
|
||||
setSelectedValues: (values: string[]) => void
|
||||
clear: () => void
|
||||
focus: () => void
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import type { MultiSelectProps, MultiSelectResponsiveSettings } from './types'
|
||||
|
||||
export function useResponsiveSettings(
|
||||
responsive: MultiSelectProps['responsive'],
|
||||
defaultMaxCount: number,
|
||||
): Required<MultiSelectResponsiveSettings> {
|
||||
const [screen, setScreen] = React.useState<'mobile' | 'tablet' | 'desktop'>('desktop')
|
||||
|
||||
React.useEffect(() => {
|
||||
const update = () => {
|
||||
if (window.innerWidth < 640) setScreen('mobile')
|
||||
else if (window.innerWidth < 1024) setScreen('tablet')
|
||||
else setScreen('desktop')
|
||||
}
|
||||
|
||||
update()
|
||||
window.addEventListener('resize', update)
|
||||
return () => window.removeEventListener('resize', update)
|
||||
}, [])
|
||||
|
||||
if (!responsive) {
|
||||
return { maxCount: defaultMaxCount, hideIcons: false, compactMode: false }
|
||||
}
|
||||
|
||||
if (responsive === true) {
|
||||
const defaults = {
|
||||
mobile: { maxCount: 2, hideIcons: false, compactMode: true },
|
||||
tablet: { maxCount: 4, hideIcons: false, compactMode: false },
|
||||
desktop: { maxCount: 6, hideIcons: false, compactMode: false },
|
||||
}
|
||||
return defaults[screen]
|
||||
}
|
||||
|
||||
const current = responsive[screen]
|
||||
return {
|
||||
maxCount: current?.maxCount ?? defaultMaxCount,
|
||||
hideIcons: current?.hideIcons ?? false,
|
||||
compactMode: current?.compactMode ?? false,
|
||||
}
|
||||
}
|
||||
48
src/components/common/multi-select/utils.ts
Normal file
48
src/components/common/multi-select/utils.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
||||
|
||||
export function isGroupedOptions<T>(options: MultiSelectOptions<T>): options is MultiSelectGroup<T>[] {
|
||||
return options.length > 0 && 'heading' in options[0]
|
||||
}
|
||||
|
||||
export function flattenOptions<T>(options: MultiSelectOptions<T>): MultiSelectOption<T>[] {
|
||||
return isGroupedOptions(options) ? options.flatMap((group) => group.options) : options
|
||||
}
|
||||
|
||||
export function deduplicateOptions<T>(options: MultiSelectOptions<T>): MultiSelectOptions<T> {
|
||||
const seen = new Set<string>()
|
||||
|
||||
if (isGroupedOptions(options)) {
|
||||
return options.map((group) => ({
|
||||
...group,
|
||||
options: group.options.filter((option) => {
|
||||
if (seen.has(option.value)) return false
|
||||
seen.add(option.value)
|
||||
return true
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
return options.filter((option) => {
|
||||
if (seen.has(option.value)) return false
|
||||
seen.add(option.value)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function arraysEqual(left: string[], right: string[]): boolean {
|
||||
if (left.length !== right.length) return false
|
||||
return left.every((value, index) => value === right[index])
|
||||
}
|
||||
|
||||
export function getVariantClass(variant: 'default' | 'secondary' | 'destructive' | 'inverted'): string {
|
||||
switch (variant) {
|
||||
case 'secondary':
|
||||
return 'bg-secondary text-secondary-foreground'
|
||||
case 'destructive':
|
||||
return 'bg-destructive text-destructive-foreground'
|
||||
case 'inverted':
|
||||
return 'bg-foreground text-background'
|
||||
default:
|
||||
return 'bg-background text-foreground'
|
||||
}
|
||||
}
|
||||
@@ -1,224 +1,179 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
ChevronsLeftIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsRightIcon,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
ArrowUpDown
|
||||
} from 'lucide-react'
|
||||
|
||||
import type { PaginationState, SortingState, RowSelectionState } from '@tanstack/react-table'
|
||||
import {
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel,
|
||||
useReactTable
|
||||
} from '@tanstack/react-table'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { OnChangeFn, PaginationState, Row, RowSelectionState, SortingState } from '@tanstack/react-table'
|
||||
import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table'
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
|
||||
import { usePagination } from './hooks/usePagination'
|
||||
import { DataTableProps, DataTableColumn } from './DataTable.type'
|
||||
|
||||
import { TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {usePreventClickOnDrag} from "@/components/data-table/hooks/usePreventClickOnDrag";
|
||||
import type { DataTableColumn, DataTableProps } from './DataTable.type'
|
||||
import { DataTablePagination } from './DataTablePagination'
|
||||
import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag'
|
||||
|
||||
export function DataTable<TData>({
|
||||
columns,
|
||||
data,
|
||||
getRowId,
|
||||
highlightRowIds,
|
||||
isClient = true,
|
||||
pageCount: serverPageCount,
|
||||
totalCount: serverTotalCount,
|
||||
onPaginationChange: onServerPaginationChange,
|
||||
onSortingChange: onServerSortingChange,
|
||||
selectMode = 'none',
|
||||
onRowClick,
|
||||
onRowSelectionChange,
|
||||
defaultPageSize = 10,
|
||||
pageSizeOptions = [5, 10, 25, 50],
|
||||
paginationItemsToDisplay = 5
|
||||
}: Readonly<DataTableProps<TData>>) {
|
||||
// Pagination state
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: defaultPageSize
|
||||
})
|
||||
|
||||
// Sorting state
|
||||
export function DataTable<TData, TValue = unknown>({
|
||||
columns,
|
||||
data,
|
||||
getRowId,
|
||||
highlightRowIds,
|
||||
focusRowId,
|
||||
isClient = true,
|
||||
pageCount: serverPageCount,
|
||||
totalCount: serverTotalCount,
|
||||
pagination: externalPagination,
|
||||
onPaginationChange: onServerPaginationChange,
|
||||
onSortingChange: onServerSortingChange,
|
||||
selectMode = 'none',
|
||||
onRowClick,
|
||||
onRowDoubleClick,
|
||||
onRowSelectionChange,
|
||||
defaultPageSize = 10,
|
||||
pageSizeOptions = [5, 10, 25, 50],
|
||||
paginationItemsToDisplay = 5,
|
||||
emptyText = '데이터가 없습니다.',
|
||||
className,
|
||||
maxBodyHeight,
|
||||
}: Readonly<DataTableProps<TData, TValue>>) {
|
||||
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
|
||||
// Row selection state
|
||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const drag = usePreventClickOnDrag()
|
||||
const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
|
||||
|
||||
const drag = usePreventClickOnDrag(6);
|
||||
const enhancedColumns = useMemo<DataTableColumn<TData, TValue>[]>(() => {
|
||||
if (!selectionEnabled) return columns
|
||||
|
||||
const isNotSelection = !['none', 'click-event'].includes(selectMode);
|
||||
const selectionColumn = {
|
||||
id: 'select',
|
||||
header: ({ table }) => selectMode === 'multi' ? (
|
||||
<Checkbox
|
||||
checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && 'indeterminate')}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(Boolean(value))}
|
||||
aria-label="전체 선택"
|
||||
/>
|
||||
) : null,
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onCheckedChange={(value) => {
|
||||
if (selectMode === 'single') table.resetRowSelection()
|
||||
row.toggleSelected(Boolean(value))
|
||||
}}
|
||||
aria-label="행 선택"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
/>
|
||||
),
|
||||
size: 28,
|
||||
enableSorting: false,
|
||||
} as DataTableColumn<TData, TValue>
|
||||
|
||||
// 서버 페이지네이션일 때 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (!isClient && onServerPaginationChange) {
|
||||
onServerPaginationChange(pagination)
|
||||
}
|
||||
}, [pagination, isClient, onServerPaginationChange])
|
||||
return [selectionColumn, ...columns]
|
||||
}, [columns, selectMode, selectionEnabled])
|
||||
|
||||
// 서버 정렬일 때 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (!isClient && onServerSortingChange) {
|
||||
onServerSortingChange(sorting)
|
||||
}
|
||||
}, [sorting, isClient, onServerSortingChange])
|
||||
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
|
||||
|
||||
// Row selection 변경 시 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (isNotSelection && onRowSelectionChange) {
|
||||
const selectedRows = table
|
||||
.getSelectedRowModel()
|
||||
.rows.map(row => row.original)
|
||||
onRowSelectionChange(selectedRows)
|
||||
}
|
||||
}, [rowSelection, selectMode])
|
||||
const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(
|
||||
(updater) => {
|
||||
if (isClient) {
|
||||
setInternalPagination(updater)
|
||||
return
|
||||
}
|
||||
|
||||
// selectMode에 따라 select column 추가
|
||||
const enhancedColumns: DataTableColumn<TData, any>[] = [
|
||||
...(isNotSelection
|
||||
? [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) =>
|
||||
selectMode === 'multi' ? (
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && 'indeterminate')
|
||||
}
|
||||
onCheckedChange={value => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label='KriSelect all'
|
||||
/>
|
||||
) : null,
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onCheckedChange={value => {
|
||||
if (selectMode === 'single') {
|
||||
// single mode: 다른 것 모두 해제
|
||||
table.resetRowSelection()
|
||||
}
|
||||
row.toggleSelected(!!value)
|
||||
}}
|
||||
aria-label='KriSelect row'
|
||||
onClick={e => e.stopPropagation()} // row 클릭 이벤트 전파 방지
|
||||
/>
|
||||
),
|
||||
size: 28,
|
||||
enableSorting: false
|
||||
} as DataTableColumn<TData, any>
|
||||
]
|
||||
: []),
|
||||
...columns
|
||||
]
|
||||
if (onServerPaginationChange) {
|
||||
onServerPaginationChange(updater)
|
||||
return
|
||||
}
|
||||
|
||||
// Row 클릭 핸들러
|
||||
const handleRowClick = (row: any) => {
|
||||
switch (selectMode) {
|
||||
case 'none':
|
||||
return
|
||||
|
||||
case 'click-event':
|
||||
if (!onRowClick) return
|
||||
onRowClick(row.original)
|
||||
return
|
||||
|
||||
case 'single':
|
||||
table.resetRowSelection()
|
||||
row.toggleSelected(true)
|
||||
return
|
||||
|
||||
default: // 'multi' 등
|
||||
row.toggleSelected(!row.getIsSelected())
|
||||
return
|
||||
}
|
||||
}
|
||||
setInternalPagination(updater)
|
||||
},
|
||||
[isClient, onServerPaginationChange],
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns: enhancedColumns,
|
||||
pageCount: isClient ? undefined : serverPageCount,
|
||||
state: {
|
||||
sorting,
|
||||
pagination,
|
||||
rowSelection
|
||||
},
|
||||
enableRowSelection: isNotSelection,
|
||||
state: { sorting, pagination, rowSelection },
|
||||
enableRowSelection: selectionEnabled,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onPaginationChange: setPagination,
|
||||
onPaginationChange: handlePaginationChange,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
||||
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
|
||||
manualPagination: !isClient,
|
||||
manualSorting: !isClient,
|
||||
enableSortingRemoval: false,
|
||||
...(getRowId && { getRowId }), //있으면만 적용
|
||||
...(getRowId ? { getRowId } : {}),
|
||||
})
|
||||
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
|
||||
currentPage: table.getState().pagination.pageIndex + 1,
|
||||
totalPages: table.getPageCount(),
|
||||
paginationItemsToDisplay
|
||||
})
|
||||
useEffect(() => {
|
||||
if (!isClient) onServerSortingChange?.(sorting)
|
||||
}, [isClient, onServerSortingChange, sorting])
|
||||
|
||||
const totalCount = isClient ? data.length : (serverTotalCount || 0)
|
||||
useEffect(() => {
|
||||
if (!selectionEnabled) return
|
||||
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
|
||||
}, [onRowSelectionChange, rowSelection, selectionEnabled, table])
|
||||
|
||||
useEffect(() => {
|
||||
if (!focusRowId) return
|
||||
const target = containerRef.current?.querySelector<HTMLElement>(`[data-row-id="${CSS.escape(focusRowId)}"]`)
|
||||
target?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}, [focusRowId, data])
|
||||
|
||||
const handleRowClick = (row: Row<TData>) => {
|
||||
if (selectMode === 'none') return
|
||||
if (selectMode === 'click-event') {
|
||||
onRowClick?.(row.original)
|
||||
return
|
||||
}
|
||||
if (selectMode === 'single') {
|
||||
table.resetRowSelection()
|
||||
row.toggleSelected(true)
|
||||
onRowClick?.(row.original)
|
||||
return
|
||||
}
|
||||
row.toggleSelected(!row.getIsSelected())
|
||||
onRowClick?.(row.original)
|
||||
}
|
||||
|
||||
const handleRowDoubleClick = (row: Row<TData>) => {
|
||||
onRowDoubleClick?.(row.original)
|
||||
}
|
||||
|
||||
const totalCount = isClient ? data.length : (serverTotalCount ?? 0)
|
||||
|
||||
return (
|
||||
<div className='w-full space-y-4'>
|
||||
<div className='rounded-md border'>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<TableRow key={headerGroup.id} className='hover:bg-transparent'>
|
||||
{headerGroup.headers.map(header => {
|
||||
<div className={cn('w-full space-y-4', className)}>
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn('relative w-full overflow-x-auto rounded-md border', maxBodyHeight && 'overflow-y-auto')}
|
||||
style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined}
|
||||
>
|
||||
<table className="w-full caption-bottom text-sm">
|
||||
<TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-10 bg-background')}>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id} className="hover:bg-transparent">
|
||||
{headerGroup.headers.map((header) => {
|
||||
const column = header.column
|
||||
const canSort = column.getCanSort()
|
||||
const sorted = column.getIsSorted() as false | 'asc' | 'desc'
|
||||
const headerContent = header.isPlaceholder
|
||||
? null
|
||||
: flexRender(column.columnDef.header, header.getContext())
|
||||
const sorted = column.getIsSorted()
|
||||
const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
|
||||
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={cn(
|
||||
'text-lg font-semibold text-gray-900',
|
||||
column.id === 'actions' && 'w-[140px] text-center'
|
||||
)}
|
||||
className={cn('text-base font-semibold text-foreground', column.id === 'actions' && 'w-[140px] text-center')}
|
||||
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
|
||||
>
|
||||
{header.isPlaceholder ? null : canSort ? (
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
className='px-0 font-semibold text-lg flex items-center gap-1'
|
||||
onClick={column.getToggleSortingHandler()}
|
||||
>
|
||||
<span>{headerContent}</span>
|
||||
{sorted === 'asc' && <ArrowUp className='w-3 h-3' />}
|
||||
{sorted === 'desc' && <ArrowDown className='w-3 h-3' />}
|
||||
{!sorted && <ArrowUpDown className='w-3 h-3 text-muted-foreground' />}
|
||||
{!header.isPlaceholder && column.getCanSort() ? (
|
||||
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}>
|
||||
<span>{content}</span>
|
||||
{sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="text-muted-foreground size-3" />}
|
||||
</Button>
|
||||
) : (
|
||||
headerContent
|
||||
)}
|
||||
) : content}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
@@ -226,160 +181,41 @@ export function DataTable<TData>({
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map(row => {
|
||||
const shouldHighlight = highlightRowIds && highlightRowIds.includes(row.id)
|
||||
return (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && 'selected'}
|
||||
onPointerDown={drag.onPointerDown}
|
||||
onPointerMove={drag.onPointerMove}
|
||||
onPointerUp={drag.onPointerUp}
|
||||
onPointerCancel={drag.onPointerCancel}
|
||||
onClick={drag.wrapClick(() => handleRowClick(row))}
|
||||
className={cn(
|
||||
'text-base',
|
||||
'[&>td]:py-0 [&>td]:px-2',
|
||||
selectMode !== 'none' && 'cursor-pointer',
|
||||
'data-[state=selected]:bg-slate-100 data-[state=selected]:font-semibold',
|
||||
shouldHighlight && 'bg-emerald-50',
|
||||
)}
|
||||
>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)})
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={enhancedColumns.length} className='h-24 text-center'>
|
||||
데이터가 없습니다.
|
||||
</TableCell>
|
||||
{table.getRowModel().rows.length ? table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-row-id={row.id}
|
||||
data-state={row.getIsSelected() ? 'selected' : undefined}
|
||||
onPointerDown={drag.onPointerDown}
|
||||
onPointerMove={drag.onPointerMove}
|
||||
onPointerUp={drag.onPointerUp}
|
||||
onPointerCancel={drag.onPointerCancel}
|
||||
onClick={drag.wrapClick(() => handleRowClick(row))}
|
||||
onDoubleClick={onRowDoubleClick ? () => handleRowDoubleClick(row) : undefined}
|
||||
className={cn(
|
||||
'text-base [&>td]:px-2 [&>td]:py-0',
|
||||
(selectMode !== 'none' || onRowDoubleClick) && 'cursor-pointer',
|
||||
'data-[state=selected]:bg-muted data-[state=selected]:font-semibold',
|
||||
highlightRowIds?.includes(row.id) && 'bg-emerald-50',
|
||||
row.id === focusRowId && 'bg-accent',
|
||||
)}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
|
||||
</TableRow>
|
||||
)) : (
|
||||
<TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className='flex items-center justify-between gap-3 max-sm:flex-col p-2 pt-0'>
|
||||
<p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>
|
||||
Page <span className='text-foreground'>{table.getState().pagination.pageIndex + 1}</span> of{' '}
|
||||
<span className='text-foreground'>{table.getPageCount()}</span>
|
||||
{!isClient && totalCount > 0 && (
|
||||
<span className='ml-2'>
|
||||
(총 <span className='text-foreground'>{totalCount}</span>건)
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className='grow'>
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.firstPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
aria-label='Go to first page'
|
||||
>
|
||||
<ChevronsLeftIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.previousPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
aria-label='Go to previous page'
|
||||
>
|
||||
<ChevronLeftIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
|
||||
{showLeftEllipsis && (
|
||||
<PaginationItem>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
)}
|
||||
|
||||
{pages.map(page => {
|
||||
const isActive = page === table.getState().pagination.pageIndex + 1
|
||||
|
||||
return (
|
||||
<PaginationItem key={page}>
|
||||
<Button
|
||||
size='icon'
|
||||
variant={isActive ? 'default' : 'ghost'}
|
||||
onClick={() => table.setPageIndex(page - 1)}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
>
|
||||
{page}
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
)
|
||||
})}
|
||||
|
||||
{showRightEllipsis && (
|
||||
<PaginationItem>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
)}
|
||||
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.nextPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
aria-label='Go to next page'
|
||||
>
|
||||
<ChevronRightIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.lastPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
aria-label='Go to last page'
|
||||
>
|
||||
<ChevronsRightIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-1 justify-end'>
|
||||
<Select
|
||||
value={table.getState().pagination.pageSize.toString()}
|
||||
onValueChange={value => {
|
||||
table.setPageSize(Number(value))
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id='results-per-page' className='w-fit whitespace-nowrap' aria-label='Results per page'>
|
||||
<SelectValue placeholder='페이지당 개수' />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pageSizeOptions.map(size => (
|
||||
<SelectItem key={size} value={size.toString()}>
|
||||
{size} / page
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DataTablePagination
|
||||
table={table}
|
||||
isClient={isClient}
|
||||
totalCount={totalCount}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
paginationItemsToDisplay={paginationItemsToDisplay}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'
|
||||
import type { ColumnDef, PaginationState, SortingState, Updater } from '@tanstack/react-table'
|
||||
|
||||
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
|
||||
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue> & {
|
||||
enableSorting?: boolean // 정렬 가능 여부 (기본값: false)
|
||||
}
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue>
|
||||
|
||||
export interface ServerPaginationParams {
|
||||
pageIndex: number
|
||||
@@ -18,30 +15,26 @@ export interface ServerPaginationResponse<TData> {
|
||||
pageCount: number
|
||||
}
|
||||
|
||||
export interface DataTableProps<TData> {
|
||||
// 필수 props
|
||||
columns: DataTableColumn<TData, any>[]
|
||||
export interface DataTableProps<TData, TValue = unknown> {
|
||||
columns: DataTableColumn<TData, TValue>[]
|
||||
data: TData[]
|
||||
getRowId?: (row: TData, index: number) => string //id 지정
|
||||
getRowId?: (row: TData, index: number) => string
|
||||
highlightRowIds?: string[]
|
||||
// 페이지네이션 모드
|
||||
isClient?: boolean // true: 클라이언트, false: 서버 (기본값: true)
|
||||
|
||||
// 서버 페이지네이션 (isClient=false일 때 필요)
|
||||
focusRowId?: string
|
||||
isClient?: boolean
|
||||
pageCount?: number
|
||||
totalCount?: number
|
||||
onPaginationChange?: (pagination: PaginationState) => void
|
||||
pagination?: PaginationState
|
||||
onPaginationChange?: (updater: Updater<PaginationState>) => void
|
||||
onSortingChange?: (sorting: SortingState) => void
|
||||
|
||||
// 선택 모드
|
||||
selectMode?: SelectMode // 'none' | 'click-event' | 'single' | 'multi' (기본값: 'none')
|
||||
onRowClick?: (selectedRows: TData) => void
|
||||
onRowSelectionChange?: (selectedRows: TData[]) => void
|
||||
|
||||
// 페이지네이션 설정
|
||||
selectMode?: SelectMode
|
||||
onRowClick?: (row: TData) => void
|
||||
onRowDoubleClick?: (row: TData) => void
|
||||
onRowSelectionChange?: (rows: TData[]) => void
|
||||
defaultPageSize?: number
|
||||
pageSizeOptions?: number[]
|
||||
|
||||
// 기타 설정
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
emptyText?: string
|
||||
className?: string
|
||||
maxBodyHeight?: string
|
||||
}
|
||||
|
||||
98
src/components/data-table/DataTablePagination.tsx
Normal file
98
src/components/data-table/DataTablePagination.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
'use client'
|
||||
|
||||
import type { Table } from '@tanstack/react-table'
|
||||
import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { usePagination } from './hooks/usePagination'
|
||||
|
||||
interface DataTablePaginationProps<TData> {
|
||||
table: Table<TData>
|
||||
isClient: boolean
|
||||
totalCount: number
|
||||
pageSizeOptions: number[]
|
||||
paginationItemsToDisplay: number
|
||||
}
|
||||
|
||||
export function DataTablePagination<TData>({
|
||||
table,
|
||||
isClient,
|
||||
totalCount,
|
||||
pageSizeOptions,
|
||||
paginationItemsToDisplay,
|
||||
}: DataTablePaginationProps<TData>) {
|
||||
'use no memo'
|
||||
|
||||
const currentPage = table.getState().pagination.pageIndex + 1
|
||||
const pageCount = table.getPageCount()
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
|
||||
currentPage,
|
||||
totalPages: pageCount,
|
||||
paginationItemsToDisplay,
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-3 p-2 pt-0 max-sm:flex-col">
|
||||
<p className="text-muted-foreground flex-1 whitespace-nowrap text-sm" aria-live="polite">
|
||||
Page <span className="text-foreground">{currentPage}</span> of{' '}
|
||||
<span className="text-foreground">{pageCount}</span>
|
||||
{!isClient && totalCount > 0 ? (
|
||||
<span className="ml-2">(총 <span className="text-foreground">{totalCount}</span>건)</span>
|
||||
) : null}
|
||||
</p>
|
||||
|
||||
<div className="grow">
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<Button size="icon" variant="outline" onClick={() => table.firstPage()} disabled={!table.getCanPreviousPage()} aria-label="첫 페이지">
|
||||
<ChevronsLeftIcon aria-hidden="true" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button size="icon" variant="outline" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} aria-label="이전 페이지">
|
||||
<ChevronLeftIcon aria-hidden="true" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
{showLeftEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
|
||||
{pages.map((page) => (
|
||||
<PaginationItem key={page}>
|
||||
<Button
|
||||
size="icon"
|
||||
variant={page === currentPage ? 'default' : 'ghost'}
|
||||
onClick={() => table.setPageIndex(page - 1)}
|
||||
aria-current={page === currentPage ? 'page' : undefined}
|
||||
>
|
||||
{page}
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
))}
|
||||
{showRightEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
|
||||
<PaginationItem>
|
||||
<Button size="icon" variant="outline" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} aria-label="다음 페이지">
|
||||
<ChevronRightIcon aria-hidden="true" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button size="icon" variant="outline" onClick={() => table.lastPage()} disabled={!table.getCanNextPage()} aria-label="마지막 페이지">
|
||||
<ChevronsRightIcon aria-hidden="true" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 justify-end">
|
||||
<Select value={String(table.getState().pagination.pageSize)} onValueChange={(value) => table.setPageSize(Number(value))}>
|
||||
<SelectTrigger className="w-fit whitespace-nowrap" aria-label="페이지당 개수">
|
||||
<SelectValue placeholder="페이지당 개수" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pageSizeOptions.map((size) => <SelectItem key={size} value={String(size)}>{size} / page</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,33 +6,25 @@ interface UsePaginationProps {
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
|
||||
export function usePagination({
|
||||
currentPage,
|
||||
totalPages,
|
||||
paginationItemsToDisplay = 5
|
||||
}: UsePaginationProps) {
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = useMemo(() => {
|
||||
const halfDisplay = Math.floor(paginationItemsToDisplay / 2)
|
||||
|
||||
let startPage = Math.max(1, currentPage - halfDisplay)
|
||||
let endPage = Math.min(totalPages, currentPage + halfDisplay)
|
||||
|
||||
if (currentPage <= halfDisplay) {
|
||||
endPage = Math.min(paginationItemsToDisplay, totalPages)
|
||||
export function usePagination({ currentPage, totalPages, paginationItemsToDisplay = 5 }: UsePaginationProps) {
|
||||
return useMemo(() => {
|
||||
if (totalPages <= 0) {
|
||||
return { pages: [] as number[], showLeftEllipsis: false, showRightEllipsis: false }
|
||||
}
|
||||
|
||||
if (currentPage > totalPages - halfDisplay) {
|
||||
startPage = Math.max(1, totalPages - paginationItemsToDisplay + 1)
|
||||
}
|
||||
const visibleCount = Math.max(1, paginationItemsToDisplay)
|
||||
const half = Math.floor(visibleCount / 2)
|
||||
let startPage = Math.max(1, currentPage - half)
|
||||
let endPage = Math.min(totalPages, startPage + visibleCount - 1)
|
||||
|
||||
const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i)
|
||||
if (endPage - startPage + 1 < visibleCount) {
|
||||
startPage = Math.max(1, endPage - visibleCount + 1)
|
||||
}
|
||||
|
||||
return {
|
||||
pages,
|
||||
pages: Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index),
|
||||
showLeftEllipsis: startPage > 1,
|
||||
showRightEllipsis: endPage < totalPages
|
||||
showRightEllipsis: endPage < totalPages,
|
||||
}
|
||||
}, [currentPage, totalPages, paginationItemsToDisplay])
|
||||
|
||||
return { pages, showLeftEllipsis, showRightEllipsis }
|
||||
}
|
||||
}, [currentPage, paginationItemsToDisplay, totalPages])
|
||||
}
|
||||
|
||||
@@ -1,48 +1,37 @@
|
||||
import * as React from "react";
|
||||
import * as React from 'react'
|
||||
|
||||
export const usePreventClickOnDrag = (thresholdPx = 6) => {
|
||||
const s = React.useRef({ x: 0, y: 0, dragging: false });
|
||||
export function usePreventClickOnDrag(thresholdPx = 6) {
|
||||
const state = React.useRef({ x: 0, y: 0, dragging: false })
|
||||
|
||||
const onPointerDown = React.useCallback((e: React.PointerEvent) => {
|
||||
// 좌클릭만
|
||||
if (e.button !== 0) return;
|
||||
s.current.x = e.clientX;
|
||||
s.current.y = e.clientY;
|
||||
s.current.dragging = false;
|
||||
}, []);
|
||||
const onPointerDown = React.useCallback((event: React.PointerEvent) => {
|
||||
if (event.button !== 0) return
|
||||
state.current = { x: event.clientX, y: event.clientY, dragging: false }
|
||||
}, [])
|
||||
|
||||
const onPointerMove = React.useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
// 누르고 있을 때만
|
||||
if (e.buttons === 0) return;
|
||||
|
||||
const dx = e.clientX - s.current.x;
|
||||
const dy = e.clientY - s.current.y;
|
||||
|
||||
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) {
|
||||
s.current.dragging = true;
|
||||
}
|
||||
},
|
||||
[thresholdPx]
|
||||
);
|
||||
const onPointerMove = React.useCallback((event: React.PointerEvent) => {
|
||||
if (event.buttons === 0) return
|
||||
const dx = event.clientX - state.current.x
|
||||
const dy = event.clientY - state.current.y
|
||||
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) state.current.dragging = true
|
||||
}, [thresholdPx])
|
||||
|
||||
const onPointerUp = React.useCallback(() => {
|
||||
// click은 pointerup 다음에 발생하므로 "다음 tick"에 false로 복구
|
||||
setTimeout(() => {
|
||||
s.current.dragging = false;
|
||||
}, 0);
|
||||
}, []);
|
||||
state.current.dragging = false
|
||||
}, 0)
|
||||
}, [])
|
||||
|
||||
const wrapClick =
|
||||
(fn: () => void) =>
|
||||
(e: React.MouseEvent) => {
|
||||
if (s.current.dragging) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
fn();
|
||||
};
|
||||
const wrapClick = React.useCallback(
|
||||
(callback: () => void) => (event: React.MouseEvent) => {
|
||||
if (state.current.dragging) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
callback()
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick };
|
||||
}
|
||||
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick }
|
||||
}
|
||||
|
||||
8
src/components/data-table/index.ts
Normal file
8
src/components/data-table/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export { DataTable } from './DataTable'
|
||||
export type {
|
||||
DataTableColumn,
|
||||
DataTableProps,
|
||||
SelectMode,
|
||||
ServerPaginationParams,
|
||||
ServerPaginationResponse,
|
||||
} from './DataTable.type'
|
||||
233
src/components/dialog/CmpnUpsertDialog.tsx
Normal file
233
src/components/dialog/CmpnUpsertDialog.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { CmpnInfoSaveRequest } from '@/types/cmpn'
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import { apiError, NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR } from "@kri/common/http";
|
||||
|
||||
export type CmpnUpsertDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
mode?: 'create' | 'edit'
|
||||
initialData?: Partial<CmpnInfoSaveRequest>
|
||||
onSubmit: (data: CmpnInfoSaveRequest) => void | Promise<void>
|
||||
onCheckDuplicate?: (cmpnId: string) => DataVerification | Promise<DataVerification>
|
||||
}
|
||||
|
||||
const createDefaultCmpnInfo = (): CmpnInfoSaveRequest => ({
|
||||
cmpnId: '',
|
||||
cmpnAlias: '',
|
||||
cmpnTel: '',
|
||||
ownCmpn: false,
|
||||
memo: '',
|
||||
})
|
||||
|
||||
const CmpnUpsertDialog = ({
|
||||
dialogId = 'cmpnUpsertDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
mode = 'create',
|
||||
initialData,
|
||||
onSubmit,
|
||||
onCheckDuplicate,
|
||||
}: CmpnUpsertDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog();
|
||||
|
||||
const [formData, setFormData] = useState<CmpnInfoSaveRequest>(createDefaultCmpnInfo);
|
||||
const [isCheckedDuplicate, setIsCheckedDuplicate] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId);
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen);
|
||||
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId);
|
||||
} else {
|
||||
hideDialog(dialogId);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (initialData) {
|
||||
setFormData({
|
||||
...createDefaultCmpnInfo(),
|
||||
...initialData,
|
||||
});
|
||||
|
||||
if (mode === 'edit') {
|
||||
setIsCheckedDuplicate(true);
|
||||
}
|
||||
} else {
|
||||
setFormData(createDefaultCmpnInfo());
|
||||
setIsCheckedDuplicate(false);
|
||||
}
|
||||
}, [initialData, mode, resolvedOpen]);
|
||||
|
||||
const handleInputChange = (field: keyof CmpnInfoSaveRequest, value: string) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
}));
|
||||
|
||||
if (field === 'cmpnId' && mode === 'create') {
|
||||
setIsCheckedDuplicate(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleCheckDuplicate = async () => {
|
||||
const cmpnId = formData.cmpnId.trim();
|
||||
if (!cmpnId) {
|
||||
alert("회사 ID를 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (onCheckDuplicate) {
|
||||
const result = await onCheckDuplicate(cmpnId);
|
||||
if (!result.success) {
|
||||
alert(result.errMessage);
|
||||
setIsCheckedDuplicate(false);
|
||||
} else {
|
||||
alert("사용 가능한 회사 ID입니다.");
|
||||
setIsCheckedDuplicate(true);
|
||||
}
|
||||
} else {
|
||||
setIsCheckedDuplicate(true);
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!formData.cmpnId.trim()) {
|
||||
alert("회사 ID를 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === 'create' && !isCheckedDuplicate) {
|
||||
alert("회사 ID 중복체크를 해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.cmpnAlias.trim()) {
|
||||
alert("별칭을 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
await onSubmit({
|
||||
...formData,
|
||||
cmpnId: formData.cmpnId.trim(),
|
||||
cmpnAlias: formData.cmpnAlias.trim(),
|
||||
cmpnTel: formData.cmpnTel?.trim(),
|
||||
ownCmpn: mode === 'create' ? false : formData.ownCmpn,
|
||||
memo: formData.memo?.trim(),
|
||||
});
|
||||
handleOpenChange(false);
|
||||
} catch (e) {
|
||||
const err = apiError(e, {
|
||||
fallbackMessage: "Save failed.",
|
||||
});
|
||||
console.error(err.status, err.code, err.message);
|
||||
if (err.code !== NONE_HTTP_ERROR && err.code !== UNKNOWN_HTTP_ERROR) {
|
||||
alert(err.message);
|
||||
} else {
|
||||
alert("저장에 실패했습니다.");
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl">{mode === 'create' ? '회사 등록' : '회사 수정'}</span>}
|
||||
description="회사 정보를 입력해주세요."
|
||||
contentClassName="sm:max-w-[500px] text-sm"
|
||||
bodyClassName="grid gap-4 py-4"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{mode === 'create' ? "등록" : "수정"}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cmpnId">
|
||||
회사 ID<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="cmpnId"
|
||||
placeholder="Enter company ID"
|
||||
value={formData.cmpnId}
|
||||
onChange={(e) => handleInputChange('cmpnId', e.target.value)}
|
||||
disabled={mode === 'edit'}
|
||||
/>
|
||||
{mode === 'create' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCheckDuplicate}
|
||||
disabled={!formData.cmpnId.trim() || isCheckedDuplicate}
|
||||
>
|
||||
{isCheckedDuplicate ? "확인완료" : "중복체크"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cmpnAlias">별칭</Label>
|
||||
<Input
|
||||
id="cmpnAlias"
|
||||
placeholder="Enter alias"
|
||||
value={formData.cmpnAlias ?? ''}
|
||||
onChange={(e) => handleInputChange('cmpnAlias', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cmpnTel">전화번호</Label>
|
||||
<Input
|
||||
id="cmpnTel"
|
||||
placeholder="Enter tel"
|
||||
value={formData.cmpnTel ?? ''}
|
||||
onChange={(e) => handleInputChange('cmpnTel', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="memo">메모</Label>
|
||||
<textarea
|
||||
id="memo"
|
||||
className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
rows={3}
|
||||
placeholder="Enter memo"
|
||||
value={formData.memo ?? ''}
|
||||
onChange={(e) => handleInputChange('memo', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default CmpnUpsertDialog
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Plus, X } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
@@ -107,7 +107,7 @@ const ListBatchEditDialog = ({
|
||||
const handleConfirm = async () => {
|
||||
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
|
||||
if (normalized.length === 0) {
|
||||
alert('일괄 수정할 항목을 입력해 주세요.')
|
||||
alert('일괄 수정할 항목을 입력해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -121,87 +121,86 @@ const ListBatchEditDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[900px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">일괄 수정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-md border px-4 py-3 text-sm">
|
||||
<p className="font-semibold mb-1">적용된 필터</p>
|
||||
<p className="text-muted-foreground">
|
||||
{filterSummary.length > 0 ? filterSummary : '적용된 필터가 없습니다.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
|
||||
<span>헤더</span>
|
||||
<span>수정 값</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="max-h-72 overflow-auto">
|
||||
{rows.map((row) => (
|
||||
<div
|
||||
key={row.id}
|
||||
className="h-12 px-4 border-b last:border-b-0 grid grid-cols-[1fr_2fr_64px] items-center gap-2"
|
||||
>
|
||||
<Select
|
||||
value={String(row.headerId)}
|
||||
onValueChange={(v) => handleChangeHeader(row.id, Number(v))}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="헤더 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{headerOptions.map((option) => (
|
||||
<SelectItem key={option.id} value={String(option.id)}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Input
|
||||
value={row.value}
|
||||
onChange={(e) => handleChangeValue(row.id, e.target.value)}
|
||||
placeholder="수정할 값을 입력해 주세요"
|
||||
/>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleRemoveRow(row.id)}
|
||||
aria-label="행 제거"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
|
||||
<Plus className="w-4 h-4" />
|
||||
행 추가
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">일괄 수정</span>}
|
||||
contentClassName="sm:max-w-[900px]"
|
||||
bodyClassName="space-y-4"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
적용
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="rounded-md border px-4 py-3 text-sm">
|
||||
<p className="font-semibold mb-1">적용된 필터</p>
|
||||
<p className="text-muted-foreground">
|
||||
{filterSummary.length > 0 ? filterSummary : '적용된 필터가 없습니다.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
|
||||
<span>헤더</span>
|
||||
<span>수정 값</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="max-h-72 overflow-auto">
|
||||
{rows.map((row) => (
|
||||
<div
|
||||
key={row.id}
|
||||
className="h-12 px-4 border-b last:border-b-0 grid grid-cols-[1fr_2fr_64px] items-center gap-2"
|
||||
>
|
||||
<Select
|
||||
value={String(row.headerId)}
|
||||
onValueChange={(v) => handleChangeHeader(row.id, Number(v))}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="헤더 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{headerOptions.map((option) => (
|
||||
<SelectItem key={option.id} value={String(option.id)}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Input
|
||||
value={row.value}
|
||||
onChange={(e) => handleChangeValue(row.id, e.target.value)}
|
||||
placeholder="수정할 값을 입력해주세요"
|
||||
/>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleRemoveRow(row.id)}
|
||||
aria-label="행 제거"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
|
||||
<Plus className="w-4 h-4" />
|
||||
행 추가
|
||||
</Button>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,15 +22,15 @@ const ApplyFilterOption = ({ value, onValueChange, idPrefix }: ApplyFilterGroupP
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="selected" id={`${idPrefix}-selected`} />
|
||||
<Label htmlFor={`${idPrefix}-selected`}>선택 항목만</Label>
|
||||
<Label className="text-base" htmlFor={`${idPrefix}-selected`}>선택 항목만</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="filtered" id={`${idPrefix}-filtered`} />
|
||||
<Label htmlFor={`${idPrefix}-filtered`}>필터 적용 대상만</Label>
|
||||
<Label className="text-base" htmlFor={`${idPrefix}-filtered`}>필터 적용 대상만</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="all" id={`${idPrefix}-all`} />
|
||||
<Label htmlFor={`${idPrefix}-all`}>전체 대상</Label>
|
||||
<Label className="text-base" htmlFor={`${idPrefix}-all`}>전체 대상</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Download } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
@@ -57,7 +57,7 @@ const ListDownloadDialog = ({
|
||||
const hasFrom = contactHistoryDateFrom.length > 0
|
||||
const hasTo = contactHistoryDateTo.length > 0
|
||||
if (hasFrom !== hasTo) {
|
||||
alert('조회 기간은 시작일과 종료일을 모두 입력해 주세요.')
|
||||
alert('조회 기간은 시작일과 종료일을 모두 입력해주세요.')
|
||||
return
|
||||
}
|
||||
if (hasFrom && hasTo && contactHistoryDateFrom > contactHistoryDateTo) {
|
||||
@@ -83,51 +83,14 @@ const ListDownloadDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[560px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">{titleMap[mode]}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">조회 기간</p>
|
||||
<KriDateRangePicker
|
||||
value={{ from: contactHistoryDateFrom, to: contactHistoryDateTo }}
|
||||
onChange={(range) => {
|
||||
setContactHistoryDateFrom(range.from)
|
||||
setContactHistoryDateTo(range.to)
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">비워두면 전체 기간으로 다운로드됩니다.</p>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">다운로드 범위</p>
|
||||
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="download-scope-target" />
|
||||
</div>
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">이력 기준</p>
|
||||
<RadioGroup
|
||||
value={contactHistoryType}
|
||||
onValueChange={(v) => setContactHistoryType(v as ContactHistoryDownloadType)}
|
||||
className="flex items-center gap-6 flex-wrap"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="all" id="download-contact-history-all" />
|
||||
<Label htmlFor="download-contact-history-all">전체 이력</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="latest" id="download-contact-history-latest" />
|
||||
<Label htmlFor="download-contact-history-latest">마지막 이력만</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
||||
contentClassName="sm:max-w-[560px]"
|
||||
bodyClassName="space-y-4"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
@@ -135,9 +98,46 @@ const ListDownloadDialog = ({
|
||||
<Download className="w-4 h-4" />
|
||||
다운로드
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">조회 기간</p>
|
||||
<KriDateRangePicker
|
||||
value={{ from: contactHistoryDateFrom, to: contactHistoryDateTo }}
|
||||
onChange={(range) => {
|
||||
setContactHistoryDateFrom(range.from)
|
||||
setContactHistoryDateTo(range.to)
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">비워두면 전체 기간으로 다운로드합니다.</p>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">다운로드 범위</p>
|
||||
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="download-scope-target" />
|
||||
</div>
|
||||
{mode === 'contact-history' ? (
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold">이력 기준</p>
|
||||
<RadioGroup
|
||||
value={contactHistoryType}
|
||||
onValueChange={(v) => setContactHistoryType(v as ContactHistoryDownloadType)}
|
||||
className="flex items-center gap-6 flex-wrap"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="all" id="download-contact-history-all" />
|
||||
<Label className="text-base" htmlFor="download-contact-history-all">전체 이력</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="latest" id="download-contact-history-latest" />
|
||||
<Label className="text-base" htmlFor="download-contact-history-latest">마지막 이력만</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
) : null}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Plus, X } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { FilterHeaderOption, FilterOperator, FilterRow } from '@/types/list'
|
||||
import type { FilterHeaderOption, FilterOperator, FilterRow, FilterValueOption } from '@/types/list'
|
||||
|
||||
export type ListFilterDialogProps = {
|
||||
dialogId?: DialogId
|
||||
@@ -31,12 +31,14 @@ const operatorLabel: Record<FilterOperator, string> = {
|
||||
neq: '다름',
|
||||
contains: '포함',
|
||||
notContains: '포함하지 않음',
|
||||
empty: '값 없음',
|
||||
notEmpty: '값 있음',
|
||||
}
|
||||
|
||||
const createFilterRow = (headerId: number): FilterRow => ({
|
||||
const createFilterRow = (headerId: number, headerOptions: FilterHeaderOption[]): FilterRow => ({
|
||||
id: crypto.randomUUID(),
|
||||
headerId,
|
||||
operator: 'eq',
|
||||
operator: headerOptions.find((option) => option.id === headerId)?.allowedOperators[0] ?? 'eq',
|
||||
textValue: '',
|
||||
multiValues: [],
|
||||
})
|
||||
@@ -54,7 +56,7 @@ const ListFilterDialog = ({
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
const defaultHeaderId = headerOptions[0]?.id ?? 0
|
||||
const defaultHeaderId = headerOptions.find((option) => !option.disabled)?.id ?? 0
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen) return
|
||||
@@ -63,9 +65,9 @@ const ListFilterDialog = ({
|
||||
return
|
||||
}
|
||||
if (defaultHeaderId > 0) {
|
||||
setRows([createFilterRow(defaultHeaderId)])
|
||||
setRows([createFilterRow(defaultHeaderId, headerOptions)])
|
||||
}
|
||||
}, [resolvedOpen, initialRows, defaultHeaderId])
|
||||
}, [resolvedOpen, initialRows, defaultHeaderId, headerOptions])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
@@ -78,7 +80,7 @@ const ListFilterDialog = ({
|
||||
|
||||
const handleAddRow = () => {
|
||||
if (defaultHeaderId <= 0) return
|
||||
setRows((prev) => [...prev, createFilterRow(defaultHeaderId)])
|
||||
setRows((prev) => [...prev, createFilterRow(defaultHeaderId, headerOptions)])
|
||||
}
|
||||
|
||||
const handleRemoveRow = (id: string) => {
|
||||
@@ -89,16 +91,25 @@ const ListFilterDialog = ({
|
||||
setRows((prev) => prev.map((row) => (row.id === id ? updater(row) : row)))
|
||||
}
|
||||
|
||||
const getValueOptions = (headerId: number) => {
|
||||
return headerOptions.find((item) => item.id === headerId)?.values ?? []
|
||||
}
|
||||
const getHeaderOption = (headerId: number) => headerOptions.find((item) => item.id === headerId)
|
||||
|
||||
const getValueOptions = (headerId: number): FilterValueOption[] => getHeaderOption(headerId)?.valueOptions ?? []
|
||||
|
||||
// valueOptions가 undefined면 텍스트 입력 헤더, 빈 배열이면 "목록형인데 현재 선택 가능한 값이 없음"이므로 둘을 구분한다.
|
||||
const isListValueHeader = (headerId: number) => getHeaderOption(headerId)?.valueOptions !== undefined
|
||||
|
||||
const getAllowedOperators = (headerId: number): FilterOperator[] =>
|
||||
getHeaderOption(headerId)?.allowedOperators ?? ['eq', 'neq', 'contains', 'notContains', 'empty', 'notEmpty']
|
||||
|
||||
const isDisabledHeader = (headerId: number) => getHeaderOption(headerId)?.disabled === true
|
||||
|
||||
const serializedRows = useMemo(
|
||||
() =>
|
||||
rows
|
||||
.map((row) => {
|
||||
const hasValueOptions = getValueOptions(row.headerId).length > 0
|
||||
if (hasValueOptions) return row.multiValues.length > 0 ? row : null
|
||||
if (isDisabledHeader(row.headerId)) return null
|
||||
if (row.operator === 'empty' || row.operator === 'notEmpty') return row
|
||||
if (isListValueHeader(row.headerId)) return row.multiValues.length > 0 ? row : null
|
||||
return row.textValue.trim().length > 0 ? row : null
|
||||
})
|
||||
.filter((row): row is FilterRow => row !== null),
|
||||
@@ -107,7 +118,7 @@ const ListFilterDialog = ({
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (serializedRows.length === 0) {
|
||||
alert('필터 조건을 입력해 주세요.')
|
||||
alert('필터 조건을 입력해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -121,141 +132,155 @@ const ListFilterDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[940px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">필터</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr_64px] items-center border-b bg-muted/40 px-4 text-sm font-semibold">
|
||||
<span>헤더</span>
|
||||
<span>비교 연산자</span>
|
||||
<span>값</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="max-h-80 overflow-auto">
|
||||
{rows.map((row) => {
|
||||
const valueOptions = getValueOptions(row.headerId)
|
||||
const listMode = valueOptions.length > 0
|
||||
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="grid min-h-12 grid-cols-[1fr_140px_1.4fr_64px] items-center gap-2 border-b px-4 py-2 last:border-b-0"
|
||||
>
|
||||
<Select
|
||||
value={String(row.headerId)}
|
||||
onValueChange={(value) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
headerId: Number(value),
|
||||
textValue: '',
|
||||
multiValues: [],
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="헤더 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{headerOptions.map((option) => (
|
||||
<SelectItem key={option.id} value={String(option.id)}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select
|
||||
value={row.operator}
|
||||
onValueChange={(value) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
operator: value as FilterOperator,
|
||||
textValue: '',
|
||||
multiValues: [],
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(Object.keys(operatorLabel) as FilterOperator[]).map((operator) => (
|
||||
<SelectItem key={operator} value={operator}>
|
||||
{operatorLabel[operator]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{listMode ? (
|
||||
<KriMultiSelect
|
||||
items={valueOptions}
|
||||
value={row.multiValues}
|
||||
onChange={(values) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
multiValues: values,
|
||||
}))
|
||||
}
|
||||
getValue={(item) => item}
|
||||
getLabel={(item) => item}
|
||||
placeholder="값 선택"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
className="w-full"
|
||||
spanClassName="text-sm"
|
||||
badgeClassName="text-xs"
|
||||
maxCount={2}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
placeholder="검색할 텍스트"
|
||||
value={row.textValue}
|
||||
onChange={(event) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
textValue: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleRemoveRow(row.id)}
|
||||
aria-label="조건 제거"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
조건 추가
|
||||
</Button>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">필터</span>}
|
||||
contentClassName="sm:max-w-[940px]"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
적용
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr_64px] items-center border-b bg-muted px-4 text-sm font-semibold">
|
||||
<span>헤더</span>
|
||||
<span>비교 연산자</span>
|
||||
<span>값</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="max-h-80 overflow-auto">
|
||||
{rows.map((row) => {
|
||||
const valueOptions = getValueOptions(row.headerId)
|
||||
const listMode = isListValueHeader(row.headerId)
|
||||
const disabled = isDisabledHeader(row.headerId)
|
||||
const rowAllowedOperators = getAllowedOperators(row.headerId)
|
||||
const isEmptyOperator = row.operator === 'empty' || row.operator === 'notEmpty'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="grid min-h-12 grid-cols-[1fr_140px_1.4fr_64px] items-center gap-2 border-b px-4 py-2 last:border-b-0"
|
||||
>
|
||||
<Select
|
||||
value={String(row.headerId)}
|
||||
disabled={disabled}
|
||||
onValueChange={(value) => {
|
||||
const nextHeaderId = Number(value)
|
||||
const nextAllowedOperators = getAllowedOperators(nextHeaderId)
|
||||
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
headerId: nextHeaderId,
|
||||
operator: nextAllowedOperators.includes(current.operator)
|
||||
? current.operator
|
||||
: nextAllowedOperators[0] ?? 'eq',
|
||||
textValue: '',
|
||||
multiValues: [],
|
||||
}))
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="헤더 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{headerOptions.map((option) => (
|
||||
<SelectItem key={option.id} value={String(option.id)} disabled={option.disabled}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select
|
||||
value={row.operator}
|
||||
disabled={disabled}
|
||||
onValueChange={(value) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
operator: value as FilterOperator,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{rowAllowedOperators.map((operator) => (
|
||||
<SelectItem key={operator} value={operator}>
|
||||
{operatorLabel[operator]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{isEmptyOperator ? (
|
||||
<Input placeholder="값을 입력할 필요 없음" value="" disabled />
|
||||
) : listMode ? (
|
||||
<KriMultiSelect
|
||||
items={valueOptions}
|
||||
value={row.multiValues}
|
||||
disabled={disabled}
|
||||
onChange={(values) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
multiValues: values,
|
||||
}))
|
||||
}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="값 선택"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
className="w-full"
|
||||
spanClassName="text-sm"
|
||||
badgeClassName="text-xs"
|
||||
maxCount={2}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
placeholder="검색할 텍스트"
|
||||
value={row.textValue}
|
||||
disabled={disabled}
|
||||
onChange={(event) =>
|
||||
handleChangeRow(row.id, (current) => ({
|
||||
...current,
|
||||
textValue: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
disabled={disabled}
|
||||
onClick={() => handleRemoveRow(row.id)}
|
||||
aria-label="조건 제거"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2" disabled={defaultHeaderId <= 0}>
|
||||
<Plus className="h-4 w-4" />
|
||||
조건 추가
|
||||
</Button>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
} from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import { GripVertical, Plus, Trash2 } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -35,6 +35,7 @@ export type ListHeaderManageDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
prjctIdx: number
|
||||
rows: listHeader[]
|
||||
onConfirm: (rows: listHeader[]) => void | Promise<void>
|
||||
}
|
||||
@@ -76,7 +77,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
|
||||
style={style}
|
||||
className={cn(
|
||||
'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2',
|
||||
(activeId === row.listHderId || isDragging) && 'bg-muted/40',
|
||||
(activeId === row.listHderId || isDragging) && 'bg-muted',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center">
|
||||
@@ -173,6 +174,7 @@ const ListHeaderManageDialog = ({
|
||||
dialogId = 'listHeaderManageDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
prjctIdx,
|
||||
rows,
|
||||
onConfirm,
|
||||
}: ListHeaderManageDialogProps) => {
|
||||
@@ -275,6 +277,7 @@ const ListHeaderManageDialog = ({
|
||||
const newIndex = prev.filter((row) => row.listHderNm.startsWith('신규 헤더')).length + 1
|
||||
|
||||
const nextRow: listHeader = {
|
||||
prjctIdx,
|
||||
listHderId: nextId,
|
||||
listHderOrder: prev.length + 1,
|
||||
listHderGrad: ListHeaderGrade.COMMON,
|
||||
@@ -295,6 +298,7 @@ const ListHeaderManageDialog = ({
|
||||
try {
|
||||
const orderedRows = localRows.map((row, index) => ({
|
||||
...row,
|
||||
prjctIdx: row.prjctIdx ?? prjctIdx,
|
||||
listHderOrder: index + 1,
|
||||
}))
|
||||
await onConfirm(orderedRows)
|
||||
@@ -305,13 +309,24 @@ const ListHeaderManageDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[1200px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">리스트 헤더 관리</DialogTitle>
|
||||
</DialogHeader>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">리스트 헤더 관리</span>}
|
||||
contentClassName="sm:max-w-[1200px]"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
저장
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button type="button" className="gap-2 bg-blue" onClick={handleAddHeader} disabled={submitting}>
|
||||
<Plus className="w-4 h-4" />
|
||||
헤더 추가
|
||||
@@ -319,7 +334,7 @@ const ListHeaderManageDialog = ({
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
|
||||
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
|
||||
<span>순서</span>
|
||||
<span>헤더명</span>
|
||||
<span>헤더 타입</span>
|
||||
@@ -355,16 +370,7 @@ const ListHeaderManageDialog = ({
|
||||
</DndContext>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
저장
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
@@ -50,47 +50,46 @@ const ListResetDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[700px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">리스트 초기화</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-2">
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
|
||||
<ApplyFilterOption
|
||||
value={target}
|
||||
onValueChange={(v) => setTarget(v)}
|
||||
idPrefix="list-reset-target"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 범위</p>
|
||||
<RadioGroup value={scope} onValueChange={(v) => setScope(v as ListResetScope)} className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="result-and-history" id="list-reset-scope-result-history" />
|
||||
<Label htmlFor="list-reset-scope-result-history">결과 + 이력 삭제</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="list-only" id="list-reset-scope-list-only" />
|
||||
<Label htmlFor="list-reset-scope-list-only">결과 + 이력 + 리스트 삭제</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">리스트 초기화</span>}
|
||||
contentClassName="sm:max-w-[700px]"
|
||||
bodyClassName="space-y-6 py-2"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting}>
|
||||
초기화
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
|
||||
<ApplyFilterOption
|
||||
value={target}
|
||||
onValueChange={(v) => setTarget(v)}
|
||||
idPrefix="list-reset-target"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-4">
|
||||
<p className="text-lg font-semibold text-red-600">초기화 범위</p>
|
||||
<RadioGroup value={scope} onValueChange={(v) => setScope(v as ListResetScope)} className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="result-and-history" id="list-reset-scope-result-history" />
|
||||
<Label className="text-base" htmlFor="list-reset-scope-result-history">결과 + 이력 삭제</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="list-only" id="list-reset-scope-list-only" />
|
||||
<Label className="text-base" htmlFor="list-reset-scope-list-only">결과 + 이력 + 리스트 삭제</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { ChevronDown, ChevronUp, Download, Upload, X } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Label } from '@/components/ui/label'
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import { KriSelect, KriSelectItem } from '@/components/common/KriSelect'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
@@ -32,6 +33,7 @@ export type ListUploadDialogProps = {
|
||||
}
|
||||
|
||||
const ACCEPT_EXTENSIONS = ['.xlsx', '.xls', '.csv']
|
||||
const FIXED_UPLOAD_MODE = ListUploadMode.ADD_AND_CHANGE
|
||||
|
||||
const ListUploadDialog = ({
|
||||
dialogId = 'listUploadDialog',
|
||||
@@ -50,7 +52,8 @@ const ListUploadDialog = ({
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [excelHeaders, setExcelHeaders] = useState<string[]>([])
|
||||
const [otherHeaderTypeMap, setOtherHeaderTypeMap] = useState<Record<number, ListHeaderType>>({})
|
||||
const [uploadMode, setUploadMode] = useState<ListUploadMode>(ListUploadMode.CHANGE)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [uploadMode, setUploadMode] = useState<ListUploadMode>(ListUploadMode.ADD_AND_CHANGE)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [historyExpanded, setHistoryExpanded] = useState(false)
|
||||
const [validation, setValidation] = useState<ValidationOption>({
|
||||
@@ -91,7 +94,7 @@ const ListUploadDialog = ({
|
||||
setSelectedFile(null)
|
||||
setExcelHeaders([])
|
||||
setOtherHeaderTypeMap({})
|
||||
setUploadMode(ListUploadMode.ADD)
|
||||
setUploadMode(ListUploadMode.ADD_AND_CHANGE)
|
||||
setSubmitting(false)
|
||||
setHistoryExpanded(false)
|
||||
setValidation({
|
||||
@@ -115,10 +118,19 @@ const ListUploadDialog = ({
|
||||
handleOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
const decodeCsvText = (buffer: ArrayBuffer) => {
|
||||
// 한국 Windows 엑셀에서 저장한 CSV는 UTF-8이 아니라 EUC-KR(CP949)인 경우가 많다.
|
||||
try {
|
||||
return new TextDecoder('utf-8', { fatal: true }).decode(buffer)
|
||||
} catch {
|
||||
return new TextDecoder('euc-kr').decode(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
const extractHeaders = async (file: File) => {
|
||||
const lower = file.name.toLowerCase()
|
||||
if (lower.endsWith('.csv')) {
|
||||
const text = await file.text()
|
||||
const text = decodeCsvText(await file.arrayBuffer())
|
||||
const firstLine = text.split(/\r?\n/)[0] ?? ''
|
||||
return firstLine.split(',').map((s) => s.trim()).filter((s) => s.length > 0)
|
||||
}
|
||||
@@ -170,7 +182,7 @@ const ListUploadDialog = ({
|
||||
)
|
||||
|
||||
await onUpload(selectedFile, {
|
||||
uploadMode,
|
||||
uploadMode: FIXED_UPLOAD_MODE,
|
||||
checkDuplicateEmail: validation.checkEmailDuplicate,
|
||||
checkDuplicatePhone: validation.checkPhoneDuplicate,
|
||||
...(Object.keys(specificHeader).length > 0 ? { specificHeader } : {}),
|
||||
@@ -235,168 +247,167 @@ const ListUploadDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogContent className="overflow-hidden" style={{ width: 'min(960px, 95vw)', maxWidth: '95vw' }}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">리스트 업로드</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="min-w-0 space-y-6 py-2">
|
||||
{
|
||||
/*
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 방식</Label>
|
||||
<RadioGroup
|
||||
value={String(uploadMode)}
|
||||
onValueChange={(value) => setUploadMode(Number(value) as ListUploadMode)}
|
||||
className="flex flex-wrap items-center gap-6"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.CHANGE)} id="list-upload-mode-change" />
|
||||
<Label htmlFor="list-upload-mode-change" className="cursor-pointer">
|
||||
전체 교체
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.ADD)} id="list-upload-mode-add" />
|
||||
<Label htmlFor="list-upload-mode-add" className="cursor-pointer">
|
||||
추가
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
*/
|
||||
}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 파일</Label>
|
||||
<div className="min-w-0 flex items-center gap-2">
|
||||
<Button type="button" className="shrink-0 bg-excel text-base" onClick={onDownloadTemplate}>
|
||||
<Download className="w-4 h-4" />
|
||||
양식 다운로드
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-w-0 flex-1 justify-start text-lg"
|
||||
disabled={submitting}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="w-4 h-4 shrink-0" />
|
||||
<span className="min-w-0 truncate">{selectedFile ? selectedFile.name : '업로드 파일을 선택해 주세요.'}</span>
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" size="icon-sm" disabled={!selectedFile || submitting} onClick={resetState} aria-label="선택 파일 제거">
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
<input ref={fileInputRef} type="file" accept={ACCEPT_EXTENSIONS.join(',')} className="hidden" onChange={handleSelectFile} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedFile && excelHeaders.length > 0 && compareRows.length > 0 && (
|
||||
<div className="min-w-0 space-y-3">
|
||||
<Label className="text-lg font-semibold">헤더 비교</Label>
|
||||
<div className="block w-full max-w-full overflow-x-scroll rounded-md border pb-1">
|
||||
<div className="w-max whitespace-nowrap">
|
||||
{headerCompareList.map(({ header, index, isMatched, isSettingRequired, serverHeader }) => {
|
||||
return (
|
||||
<div key={`${header}-${index}`} className="inline-block w-[125px] align-top border-r last:border-r-0">
|
||||
<div className="flex h-8 items-center truncate bg-slate-700 px-2.5 text-sm font-medium text-slate-50">
|
||||
{header || `컬럼${index + 1}`}
|
||||
</div>
|
||||
<div className="flex h-9 items-center border-t px-2">
|
||||
{renderHeaderTypeCell(serverHeader, isMatched, isSettingRequired, index)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">중복 검증</Label>
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="list-upload-email-dup"
|
||||
checked={validation.checkEmailDuplicate}
|
||||
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkEmailDuplicate: checked === true }))}
|
||||
/>
|
||||
<Label htmlFor="list-upload-email-dup" className="cursor-pointer">
|
||||
이메일 중복검증
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="list-upload-phone-dup"
|
||||
checked={validation.checkPhoneDuplicate}
|
||||
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkPhoneDuplicate: checked === true }))}
|
||||
/>
|
||||
<Label htmlFor="list-upload-phone-dup" className="cursor-pointer">
|
||||
전화번호 중복검증
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border">
|
||||
<button type="button" className="flex h-11 w-full items-center justify-between border-b px-4 text-left" onClick={() => setHistoryExpanded((prev) => !prev)}>
|
||||
<span className="text-lg font-semibold">업로드 이력({normalizedHistory.length} 회)</span>
|
||||
{historyExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
</button>
|
||||
{historyExpanded && (
|
||||
<div className="h-[160px] overflow-y-auto">
|
||||
<table className="w-full text-base">
|
||||
<thead className="sticky top-0 border-b bg-white">
|
||||
<tr>
|
||||
<th className="h-9 px-3 text-center">회차</th>
|
||||
<th className="h-9 px-3 text-center">파일명</th>
|
||||
<th className="h-9 px-3 text-center">사용자 ID</th>
|
||||
<th className="h-9 px-3 text-center">업로드 건수</th>
|
||||
<th className="h-9 px-3 text-center">업로드 일시</th>
|
||||
<th className="h-9 px-3 text-center">다운로드</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{normalizedHistory.length === 0 && (
|
||||
<tr>
|
||||
<td className="h-12 px-3 text-center text-muted-foreground" colSpan={6}>
|
||||
업로드 이력이 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{normalizedHistory.map((item) => (
|
||||
<tr key={item.listUploadLogId} className="border-b last:border-b-0">
|
||||
<td className="h-10 px-3 text-center">{item.wave}</td>
|
||||
<td className="h-10 px-3 text-center">{item.fileName}</td>
|
||||
<td className="h-10 px-3 text-center">{item.regUser}</td>
|
||||
<td className="h-10 px-3 text-center">{item.listCount.toLocaleString()}</td>
|
||||
<td className="h-10 px-3 text-center">{item.uploadAtLabel}</td>
|
||||
<td className="h-10 px-3 text-center">
|
||||
<Button type="button" size="sm" className="bg-excel" onClick={() => onDownloadHistory?.(item)}>
|
||||
<Download className="h-4 w-4" />
|
||||
다운로드
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
title={<span className="text-2xl font-bold">리스트 업로드</span>}
|
||||
contentClassName="w-[min(960px,95vw)] max-w-[95vw] sm:max-w-[min(960px,95vw)] overflow-hidden"
|
||||
bodyClassName="min-w-0 space-y-6 py-2"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleDialogOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch}>
|
||||
{submitting ? '업로드 중...' : '업로드'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{
|
||||
/*
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 방식</Label>
|
||||
<RadioGroup
|
||||
value={String(uploadMode)}
|
||||
onValueChange={(value) => setUploadMode(Number(value) as ListUploadMode)}
|
||||
className="flex flex-wrap items-center gap-6"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.CHANGE)} id="list-upload-mode-change" />
|
||||
<Label htmlFor="list-upload-mode-change" className="cursor-pointer">
|
||||
전체 교체
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value={String(ListUploadMode.ADD)} id="list-upload-mode-add" />
|
||||
<Label htmlFor="list-upload-mode-add" className="cursor-pointer">
|
||||
추가
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
*/
|
||||
}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">업로드 파일</Label>
|
||||
<div className="min-w-0 flex items-center gap-2">
|
||||
<Button type="button" className="shrink-0 bg-excel text-base" onClick={onDownloadTemplate}>
|
||||
<Download className="w-4 h-4" />
|
||||
양식 다운로드
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-w-0 flex-1 justify-start text-lg"
|
||||
disabled={submitting}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="w-4 h-4 shrink-0" />
|
||||
<span className="min-w-0 truncate text-sm">{selectedFile ? selectedFile.name : '업로드 파일을 선택해 주세요.'}</span>
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" size="icon-sm" disabled={!selectedFile || submitting} onClick={resetState} aria-label="선택 파일 제거">
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
<input ref={fileInputRef} type="file" accept={ACCEPT_EXTENSIONS.join(',')} className="hidden" onChange={handleSelectFile} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedFile && excelHeaders.length > 0 && compareRows.length > 0 && (
|
||||
<div className="min-w-0 space-y-3">
|
||||
<Label className="text-lg font-semibold">헤더 비교</Label>
|
||||
<div className="block w-full max-w-full overflow-x-scroll rounded-md border pb-1">
|
||||
<div className="w-max whitespace-nowrap">
|
||||
{headerCompareList.map(({ header, index, isMatched, isSettingRequired, serverHeader }) => {
|
||||
return (
|
||||
<div key={`${header}-${index}`} className="inline-block w-[125px] align-top border-r last:border-r-0">
|
||||
<div className="flex h-8 items-center truncate bg-slate-700 px-2.5 text-sm font-medium text-slate-50">
|
||||
{header || `컬럼${index + 1}`}
|
||||
</div>
|
||||
<div className="flex h-9 items-center border-t px-2">
|
||||
{renderHeaderTypeCell(serverHeader, isMatched, isSettingRequired, index)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">중복 검증</Label>
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="list-upload-email-dup"
|
||||
checked={validation.checkEmailDuplicate}
|
||||
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkEmailDuplicate: checked === true }))}
|
||||
/>
|
||||
<Label htmlFor="list-upload-email-dup" className="cursor-pointer text-base">
|
||||
이메일 중복검증
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="list-upload-phone-dup"
|
||||
checked={validation.checkPhoneDuplicate}
|
||||
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkPhoneDuplicate: checked === true }))}
|
||||
/>
|
||||
<Label htmlFor="list-upload-phone-dup" className="cursor-pointer text-base">
|
||||
전화번호 중복검증
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border">
|
||||
<button type="button" className="flex h-11 w-full items-center justify-between border-b px-4 text-left" onClick={() => setHistoryExpanded((prev) => !prev)}>
|
||||
<span className="text-lg font-semibold">업로드 이력({normalizedHistory.length} 회)</span>
|
||||
{historyExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
</button>
|
||||
{historyExpanded && (
|
||||
<div className="h-[160px] overflow-y-auto">
|
||||
<table className="w-full text-base">
|
||||
<thead className="sticky top-0 border-b bg-white">
|
||||
<tr>
|
||||
<th className="h-9 px-3 text-center">회차</th>
|
||||
<th className="h-9 px-3 text-center">파일명</th>
|
||||
<th className="h-9 px-3 text-center">사용자 ID</th>
|
||||
<th className="h-9 px-3 text-center">업로드 건수</th>
|
||||
<th className="h-9 px-3 text-center">업로드 일시</th>
|
||||
<th className="h-9 px-3 text-center">다운로드</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{normalizedHistory.length === 0 && (
|
||||
<tr>
|
||||
<td className="h-12 px-3 text-center text-muted-foreground" colSpan={6}>
|
||||
업로드 이력이 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{normalizedHistory.map((item) => (
|
||||
<tr key={item.listUploadLogId} className="border-b last:border-b-0">
|
||||
<td className="h-10 px-3 text-center">{item.wave}</td>
|
||||
<td className="h-10 px-3 text-center">{item.fileName}</td>
|
||||
<td className="h-10 px-3 text-center">{item.regUser}</td>
|
||||
<td className="h-10 px-3 text-center">{item.listCount.toLocaleString()}</td>
|
||||
<td className="h-10 px-3 text-center">{item.uploadAtLabel}</td>
|
||||
<td className="h-10 px-3 text-center">
|
||||
<Button type="button" size="sm" className="bg-excel" onClick={() => onDownloadHistory?.(item)}>
|
||||
<Download className="h-4 w-4" />
|
||||
다운로드
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,39 +1,28 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DataTable } from '@/components/data-table/DataTable'
|
||||
import type { DataTableColumn } from '@/components/data-table/DataTable.type'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||
import { useBulkSendDetailExcelMutation, useBulkSendDetailQuery, useBulkSendListQuery } from '@/query/message'
|
||||
import { MessageType } from '@kri/common/noti-hub'
|
||||
import { downloadBase64File, XLSX_MIME_TYPE } from '@kri/common/browser'
|
||||
import { formatKst } from '@kri/common'
|
||||
import type { PaginationState } from '@tanstack/react-table'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { BulkSendInfo } from '@kri/common/noti-hub'
|
||||
import type { SendResultInfo } from '@/types/message'
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
|
||||
export type MessageHistoryType = 'sms' | 'email'
|
||||
export type MessageHistoryDetailType = 'template' | 'target' | 'success' | 'fail' | null
|
||||
|
||||
export type MessageHistoryRow = {
|
||||
id: number
|
||||
type: MessageHistoryType
|
||||
title: string
|
||||
templateName: string
|
||||
sendInfo: string
|
||||
targetHeader: string
|
||||
targetCount: number
|
||||
successCount: number
|
||||
failCount: number
|
||||
createdAt: string
|
||||
sendAt: string
|
||||
status: string
|
||||
templatePreview?: string
|
||||
targetPreview?: string[]
|
||||
successPreview?: string[]
|
||||
failPreview?: string[]
|
||||
}
|
||||
|
||||
export type MessageHistoryDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
rows: MessageHistoryRow[]
|
||||
onDownload?: (row: MessageHistoryRow, detailType: Exclude<MessageHistoryDetailType, null>) => void | Promise<void>
|
||||
}
|
||||
|
||||
const tabLabelMap: Record<MessageHistoryType, string> = {
|
||||
@@ -41,26 +30,64 @@ const tabLabelMap: Record<MessageHistoryType, string> = {
|
||||
email: '이메일',
|
||||
}
|
||||
|
||||
const historyColumns: DataTableColumn<BulkSendInfo>[] = [
|
||||
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
||||
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
||||
{ id: 'resve', header: '구분', accessorFn: (row) => (row.resve ? '예약' : '즉시') },
|
||||
{ id: 'trgtCnt', header: '대상수', accessorFn: (row) => row.trgtCnt.toLocaleString() },
|
||||
{ id: 'sendCnt', header: '발송수', accessorFn: (row) => row.sendCnt.toLocaleString() },
|
||||
{ id: 'succesCnt', header: '성공', accessorFn: (row) => row.succesCnt.toLocaleString() },
|
||||
{ id: 'failCnt', header: '실패', accessorFn: (row) => row.failCnt.toLocaleString() },
|
||||
{ id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') },
|
||||
{ id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' },
|
||||
]
|
||||
|
||||
const detailColumns: DataTableColumn<SendResultInfo>[] = [
|
||||
{ id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || row.destTel || '-' },
|
||||
{ id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' },
|
||||
{ id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || row.sendTel || '-' },
|
||||
{ id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) },
|
||||
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
||||
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
||||
]
|
||||
|
||||
const MessageHistoryDialog = ({
|
||||
dialogId = 'messageHistoryDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
rows,
|
||||
onDownload,
|
||||
}: MessageHistoryDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const { selectedProject } = useSelectedProject()
|
||||
const [tab, setTab] = useState<MessageHistoryType>('sms')
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null)
|
||||
const [detailType, setDetailType] = useState<MessageHistoryDetailType>(null)
|
||||
const [selectedKey, setSelectedKey] = useState<string | null>(null)
|
||||
const [detailPagination, setDetailPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 })
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
const prjctCd = selectedProject?.prjctCd ?? ''
|
||||
const enabled = resolvedOpen && !!prjctCd
|
||||
|
||||
const visibleRows = useMemo(() => rows.filter((row) => row.type === tab), [rows, tab])
|
||||
const emailListQuery = useBulkSendListQuery(MessageType.EMAIL, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'email')
|
||||
const smsListQuery = useBulkSendListQuery(MessageType.SMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
|
||||
const lmsListQuery = useBulkSendListQuery(MessageType.LMS_MMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
|
||||
|
||||
const selectedRow = useMemo(
|
||||
() => visibleRows.find((row) => row.id === selectedId) ?? null,
|
||||
[visibleRows, selectedId],
|
||||
const visibleRows = useMemo(() => {
|
||||
if (tab === 'email') return emailListQuery.data ?? []
|
||||
return [...(smsListQuery.data ?? []), ...(lmsListQuery.data ?? [])].sort((a, b) =>
|
||||
(b.regDt ?? '').localeCompare(a.regDt ?? ''),
|
||||
)
|
||||
}, [tab, emailListQuery.data, smsListQuery.data, lmsListQuery.data])
|
||||
|
||||
const detailQuery = useBulkSendDetailQuery(
|
||||
selectedKey ?? '',
|
||||
{
|
||||
pageIndex: detailPagination.pageIndex,
|
||||
pageSize: detailPagination.pageSize,
|
||||
sortBy: 'regDt',
|
||||
sortDir: 'desc',
|
||||
},
|
||||
enabled && !!selectedKey,
|
||||
)
|
||||
const detailExcelMutation = useBulkSendDetailExcelMutation()
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
@@ -69,142 +96,85 @@ const MessageHistoryDialog = ({
|
||||
return
|
||||
}
|
||||
hideDialog(dialogId)
|
||||
setSelectedId(null)
|
||||
setDetailType(null)
|
||||
setSelectedKey(null)
|
||||
}
|
||||
|
||||
const handlePickDetail = (rowId: number, nextType: Exclude<MessageHistoryDetailType, null>) => {
|
||||
setSelectedId(rowId)
|
||||
setDetailType(nextType)
|
||||
const handleSelectTab = (nextTab: MessageHistoryType) => {
|
||||
setTab(nextTab)
|
||||
setSelectedKey(null)
|
||||
}
|
||||
|
||||
const detailContent = useMemo(() => {
|
||||
if (!selectedRow || !detailType) return null
|
||||
if (detailType === 'template') return selectedRow.templatePreview ?? '(미리보기 데이터 없음)'
|
||||
if (detailType === 'target') return (selectedRow.targetPreview ?? []).join('\n')
|
||||
if (detailType === 'success') return (selectedRow.successPreview ?? []).join('\n')
|
||||
if (detailType === 'fail') return (selectedRow.failPreview ?? []).join('\n')
|
||||
return null
|
||||
}, [selectedRow, detailType])
|
||||
const handleSelectRow = (row: BulkSendInfo) => {
|
||||
setSelectedKey(row.bulkSendKey)
|
||||
setDetailPagination({ pageIndex: 0, pageSize: 10 })
|
||||
}
|
||||
|
||||
const handleDownloadDetail = async () => {
|
||||
if (!selectedKey) return
|
||||
const result = await detailExcelMutation.mutateAsync(selectedKey)
|
||||
if (!result.fileBase64) {
|
||||
alert('다운로드할 데이터가 없습니다.')
|
||||
return
|
||||
}
|
||||
downloadBase64File(result.fileBase64, result.fileName, XLSX_MIME_TYPE)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[1200px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">발송 이력</DialogTitle>
|
||||
</DialogHeader>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">발송 이력</span>}
|
||||
contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto"
|
||||
closeLabel="닫기"
|
||||
bodyClassName="space-y-4"
|
||||
>
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => handleSelectTab('sms')}>
|
||||
{tabLabelMap.sms}
|
||||
</Button>
|
||||
<Button type="button" variant={tab === 'email' ? 'default' : 'outline'} onClick={() => handleSelectTab('email')}>
|
||||
{tabLabelMap.email}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => setTab('sms')}>
|
||||
{tabLabelMap.sms}
|
||||
</Button>
|
||||
<Button type="button" variant={tab === 'email' ? 'default' : 'outline'} onClick={() => setTab('email')}>
|
||||
{tabLabelMap.email}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<DataTable<BulkSendInfo>
|
||||
columns={historyColumns}
|
||||
data={visibleRows}
|
||||
getRowId={(row) => row.bulkSendKey}
|
||||
isClient
|
||||
selectMode="click-event"
|
||||
onRowClick={handleSelectRow}
|
||||
highlightRowIds={selectedKey ? [selectedKey] : []}
|
||||
emptyText="발송 이력이 없습니다."
|
||||
pageSizeOptions={[5, 10, 20]}
|
||||
defaultPageSize={5}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-[1.7fr_1fr] gap-4">
|
||||
<div className="rounded-md border overflow-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-white border-b">
|
||||
<tr>
|
||||
<th className="px-2 h-9 text-left">회차</th>
|
||||
<th className="px-2 h-9 text-left">제목</th>
|
||||
<th className="px-2 h-9 text-left">템플릿</th>
|
||||
<th className="px-2 h-9 text-left">발송 정보</th>
|
||||
<th className="px-2 h-9 text-left">타겟 헤더</th>
|
||||
<th className="px-2 h-9 text-right">대상수</th>
|
||||
<th className="px-2 h-9 text-right">성공</th>
|
||||
<th className="px-2 h-9 text-right">실패</th>
|
||||
<th className="px-2 h-9 text-left">등록 일시</th>
|
||||
<th className="px-2 h-9 text-left">발송 일시</th>
|
||||
<th className="px-2 h-9 text-left">상태</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visibleRows.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={11} className="h-12 text-center text-muted-foreground">
|
||||
발송 이력이 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{visibleRows.map((row) => (
|
||||
<tr key={`${row.type}-${row.id}`} className="border-b last:border-b-0">
|
||||
<td className="px-2 h-10">{row.id}</td>
|
||||
<td className="px-2 h-10">{row.title}</td>
|
||||
<td className="px-2 h-10">
|
||||
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'template')}>
|
||||
{row.templateName}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2 h-10">{row.sendInfo}</td>
|
||||
<td className="px-2 h-10">
|
||||
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'target')}>
|
||||
{row.targetHeader}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2 h-10 text-right">{row.targetCount}</td>
|
||||
<td className="px-2 h-10 text-right">
|
||||
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'success')}>
|
||||
{row.successCount}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2 h-10 text-right">
|
||||
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'fail')}>
|
||||
{row.failCount}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2 h-10">{row.createdAt}</td>
|
||||
<td className="px-2 h-10">{row.sendAt}</td>
|
||||
<td className="px-2 h-10">{row.status}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-3 min-h-80">
|
||||
<p className="text-lg font-semibold">
|
||||
{detailType === null && '상세 이력'}
|
||||
{detailType === 'template' && '미리보기'}
|
||||
{detailType === 'target' && '수신 대상'}
|
||||
{detailType === 'success' && '성공 이력'}
|
||||
{detailType === 'fail' && '실패 이력'}
|
||||
</p>
|
||||
|
||||
{detailType === null && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
템플릿, 대상수, 성공, 실패 항목을 선택하면 상세 영역이 열립니다.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{detailType !== null && (
|
||||
<>
|
||||
<pre className="rounded border p-3 text-sm whitespace-pre-wrap min-h-56">{detailContent}</pre>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (!selectedRow || !detailType) return
|
||||
onDownload?.(selectedRow, detailType)
|
||||
}}
|
||||
disabled={!selectedRow || !detailType || !onDownload}
|
||||
>
|
||||
다운로드
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{selectedKey && (
|
||||
<div className="rounded-md border p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-lg font-semibold">상세 이력</p>
|
||||
<Button type="button" variant="outline" onClick={handleDownloadDetail} disabled={detailExcelMutation.isPending}>
|
||||
다운로드
|
||||
</Button>
|
||||
</div>
|
||||
<DataTable<SendResultInfo>
|
||||
columns={detailColumns}
|
||||
data={detailQuery.data?.content ?? []}
|
||||
getRowId={(row) => row.cmid}
|
||||
isClient={false}
|
||||
pageCount={detailQuery.data?.totalPages ?? 0}
|
||||
totalCount={detailQuery.data?.totalElements ?? 0}
|
||||
pagination={detailPagination}
|
||||
onPaginationChange={setDetailPagination}
|
||||
emptyText="상세 이력이 없습니다."
|
||||
pageSizeOptions={[10, 20, 30]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" onClick={() => handleOpenChange(false)}>
|
||||
닫기
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,60 +1,54 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||
import { useListSearchQuery } from '@/query/list'
|
||||
import {
|
||||
useCreateBulkSendKeyMutation,
|
||||
useMainTemplateIdxQuery,
|
||||
useSendBulkMutation,
|
||||
useTemplateListQuery,
|
||||
useTemplateQuery,
|
||||
} from '@/query/message'
|
||||
import {ChannelType, type DestInfo, TemplateSms, type TemplateSummary} from '@kri/common/noti-hub'
|
||||
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import { createEmptyListFilter, type ListFilter, type ListFilterTarget, type listHeader } from '@/types/list'
|
||||
import { ListHeaderConst } from '@/const/listConst'
|
||||
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import ApplyFilterOption from './ListDialogOption/ApplyFilterOption'
|
||||
import {KriEditor} from "@/components/kri-editor";
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
|
||||
export type MessageSendMode = 'email' | 'sms'
|
||||
export type ScheduleType = 'instant' | 'reserve'
|
||||
|
||||
export type MessageTemplateOption = {
|
||||
id: string
|
||||
name: string
|
||||
title: string
|
||||
body: string
|
||||
}
|
||||
const MAX_TARGET_COUNT = 5000
|
||||
|
||||
export type MessageSendHeaderOption = {
|
||||
id: number
|
||||
label: string
|
||||
}
|
||||
|
||||
export type MessageSendPayload = {
|
||||
mode: MessageSendMode
|
||||
templateId: string
|
||||
senderEmail: string
|
||||
senderName: string
|
||||
senderNumber: string
|
||||
title: string
|
||||
body: string
|
||||
scheduleType: ScheduleType
|
||||
reserveAt?: string
|
||||
targetHeaderId: number
|
||||
}
|
||||
const toTargetRow = (row: ListTableRow): { sid: string; itemList: Record<number, string> } => ({
|
||||
sid: String(row.sid ?? ''),
|
||||
itemList: (row.itemList as Record<number, string> | undefined) ?? {},
|
||||
})
|
||||
|
||||
export type MessageSendDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
mode: MessageSendMode
|
||||
templateOptions: MessageTemplateOption[]
|
||||
targetHeaderOptions: MessageSendHeaderOption[]
|
||||
defaultSenderEmail?: string
|
||||
defaultSenderName?: string
|
||||
defaultSenderNumber?: string
|
||||
onConfirm: (payload: MessageSendPayload) => void | Promise<void>
|
||||
listHeaders: listHeader[]
|
||||
currentFilter: ListFilter
|
||||
selectedRows: ListTableRow[]
|
||||
onSent?: () => void
|
||||
}
|
||||
|
||||
const titleMap: Record<MessageSendMode, string> = {
|
||||
@@ -67,45 +61,105 @@ const MessageSendDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
mode,
|
||||
templateOptions,
|
||||
targetHeaderOptions,
|
||||
defaultSenderEmail = '',
|
||||
defaultSenderName = '',
|
||||
defaultSenderNumber = '',
|
||||
onConfirm,
|
||||
listHeaders,
|
||||
currentFilter,
|
||||
selectedRows,
|
||||
onSent,
|
||||
}: MessageSendDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const [templateId, setTemplateId] = useState('')
|
||||
const [title, setTitle] = useState('')
|
||||
const [body, setBody] = useState('')
|
||||
const [senderEmail, setSenderEmail] = useState(defaultSenderEmail)
|
||||
const [senderName, setSenderName] = useState(defaultSenderName)
|
||||
const [senderNumber, setSenderNumber] = useState(defaultSenderNumber)
|
||||
const [scheduleType, setScheduleType] = useState<ScheduleType>('instant')
|
||||
const { auth } = useAuth()
|
||||
const { selectedProject } = useSelectedProject()
|
||||
|
||||
const chnnlTy = mode === 'email' ? ChannelType.EMAIL : ChannelType.SMS
|
||||
|
||||
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
|
||||
const [senderEmail, setSenderEmail] = useState('')
|
||||
const [senderName, setSenderName] = useState('')
|
||||
const [senderNumber, setSenderNumber] = useState('')
|
||||
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
|
||||
const [reserveAt, setReserveAt] = useState('')
|
||||
const [targetHeaderId, setTargetHeaderId] = useState<number>(targetHeaderOptions[0]?.id ?? 0)
|
||||
const [targetHeaderId, setTargetHeaderId] = useState<number | null>(null)
|
||||
const [target, setTarget] = useState<ListFilterTarget>('selected')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
|
||||
const selectedTemplate = useMemo(
|
||||
() => templateOptions.find((template) => template.id === templateId),
|
||||
[templateId, templateOptions],
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
||||
const prjctCd = selectedProject?.prjctCd ?? ''
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? ''
|
||||
const enabled = resolvedOpen && !!selectedProject && prjctIdx > 0
|
||||
|
||||
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled)
|
||||
const templateList: TemplateSummary[] = templateListQuery.data ?? []
|
||||
const templateDetailQuery = useTemplateQuery(templateIdx ?? 0, enabled && !!templateIdx)
|
||||
const selectedTemplate = templateDetailQuery.data ?? null
|
||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
||||
const mainTemplateIdx = mainTemplateQuery.data ?? null
|
||||
|
||||
const headerType = mode === 'email' ? ListHeaderConst.EMAIL : ListHeaderConst.TEL_NUM
|
||||
const targetHeaderOptions = useMemo(
|
||||
() => listHeaders.filter((header) => header.listHderTy === headerType),
|
||||
[listHeaders, headerType],
|
||||
)
|
||||
|
||||
// '전체'/'필터 적용 대상'은 현재 페이지에 보이는 행을 넘어설 수 있어 별도로 넓게 조회한다
|
||||
const bulkTargetFilter = target === 'all' ? createEmptyListFilter() : currentFilter
|
||||
const bulkTargetEnabled = enabled && target !== 'selected'
|
||||
const bulkTargetQuery = useListSearchQuery(
|
||||
prjctIdx,
|
||||
{
|
||||
listFilter: bulkTargetFilter,
|
||||
pageRequest: { pageIndex: 0, pageSize: MAX_TARGET_COUNT, sortBy: 'sid', sortDir: 'asc' },
|
||||
},
|
||||
bulkTargetEnabled,
|
||||
)
|
||||
|
||||
const targetRows = useMemo(() => {
|
||||
const rows = target === 'selected' ? selectedRows : (bulkTargetQuery.data?.content ?? [])
|
||||
return rows.map(toTargetRow)
|
||||
}, [target, selectedRows, bulkTargetQuery.data])
|
||||
|
||||
const targetTotalCount = target === 'selected' ? selectedRows.length : (bulkTargetQuery.data?.totalElements ?? 0)
|
||||
const isTargetTruncated = target !== 'selected' && targetTotalCount > MAX_TARGET_COUNT
|
||||
|
||||
const createBulkKeyMutation = useCreateBulkSendKeyMutation(mode)
|
||||
const sendBulkMutation = useSendBulkMutation(mode)
|
||||
|
||||
const mainTemplateAppliedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen) return
|
||||
const firstTemplate = templateOptions[0]
|
||||
setTemplateId(firstTemplate?.id ?? '')
|
||||
setTitle(firstTemplate?.title ?? '')
|
||||
setBody(firstTemplate?.body ?? '')
|
||||
setTemplateIdx(null)
|
||||
setSenderEmail('')
|
||||
setSenderName('')
|
||||
setSenderNumber('')
|
||||
setScheduleType('instant')
|
||||
setReserveAt('')
|
||||
setTargetHeaderId(targetHeaderOptions[0]?.id ?? 0)
|
||||
setSenderEmail(defaultSenderEmail)
|
||||
setSenderName(defaultSenderName)
|
||||
setSenderNumber(defaultSenderNumber)
|
||||
}, [resolvedOpen, templateOptions, targetHeaderOptions, defaultSenderEmail, defaultSenderName, defaultSenderNumber])
|
||||
setTarget('selected')
|
||||
setTargetHeaderId(null)
|
||||
mainTemplateAppliedRef.current = false
|
||||
}, [resolvedOpen])
|
||||
|
||||
// 대표 템플릿이 있으면 최초 1회 자동 선택
|
||||
useEffect(() => {
|
||||
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return
|
||||
mainTemplateAppliedRef.current = true
|
||||
if (mainTemplateIdx) setTemplateIdx(mainTemplateIdx)
|
||||
}, [enabled, mainTemplateQuery.isSuccess, mainTemplateIdx])
|
||||
|
||||
// 템플릿 상세가 도착하면 발신 정보를 세팅한다 (발송 전 수정 가능)
|
||||
useEffect(() => {
|
||||
if (!selectedTemplate) return
|
||||
setSenderName(selectedTemplate.sendNm)
|
||||
if ('sendEml' in selectedTemplate) setSenderEmail(selectedTemplate.sendEml)
|
||||
if ('sendTel' in selectedTemplate) setSenderNumber(selectedTemplate.sendTel)
|
||||
}, [selectedTemplate])
|
||||
|
||||
useEffect(() => {
|
||||
if (targetHeaderId !== null) return
|
||||
const first = targetHeaderOptions[0]
|
||||
if (first) setTargetHeaderId(first.listHderId)
|
||||
}, [targetHeaderOptions, targetHeaderId])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
@@ -116,175 +170,235 @@ const MessageSendDialog = ({
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
|
||||
const handleTemplateChange = (nextTemplateId: string) => {
|
||||
const template = templateOptions.find((item) => item.id === nextTemplateId)
|
||||
setTemplateId(nextTemplateId)
|
||||
if (!template) return
|
||||
setTitle(template.title)
|
||||
setBody(template.body)
|
||||
const handleScheduleTypeChange = (next: 'instant' | 'reserve') => {
|
||||
setScheduleType(next)
|
||||
if (next === 'reserve' && !reserveAt) {
|
||||
setReserveAt(getNearestFutureDateTime())
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectTemplate = (value: string) => {
|
||||
const idx = Number(value)
|
||||
setTemplateIdx(Number.isFinite(idx) && idx > 0 ? idx : null)
|
||||
}
|
||||
|
||||
const buildMsgParam = (itemList: Record<number, string>): Record<string, string> => {
|
||||
const param: Record<string, string> = {}
|
||||
listHeaders.forEach((header) => {
|
||||
const value = itemList[header.listHderId]
|
||||
if (value !== undefined) param[header.listHderNm] = value
|
||||
})
|
||||
return param
|
||||
}
|
||||
|
||||
const buildDestInfoList = (): DestInfo[] => {
|
||||
if (!targetHeaderId) return []
|
||||
return targetRows.map(({ sid, itemList }) => {
|
||||
const destValue = itemList[targetHeaderId] ?? ''
|
||||
return {
|
||||
sid,
|
||||
destEml: mode === 'email' ? destValue : undefined,
|
||||
destTel: mode === 'sms' ? destValue : undefined,
|
||||
msgParam: buildMsgParam(itemList),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!templateId) {
|
||||
if (!selectedTemplate || !templateIdx) {
|
||||
alert('템플릿을 선택해 주세요.')
|
||||
return
|
||||
}
|
||||
if (!title.trim() || !body.trim()) {
|
||||
alert('제목과 내용을 입력해 주세요.')
|
||||
if (!targetHeaderId) {
|
||||
alert(`수신 ${mode === 'email' ? '이메일' : '번호'} 헤더를 선택해 주세요.`)
|
||||
return
|
||||
}
|
||||
if (mode === 'email' && !senderEmail.trim()) {
|
||||
alert('발송자 메일을 입력해 주세요.')
|
||||
return
|
||||
}
|
||||
if (mode === 'sms' && !senderNumber.trim()) {
|
||||
alert('발송 번호를 입력해 주세요.')
|
||||
return
|
||||
}
|
||||
if (mode === 'email' && (!senderEmail.trim() || !senderName.trim())) {
|
||||
alert('발송자 정보를 입력해 주세요.')
|
||||
return
|
||||
}
|
||||
if (scheduleType === 'reserve' && !reserveAt) {
|
||||
alert('예약 발송 일시를 선택해 주세요.')
|
||||
return
|
||||
}
|
||||
if (isTargetTruncated) {
|
||||
alert(`수신 대상이 ${MAX_TARGET_COUNT}건을 초과합니다. 대상 범위를 좁혀 주세요.`)
|
||||
return
|
||||
}
|
||||
const destInfoList = buildDestInfoList()
|
||||
if (destInfoList.length === 0) {
|
||||
alert('수신 대상이 없습니다.')
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await onConfirm({
|
||||
mode,
|
||||
templateId,
|
||||
senderEmail,
|
||||
senderName,
|
||||
senderNumber,
|
||||
title,
|
||||
body,
|
||||
scheduleType,
|
||||
reserveAt: scheduleType === 'reserve' ? reserveAt : undefined,
|
||||
targetHeaderId,
|
||||
const bulkSendKey = await createBulkKeyMutation.mutateAsync({
|
||||
reqstCmpn: auth.user?.userCmpn ?? '',
|
||||
reqstUser: auth.user?.userId ?? '',
|
||||
reqstSvc: clientEnv.REQUEST_SVC,
|
||||
prjctCd,
|
||||
tmplatIdx: templateIdx,
|
||||
resve: scheduleType === 'reserve',
|
||||
sendDt: scheduleType === 'reserve' ? new Date(reserveAt).toISOString() : undefined,
|
||||
trgtCnt: destInfoList.length,
|
||||
})
|
||||
|
||||
await sendBulkMutation.mutateAsync({
|
||||
sendEml: mode === 'email' ? senderEmail : undefined,
|
||||
sendTel: mode === 'sms' ? senderNumber : undefined,
|
||||
sendNm: senderName || undefined,
|
||||
bulkSendKey,
|
||||
destInfoList,
|
||||
})
|
||||
|
||||
alert('발송 요청이 완료되었습니다.')
|
||||
onSent?.()
|
||||
handleOpenChange(false)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert('발송 중 오류가 발생했습니다.')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[980px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">{titleMap[mode]}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-lg font-semibold">템플릿</Label>
|
||||
<Select value={templateId} onValueChange={handleTemplateChange}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="템플릿을 선택해 주세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{templateOptions.map((template) => (
|
||||
<SelectItem key={template.id} value={template.id}>
|
||||
{template.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{mode === 'email' ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label>발송자 메일</Label>
|
||||
<Input value={senderEmail} onChange={(e) => setSenderEmail(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>발송자 이름</Label>
|
||||
<Input value={senderName} onChange={(e) => setSenderName(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label>발송 번호</Label>
|
||||
<Input value={senderNumber} onChange={(e) => setSenderNumber(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{mode === 'email' ? '메일 제목' : '문자 제목'}</Label>
|
||||
<Input value={title} onChange={(e) => setTitle(e.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{mode === 'email' ? '메일 내용' : '문자 내용'}</Label>
|
||||
<textarea
|
||||
className="w-full min-h-36 rounded-md border px-3 py-2 text-sm resize-y"
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>수신 대상 헤더</Label>
|
||||
<Select value={String(targetHeaderId)} onValueChange={(v) => setTargetHeaderId(Number(v))}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{targetHeaderOptions.map((header) => (
|
||||
<SelectItem key={header.id} value={String(header.id)}>
|
||||
{header.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>발송 일시</Label>
|
||||
<RadioGroup
|
||||
value={scheduleType}
|
||||
onValueChange={(v) => setScheduleType(v as ScheduleType)}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="instant" id="message-send-instant" />
|
||||
<Label htmlFor="message-send-instant">즉시</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="reserve" id="message-send-reserve" />
|
||||
<Label htmlFor="message-send-reserve">예약</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
{scheduleType === 'reserve' && (
|
||||
<Input type="datetime-local" value={reserveAt} onChange={(e) => setReserveAt(e.target.value)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-2">
|
||||
<p className="text-lg font-semibold">미리보기</p>
|
||||
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
|
||||
{selectedTemplate && (
|
||||
<>
|
||||
<div className="rounded border p-2 text-sm font-semibold">{title || '(제목 없음)'}</div>
|
||||
<div className="rounded border p-3 text-sm whitespace-pre-wrap min-h-72">
|
||||
{body || '(내용 없음)'}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
||||
contentClassName="sm:max-w-[1100px] max-h-[90vh] overflow-y-auto"
|
||||
bodyClassName="grid grid-cols-1 lg:grid-cols-2 gap-6"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
발송
|
||||
{submitting ? '발송 중...' : '발송'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">템플릿을 선택해 주세요</Label>
|
||||
<KriSingleSelect
|
||||
items={templateList}
|
||||
value={String(templateIdx ?? '')}
|
||||
onChange={handleSelectTemplate}
|
||||
placeholder="템플릿을 선택해 주세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
getLabel={(item) => item.tmplatNm}
|
||||
getValue={(item) => String(item.tmplatIdx)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{mode === 'email' ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">발송자 메일</Label>
|
||||
<Input value={senderEmail} onChange={(e) => setSenderEmail(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">발송자 이름</Label>
|
||||
<Input value={senderName} onChange={(e) => setSenderName(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">발송 번호</Label>
|
||||
<Input value={senderNumber} onChange={(e) => setSenderNumber(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">발송 일시</Label>
|
||||
<RadioGroup
|
||||
value={scheduleType}
|
||||
onValueChange={(v) => handleScheduleTypeChange(v as 'instant' | 'reserve')}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2 cursor-pointer">
|
||||
<RadioGroupItem value="instant" id="message-send-instant" />
|
||||
<Label htmlFor="message-send-instant">즉시</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 cursor-pointer">
|
||||
<RadioGroupItem value="reserve" id="message-send-reserve" />
|
||||
<Label htmlFor="message-send-reserve">예약</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
{scheduleType === 'reserve' && (
|
||||
<KriDateTimePicker value={reserveAt} onChange={setReserveAt} placeholder="예약 일시 선택" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">수신 {mode === 'email' ? '이메일' : '번호'} 헤더</Label>
|
||||
<KriSingleSelect
|
||||
items={targetHeaderOptions}
|
||||
value={String(targetHeaderId ?? '')}
|
||||
onChange={(value) => setTargetHeaderId(Number(value) || null)}
|
||||
placeholder={`수신 ${mode === 'email' ? '이메일' : '번호'}로 사용할 헤더를 선택해 주세요`}
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
getLabel={(item) => item.listHderNm}
|
||||
getValue={(item) => String(item.listHderId)}
|
||||
/>
|
||||
{targetHeaderOptions.length === 0 && (
|
||||
<p className="text-sm text-red-600">
|
||||
{mode === 'email' ? '이메일' : '전화번호'} 타입의 리스트 헤더가 없습니다. 헤더 관리에서 먼저 설정해 주세요.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-md border p-4">
|
||||
<Label className="text-base">수신 대상</Label>
|
||||
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="message-send-target" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
대상 {targetTotalCount.toLocaleString()}건
|
||||
{isTargetTruncated ? ` (최대 ${MAX_TARGET_COUNT.toLocaleString()}건까지만 발송 가능합니다)` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-4 space-y-2">
|
||||
<p className="text-lg font-semibold">미리보기</p>
|
||||
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
|
||||
{selectedTemplate && (
|
||||
<>
|
||||
{chnnlTy !== ChannelType.SMS && (
|
||||
<div className="rounded border p-2 text-lg font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
|
||||
)}
|
||||
{chnnlTy === ChannelType.SMS ? (
|
||||
<div className="flex flex-col items-center">
|
||||
<KriEditor
|
||||
mode="sms"
|
||||
value={(selectedTemplate as TemplateSms).tmplatBody ?? ""}
|
||||
onChange={() => {}}
|
||||
isSmsReadOnly
|
||||
placeholder="문자 내용을 입력해 주세요"
|
||||
className="max-w-80 mx-0"
|
||||
debounceMs={600}
|
||||
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cn('rounded-md border bg-muted/30 p-3')}
|
||||
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import {useState, useEffect, useMemo} from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from "@/components/ui/dialog";
|
||||
import { KriDialog } from "@/components/common/KriDialog";
|
||||
import {Label} from "@/components/ui/label";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {Button} from "@/components/ui/button";
|
||||
@@ -21,7 +14,7 @@ import {ProjectCreateRequest} from "@/types/project";
|
||||
import { useDebouncedValue } from "@kri/common/hooks";
|
||||
import {PROJECT_NAME_REGEX} from "@/const/projectConst";
|
||||
import {FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {useIntranetProjectListQuery} from "@/query/intranet";
|
||||
|
||||
@@ -165,15 +158,32 @@ const ProjectCreateDialog = ({
|
||||
}, [users]);
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px] text-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-xl">
|
||||
프로젝트 생성
|
||||
</DialogTitle>
|
||||
<DialogDescription>프로젝트 생성에 필요한 기본 정보를 입력해주세요.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-6 py-4">
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl">프로젝트 생성</span>}
|
||||
description="프로젝트 생성에 필요한 기본 정보를 입력해주세요."
|
||||
contentClassName="sm:max-w-[500px] text-sm"
|
||||
bodyClassName="grid gap-6 py-4"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
생성
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-2">
|
||||
<Label>
|
||||
인트라넷 프로젝트<span className="text-red-500 ml-1">*</span>
|
||||
@@ -230,25 +240,7 @@ const ProjectCreateDialog = ({
|
||||
widthClassName="w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
생성
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
91
src/components/dialog/ReservationListDialog.tsx
Normal file
91
src/components/dialog/ReservationListDialog.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
'use client'
|
||||
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { ListReserve } from '@/types/list'
|
||||
import { formatKst } from '@kri/common'
|
||||
|
||||
export type ReservationListDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
reservations: ListReserve[]
|
||||
onSelectReservation: (sid: string) => void
|
||||
}
|
||||
|
||||
// 오늘과 가장 가까운(과거/미래 무관) 예약의 sid를 찾는다.
|
||||
export const findClosestReservationSid = (reservations: ListReserve[], now: Date = new Date()): number | null => {
|
||||
if (reservations.length === 0) return null
|
||||
|
||||
return reservations.reduce((closest, current) => {
|
||||
const closestDiff = Math.abs(new Date(closest.resveDt).getTime() - now.getTime())
|
||||
const currentDiff = Math.abs(new Date(current.resveDt).getTime() - now.getTime())
|
||||
return currentDiff < closestDiff ? current : closest
|
||||
}, reservations[0]).sid
|
||||
}
|
||||
|
||||
const ReservationListDialog = ({
|
||||
dialogId = 'reservationListDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
reservations,
|
||||
onSelectReservation,
|
||||
}: ReservationListDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
const closestSid = findClosestReservationSid(reservations)
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId)
|
||||
return
|
||||
}
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
|
||||
const handleSelect = (sid: number) => {
|
||||
onSelectReservation(String(sid))
|
||||
handleOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl">예약리스트 조회</span>}
|
||||
contentClassName="sm:max-w-[480px]"
|
||||
showDefaultFooter
|
||||
>
|
||||
<div className="max-h-80 overflow-auto rounded-md border">
|
||||
{reservations.length === 0 ? (
|
||||
<div className="p-6 text-center text-sm text-muted-foreground">예약된 리스트가 없습니다.</div>
|
||||
) : (
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-muted">
|
||||
<tr>
|
||||
<th className="p-2 text-left">SID</th>
|
||||
<th className="p-2 text-left">예약 일시</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{reservations.map((item) => (
|
||||
<tr
|
||||
key={item.listResveIdx}
|
||||
className={`cursor-pointer border-t hover:bg-muted/50 ${item.sid === closestSid ? 'bg-accent' : ''}`}
|
||||
onClick={() => handleSelect(item.sid)}
|
||||
>
|
||||
<td className="p-2">{item.sid}</td>
|
||||
<td className="p-2">{formatKst(item.resveDt, 'dateHourMin')}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default ReservationListDialog
|
||||
@@ -1,13 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useMemo, useState} from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {Trash2, Plus, Download} from 'lucide-react'
|
||||
@@ -77,6 +71,7 @@ const ResultCodeDialog = ({
|
||||
resultCdTy: resultCodeType,
|
||||
resultCd: lastCode + 1,
|
||||
resultCdLbl: '',
|
||||
isDefault: false,
|
||||
}
|
||||
])
|
||||
}
|
||||
@@ -220,23 +215,46 @@ const ResultCodeDialog = ({
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<KriDialog
|
||||
open={open ?? false}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) handleClose()
|
||||
}}
|
||||
title={<div className="text-2xl font-bold">결과 코드 설정</div>}
|
||||
contentClassName={[
|
||||
'overflow-hidden',
|
||||
'transition-all duration-200',
|
||||
importMode ? 'sm:max-w-6xl' : 'sm:max-w-3xl',
|
||||
'w-[calc(100vw-2rem)]',
|
||||
'max-h-[85vh]',
|
||||
'gap-2',
|
||||
].join(' ')}
|
||||
bodyClassName="min-h-0 p-0"
|
||||
footerClassName="px-6 py-4 border-t bg-white"
|
||||
footer={
|
||||
importMode ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={handleImportCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleImportApply} disabled={!importProject} className="gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
가져오기 적용
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
>
|
||||
{/* importMode일 때 더 넓게(그리고 애니메이션으로 부드럽게) */}
|
||||
<DialogContent
|
||||
className={[
|
||||
'p-0 overflow-hidden',
|
||||
'transition-all duration-200',
|
||||
importMode ? 'sm:max-w-6xl' : 'sm:max-w-3xl',
|
||||
'w-[calc(100vw-2rem)]',
|
||||
'max-h-[85vh]',
|
||||
'gap-2',
|
||||
].join(' ')}
|
||||
>
|
||||
<DialogHeader className="px-6 pt-6 pb-4 border-b">
|
||||
<DialogTitle className="flex items-center justify-between gap-3">
|
||||
<span>결과 코드 설정</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 상단 버튼 영역 */}
|
||||
<div className="px-6 pt-1 pb-3 border-b bg-white flex justify-end">
|
||||
@@ -272,7 +290,7 @@ const ResultCodeDialog = ({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="px-6 pt-4 flex flex-wrap items-center gap-2">
|
||||
<div className="px-6 py-2 flex flex-wrap items-center gap-1">
|
||||
{RESULT_CODE_TYPE_OPTIONS
|
||||
.filter((opt) => opt.value !== ResultCodeType.SURVEY)
|
||||
.map((opt) => (
|
||||
@@ -315,7 +333,9 @@ const ResultCodeDialog = ({
|
||||
<tbody className="divide-y">
|
||||
{resultCodeArray
|
||||
.filter((rc) => rc.resultCdTy === resultCodeType)
|
||||
.map((code, index) => (
|
||||
.map((code, index) => {
|
||||
const isLocked = code.isDefault;
|
||||
return (
|
||||
<tr key={index} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-2 align-middle">
|
||||
<Input
|
||||
@@ -323,7 +343,7 @@ const ResultCodeDialog = ({
|
||||
onChange={(e) => handleCodeChange(code.resultCdUUID, 'resultCd', e.target.value)}
|
||||
onBlur={(e) => checkDuplicate(code.resultCdUUID, Number(e.target.value), e.target)}
|
||||
className="h-9"
|
||||
disabled={importMode}
|
||||
disabled={importMode || isLocked}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-4 py-2 align-middle">
|
||||
@@ -331,15 +351,15 @@ const ResultCodeDialog = ({
|
||||
value={code.resultCdLbl}
|
||||
onChange={(e) => handleCodeChange(code.resultCdUUID, 'resultCdLbl', e.target.value)}
|
||||
className="h-9"
|
||||
disabled={importMode}
|
||||
disabled={importMode || isLocked}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-2 py-2 align-middle">
|
||||
{!importMode && (
|
||||
{!importMode && !isLocked && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleDeleteCode(index)}
|
||||
onClick={() => handleDeleteCode(code.resultCd)}
|
||||
aria-label="delete"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 text-red-600" />
|
||||
@@ -347,7 +367,8 @@ const ResultCodeDialog = ({
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -398,30 +419,7 @@ const ResultCodeDialog = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="px-6 py-4 border-t bg-white">
|
||||
{importMode ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={handleImportCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleImportApply} disabled={!importProject} className="gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
가져오기 적용
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
230
src/components/dialog/SingleMessageSendDialog.tsx
Normal file
230
src/components/dialog/SingleMessageSendDialog.tsx
Normal file
@@ -0,0 +1,230 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import {
|
||||
useMainTemplateIdxQuery,
|
||||
useSendSingleMessageMutation,
|
||||
useTemplateListQuery,
|
||||
useTemplateQuery,
|
||||
} from '@/query/message'
|
||||
import { ChannelType, type TemplateSms, type TemplateSummary } from '@kri/common/noti-hub'
|
||||
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
|
||||
import { KriEditor } from '@/components/kri-editor'
|
||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { MessageSendChannel } from '@/types/message'
|
||||
|
||||
const titleMap: Record<MessageSendChannel, string> = {
|
||||
email: '메일 발송',
|
||||
sms: '문자 발송',
|
||||
}
|
||||
|
||||
export type SingleMessageSendDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
channel: MessageSendChannel
|
||||
prjctIdx: number
|
||||
itrntPrjctCd: string
|
||||
sid: string
|
||||
destHeaderId: number
|
||||
onSent?: () => void
|
||||
}
|
||||
|
||||
const SingleMessageSendDialog = ({
|
||||
dialogId = 'singleMessageSendDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
channel,
|
||||
prjctIdx,
|
||||
itrntPrjctCd,
|
||||
sid,
|
||||
destHeaderId,
|
||||
onSent,
|
||||
}: SingleMessageSendDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
|
||||
const chnnlTy = channel === 'email' ? ChannelType.EMAIL : ChannelType.SMS
|
||||
|
||||
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
|
||||
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
|
||||
const [reserveAt, setReserveAt] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const enabled = resolvedOpen && !!itrntPrjctCd
|
||||
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled)
|
||||
const templateList: TemplateSummary[] = templateListQuery.data ?? []
|
||||
const templateDetailQuery = useTemplateQuery(templateIdx ?? 0, enabled && !!templateIdx)
|
||||
const selectedTemplate = templateDetailQuery.data ?? null
|
||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
||||
const mainTemplateIdx = mainTemplateQuery.data ?? null
|
||||
|
||||
const sendSingleMutation = useSendSingleMessageMutation(channel, prjctIdx)
|
||||
|
||||
const mainTemplateAppliedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen) return
|
||||
setTemplateIdx(null)
|
||||
setScheduleType('instant')
|
||||
setReserveAt('')
|
||||
mainTemplateAppliedRef.current = false
|
||||
}, [resolvedOpen])
|
||||
|
||||
// 대표 템플릿이 있으면 최초 1회 자동 선택
|
||||
useEffect(() => {
|
||||
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return
|
||||
mainTemplateAppliedRef.current = true
|
||||
if (mainTemplateIdx) setTemplateIdx(mainTemplateIdx)
|
||||
}, [enabled, mainTemplateQuery.isSuccess, mainTemplateIdx])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId)
|
||||
return
|
||||
}
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
|
||||
const handleScheduleTypeChange = (next: 'instant' | 'reserve') => {
|
||||
setScheduleType(next)
|
||||
if (next === 'reserve' && !reserveAt) {
|
||||
setReserveAt(getNearestFutureDateTime())
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectTemplate = (value: string) => {
|
||||
const idx = Number(value)
|
||||
setTemplateIdx(Number.isFinite(idx) && idx > 0 ? idx : null)
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!templateIdx) {
|
||||
alert('템플릿을 선택해 주세요.')
|
||||
return
|
||||
}
|
||||
if (scheduleType === 'reserve' && !reserveAt) {
|
||||
alert('예약 발송 일시를 선택해 주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await sendSingleMutation.mutateAsync({
|
||||
tmplatIdx: templateIdx,
|
||||
resve: scheduleType === 'reserve',
|
||||
sendDt: scheduleType === 'reserve' ? new Date(reserveAt).toISOString() : undefined,
|
||||
sid: Number(sid),
|
||||
destHeaderIds: [destHeaderId],
|
||||
})
|
||||
|
||||
alert('발송 요청이 완료되었습니다.')
|
||||
onSent?.()
|
||||
handleOpenChange(false)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert('발송 중 오류가 발생했습니다.')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl font-bold">{titleMap[channel]}</span>}
|
||||
contentClassName="sm:max-w-[900px] max-h-[90vh] overflow-y-auto"
|
||||
bodyClassName="grid grid-cols-1 lg:grid-cols-2 gap-6"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
||||
{submitting ? '발송 중...' : '발송'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">템플릿을 선택해 주세요</Label>
|
||||
<KriSingleSelect
|
||||
items={templateList}
|
||||
value={String(templateIdx ?? '')}
|
||||
onChange={handleSelectTemplate}
|
||||
placeholder="템플릿을 선택해 주세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
getLabel={(item) => item.tmplatNm}
|
||||
getValue={(item) => String(item.tmplatIdx)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">발송 일시</Label>
|
||||
<RadioGroup
|
||||
value={scheduleType}
|
||||
onValueChange={(v) => handleScheduleTypeChange(v as 'instant' | 'reserve')}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2 cursor-pointer">
|
||||
<RadioGroupItem value="instant" id="single-send-instant" />
|
||||
<Label htmlFor="single-send-instant">즉시</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 cursor-pointer">
|
||||
<RadioGroupItem value="reserve" id="single-send-reserve" />
|
||||
<Label htmlFor="single-send-reserve">예약</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
{scheduleType === 'reserve' && (
|
||||
<KriDateTimePicker value={reserveAt} onChange={setReserveAt} placeholder="예약 일시 선택" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-md border p-4">
|
||||
<p className="text-sm font-semibold">미리보기</p>
|
||||
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
|
||||
{selectedTemplate && (
|
||||
<>
|
||||
{chnnlTy !== ChannelType.SMS && (
|
||||
<div className="rounded border p-2 text-sm font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
|
||||
)}
|
||||
{chnnlTy === ChannelType.SMS ? (
|
||||
<div className="flex flex-col items-center">
|
||||
<KriEditor
|
||||
mode="sms"
|
||||
value={(selectedTemplate as TemplateSms).tmplatBody ?? ''}
|
||||
onChange={() => {}}
|
||||
isSmsReadOnly
|
||||
placeholder="문자 내용을 입력해 주세요"
|
||||
className="max-w-80 mx-0"
|
||||
debounceMs={600}
|
||||
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="rounded-md border bg-muted/30 p-3 text-sm"
|
||||
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default SingleMessageSendDialog
|
||||
69
src/components/dialog/SurveyQrDialog.tsx
Normal file
69
src/components/dialog/SurveyQrDialog.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { toDataURL } from 'qrcode'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
|
||||
export type SurveyQrDialogProps = {
|
||||
dialogId?: DialogId
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
url: string
|
||||
}
|
||||
|
||||
const SurveyQrDialog = ({ dialogId = 'surveyQrDialog', open, onOpenChange, url }: SurveyQrDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null)
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId)
|
||||
return
|
||||
}
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen || !url) {
|
||||
setQrDataUrl(null)
|
||||
return
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
toDataURL(url, { width: 240 }).then((dataUrl) => {
|
||||
if (!cancelled) setQrDataUrl(dataUrl)
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [resolvedOpen, url])
|
||||
|
||||
return (
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl">설문 QR코드</span>}
|
||||
contentClassName="sm:max-w-[360px]"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-3 py-4">
|
||||
{qrDataUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={qrDataUrl} alt="설문 QR코드" width={240} height={240} />
|
||||
) : (
|
||||
<div className="flex h-[240px] w-[240px] items-center justify-center text-sm text-muted-foreground">
|
||||
QR코드 생성 중...
|
||||
</div>
|
||||
)}
|
||||
<p className="break-all text-center text-xs text-muted-foreground">{url}</p>
|
||||
</div>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default SurveyQrDialog
|
||||
@@ -1,12 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useState, useRef } from 'react'
|
||||
import {Download, Upload, X} from 'lucide-react'
|
||||
@@ -117,13 +111,20 @@ const UserUploadDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className=" text-2xl font-bold">User upload</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-4">
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
title={<span className="text-2xl font-bold">User upload</span>}
|
||||
contentClassName="sm:max-w-[600px]"
|
||||
bodyClassName="space-y-6 py-4"
|
||||
footer={
|
||||
<div className="flex items-center justify-end w-full gap-2">
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting}>
|
||||
확인
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
@@ -165,17 +166,7 @@ const UserUploadDialog = ({
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<div className="flex items-center justify-end w-full gap-2">
|
||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting}>
|
||||
확인
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,20 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import { UserInfoSaveRequest } from '@/types/user'
|
||||
import KriPassword from "@/components/common/KriPassword";
|
||||
import KriPassword, { KRI_PW_REGEX } from "@/components/common/KriPassword";
|
||||
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
|
||||
import {DataVerification} from "@/types/common";
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import {apiError} from "@kri/common/http";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
import {FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {CONTACT_INTERVIEWER_ROLE, FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@kri/common/http";
|
||||
import type { CmpnInfo } from "@/types/cmpn";
|
||||
|
||||
export type UserUpsertDialogProps = {
|
||||
/** Jotai로 관리할 다이얼로그 ID */
|
||||
@@ -35,7 +28,7 @@ export type UserUpsertDialogProps = {
|
||||
initialData?: Partial<UserInfoSaveRequest>
|
||||
isInternal: boolean
|
||||
userCmpn: string
|
||||
userCmpnArray: string[]
|
||||
userCmpnArray: CmpnInfo[]
|
||||
userRoleArray: KriSelectItem[]
|
||||
onSubmit: (data: UserInfoSaveRequest) => void | Promise<void>
|
||||
onCheckDuplicate?: (userId: string) => DataVerification | Promise<DataVerification>
|
||||
@@ -47,7 +40,6 @@ const UserUpsertDialog = ({
|
||||
onOpenChange,
|
||||
mode = 'create',
|
||||
initialData,
|
||||
isInternal,
|
||||
userCmpn,
|
||||
userCmpnArray,
|
||||
userRoleArray,
|
||||
@@ -60,7 +52,7 @@ const UserUpsertDialog = ({
|
||||
userName: '',
|
||||
userCmpn: userCmpn,
|
||||
userTeam: '',
|
||||
userRole: 9002,
|
||||
userRole: CONTACT_INTERVIEWER_ROLE,
|
||||
memo: '',
|
||||
}
|
||||
|
||||
@@ -102,7 +94,7 @@ const UserUpsertDialog = ({
|
||||
}
|
||||
}, [initialData, mode, resolvedOpen])
|
||||
|
||||
const handleInputChange = (field: keyof UserInfoSaveRequest, value: any) => {
|
||||
const handleInputChange = <K extends keyof UserInfoSaveRequest>(field: K, value: UserInfoSaveRequest[K]) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
@@ -146,6 +138,10 @@ const UserUpsertDialog = ({
|
||||
alert("비밀번호를 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
if (!KRI_PW_REGEX.test(formData.userPw)) {
|
||||
alert("비밀번호는 영문과 숫자를 포함한 8~20자로 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
if (!formData.userName.trim()) {
|
||||
alert("이름을 입력해주세요.");
|
||||
return;
|
||||
@@ -179,15 +175,32 @@ const UserUpsertDialog = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px] text-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-xl">
|
||||
{mode === 'create' ? '계정 등록' : '계정 수정'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>면접원 계정 정보를 입력해주세요.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<KriDialog
|
||||
open={resolvedOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={<span className="text-xl">{mode === 'create' ? '계정 등록' : '계정 수정'}</span>}
|
||||
description="면접원 계정 정보를 입력해주세요."
|
||||
contentClassName="sm:max-w-[500px] text-sm"
|
||||
bodyClassName="grid gap-4 py-4"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{mode === 'create' ? "등록" : "수정"}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="userId">
|
||||
ID<span className="text-red-500 ml-1">*</span>
|
||||
@@ -217,6 +230,7 @@ const UserUpsertDialog = ({
|
||||
</Label>
|
||||
<KriPassword
|
||||
id="password"
|
||||
label=""
|
||||
value={formData.userPw}
|
||||
onChange={(v) => handleInputChange('userPw', v)}
|
||||
placeholder="Enter password"
|
||||
@@ -235,45 +249,35 @@ const UserUpsertDialog = ({
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>계정 권한</Label>
|
||||
<KriSingleSelect
|
||||
<KriSelect
|
||||
items={userRoleArray}
|
||||
value={String(formData.userRole)}
|
||||
getLabel={(item) => item.label}
|
||||
getValue={(item) => String(item.value)}
|
||||
onChange={(e) => {
|
||||
if(mode !== 'create'){
|
||||
alert("권한이 변경되면 해당 계정에 배정된 리스트 정보가 초기화됩니다.");
|
||||
}
|
||||
|
||||
handleInputChange('userRole', Number(e));
|
||||
}}
|
||||
getLabel={(item) => item.label}
|
||||
getValue={(item) => String(item.value)}
|
||||
placeholder="사용자 권한"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
useAll={false}
|
||||
className="w-full min-w-0 overflow-hidden [&>span]:truncate"
|
||||
heightClassName="h-8"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>소속 회사</Label>
|
||||
{
|
||||
isInternal && formData.userRole > 9000 ?
|
||||
<KriSingleSelect
|
||||
items={userCmpnArray}
|
||||
value={formData.userCmpn}
|
||||
onChange={(e) => handleInputChange('userCmpn', e)}
|
||||
placeholder="소속 회사"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
:
|
||||
<Input
|
||||
id="userCmpn"
|
||||
placeholder="Enter company"
|
||||
value={formData.userCmpn}
|
||||
disabled={!isInternal}
|
||||
onChange={(e) => handleInputChange('userCmpn', e.target.value)}
|
||||
/>
|
||||
}
|
||||
|
||||
<KriSelect
|
||||
items={userCmpnArray}
|
||||
value={formData.userCmpn}
|
||||
getValue={(item) => item.cmpnId}
|
||||
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||
onChange={(e) => handleInputChange('userCmpn', e)}
|
||||
useAll={false}
|
||||
disabled={mode !== 'create'}
|
||||
className="w-full min-w-0 overflow-hidden [&>span]:truncate"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="memo">메모</Label>
|
||||
@@ -284,25 +288,7 @@ const UserUpsertDialog = ({
|
||||
onChange={(e) => handleInputChange('memo', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{mode === 'create' ? "등록" : "수정"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</KriDialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -5,20 +5,20 @@ import { KriEditorHtmlOnly } from "./KriEditorHtmlOnly";
|
||||
import { KriEditorWysiwyg } from "./KriEditorWysiwyg";
|
||||
import {KriEditorSms} from "./KriEditorSms";
|
||||
|
||||
function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode {
|
||||
return mode ?? editorMode ?? "wysiwyg";
|
||||
function resolveMode(mode?: KriEditorMode): KriEditorMode {
|
||||
return mode ?? "wysiwyg";
|
||||
}
|
||||
|
||||
export function KriEditor(props: KriEditorProps) {
|
||||
const mode = resolveMode(props.mode, props.editorMode);
|
||||
const mode = resolveMode(props.mode);
|
||||
|
||||
if (mode === "html") {
|
||||
return <KriEditorHtmlOnly {...props} mode={mode} editorMode={mode} />;
|
||||
return <KriEditorHtmlOnly {...props} mode={mode} />;
|
||||
}
|
||||
|
||||
if(mode === "sms") {
|
||||
return <KriEditorSms {...props} mode={mode} editorMode={mode} />
|
||||
return <KriEditorSms {...props} mode={mode} />;
|
||||
}
|
||||
|
||||
return <KriEditorWysiwyg {...props} mode={mode} editorMode={mode} />;
|
||||
return <KriEditorWysiwyg {...props} mode={mode} />;
|
||||
}
|
||||
|
||||
@@ -1,244 +1,158 @@
|
||||
"use client";
|
||||
'use client'
|
||||
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { cn } from "@kri/common/ui";
|
||||
import * as React from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { KriEditorProps } from './types'
|
||||
import { resolveUploadUrl } from './types'
|
||||
import { compressImage } from './utils/imageCompression'
|
||||
import { useDebouncedChange } from './hooks/useDebouncedChange'
|
||||
import { sanitizeHtmlForPreview } from './utils/sanitizeHtml'
|
||||
import { useTextareaInsert } from './hooks/useTextareaInsert'
|
||||
|
||||
import type { KriEditorProps } from "./types";
|
||||
import { compressImage } from "./utils/imageCompression";
|
||||
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
||||
import { sanitizeHtmlForPreview } from "./utils/sanitizeHtml";
|
||||
import {useCallback} from "react";
|
||||
import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
||||
type HtmlOnlyProps = Omit<KriEditorProps, 'mode'> & { mode: 'html' }
|
||||
|
||||
type HtmlOnlyProps = Omit<KriEditorProps, "mode"> & {
|
||||
mode: "html";
|
||||
};
|
||||
export function KriEditorHtmlOnly({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = 'HTML을 입력하세요...',
|
||||
className,
|
||||
showPreview,
|
||||
previewClassName,
|
||||
rows = 14,
|
||||
debounceMs = 350,
|
||||
onImageUpload,
|
||||
onImageUploadError,
|
||||
maxImageBytes = 5 * 1024 * 1024,
|
||||
imageMaxWidth = 1600,
|
||||
imageMaxHeight = 1600,
|
||||
imageQuality = 0.82,
|
||||
imageMimeType = 'image/webp',
|
||||
onEditorReady,
|
||||
onCommandReady,
|
||||
}: HtmlOnlyProps) {
|
||||
const [html, setHtml] = React.useState(value || '')
|
||||
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
|
||||
const fileRef = React.useRef<HTMLInputElement | null>(null)
|
||||
const latestHtmlRef = React.useRef(html)
|
||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
|
||||
const textareaInsert = useTextareaInsert(textareaRef)
|
||||
|
||||
export function KriEditorHtmlOnly(props: HtmlOnlyProps) {
|
||||
const {
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "HTML을 입력하세요...",
|
||||
className,
|
||||
showPreview,
|
||||
previewClassName,
|
||||
rows = 14,
|
||||
debounceMs = 350,
|
||||
const commitHtml = React.useCallback((next: string, immediate = false) => {
|
||||
setHtml(next)
|
||||
latestHtmlRef.current = next
|
||||
if (immediate) flushChange(next)
|
||||
else scheduleChange(next)
|
||||
}, [flushChange, scheduleChange])
|
||||
|
||||
onImageUpload,
|
||||
onImageUploadError,
|
||||
maxImageBytes = 5 * 1024 * 1024,
|
||||
imageMaxWidth = 1600,
|
||||
imageMaxHeight = 1600,
|
||||
imageQuality = 0.82,
|
||||
imageMimeType = "image/webp",
|
||||
} = props;
|
||||
|
||||
const [html, setHtml] = React.useState<string>(value || "");
|
||||
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null);
|
||||
const fileRef = React.useRef<HTMLInputElement | null>(null);
|
||||
const latestHtmlRef = React.useRef(html);
|
||||
|
||||
const canImageUpload = Boolean(onImageUpload);
|
||||
|
||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs);
|
||||
const ti = useTextareaInsert(textareaRef);
|
||||
|
||||
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const next = e.target.value;
|
||||
setHtml(next);
|
||||
latestHtmlRef.current = next;
|
||||
scheduleChange(next);
|
||||
};
|
||||
|
||||
const handleBlur = () => {
|
||||
flushChange(latestHtmlRef.current);
|
||||
};
|
||||
|
||||
const handlePickImage = useCallback(() => {
|
||||
if (!canImageUpload) return;
|
||||
fileRef.current?.click();
|
||||
}, [canImageUpload]);
|
||||
|
||||
const handleFile = useCallback(
|
||||
async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
try {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
|
||||
if (!canImageUpload || !onImageUpload) return;
|
||||
|
||||
if (!file.type.startsWith("image/")) {
|
||||
toast.error("이미지 파일만 업로드할 수 있습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
const compressed = await compressImage(file, {
|
||||
maxBytes: maxImageBytes,
|
||||
maxWidth: imageMaxWidth,
|
||||
maxHeight: imageMaxHeight,
|
||||
mimeType: imageMimeType,
|
||||
quality: imageQuality,
|
||||
});
|
||||
|
||||
if (compressed.size > maxImageBytes) {
|
||||
toast.error("이미지 용량이 제한을 초과합니다.", {
|
||||
description: `최대 ${(maxImageBytes / (1024 * 1024)).toFixed(0)}MB`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const { url } = await onImageUpload(compressed);
|
||||
|
||||
if (!url || typeof url !== "string") {
|
||||
toast.error("이미지 업로드 응답이 올바르지 않습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
setHtml((prev) => {
|
||||
const current = prev ?? "";
|
||||
const textarea = textareaRef.current;
|
||||
const imgTag = `<img src="${url}" alt="" />`;
|
||||
|
||||
if (!textarea) {
|
||||
const next = current + imgTag;
|
||||
latestHtmlRef.current = next;
|
||||
scheduleChange(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
const { selectionStart, selectionEnd } = textarea;
|
||||
const before = current.slice(0, selectionStart);
|
||||
const after = current.slice(selectionEnd);
|
||||
const next = before + imgTag + after;
|
||||
|
||||
latestHtmlRef.current = next;
|
||||
scheduleChange(next);
|
||||
|
||||
// 커서 위치를 이미지 태그 뒤로 이동
|
||||
window.requestAnimationFrame(() => {
|
||||
const pos = before.length + imgTag.length;
|
||||
textarea.focus();
|
||||
textarea.setSelectionRange(pos, pos);
|
||||
});
|
||||
|
||||
return next;
|
||||
});
|
||||
} catch (err) {
|
||||
toast.error("이미지 업로드에 실패했습니다.");
|
||||
console.error(err);
|
||||
}
|
||||
},
|
||||
[
|
||||
scheduleChange,
|
||||
setHtml,
|
||||
canImageUpload,
|
||||
onImageUpload,
|
||||
maxImageBytes,
|
||||
imageMaxWidth,
|
||||
imageMaxHeight,
|
||||
imageMimeType,
|
||||
imageQuality,
|
||||
]
|
||||
);
|
||||
|
||||
const sanitizedHtml = React.useMemo(
|
||||
() => sanitizeHtmlForPreview(html || ""),
|
||||
[html],
|
||||
);
|
||||
|
||||
// 외부 value 변경 시 동기화
|
||||
React.useEffect(() => {
|
||||
if ((value || "") !== latestHtmlRef.current) {
|
||||
setHtml(value || "");
|
||||
latestHtmlRef.current = value || "";
|
||||
if ((value || '') !== latestHtmlRef.current) {
|
||||
setHtml(value || '')
|
||||
latestHtmlRef.current = value || ''
|
||||
}
|
||||
}, [value]);
|
||||
}, [value])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (textareaRef.current && props.onEditorReady) {
|
||||
props.onEditorReady(textareaRef.current);
|
||||
}
|
||||
},[props.onEditorReady])
|
||||
onEditorReady?.(textareaRef.current)
|
||||
}, [onEditorReady])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!props.onCommandReady) return;
|
||||
|
||||
props.onCommandReady({
|
||||
if (!onCommandReady) return
|
||||
onCommandReady({
|
||||
focus: () => textareaRef.current?.focus(),
|
||||
insertText: (placeholder: string) => {
|
||||
const current = latestHtmlRef.current ?? "";
|
||||
|
||||
ti.insertText(
|
||||
placeholder,
|
||||
current,
|
||||
(next) => {
|
||||
setHtml(next);
|
||||
latestHtmlRef.current = next;
|
||||
},
|
||||
(next) => {
|
||||
// html 모드도 debounce 쓰면 flush 권장
|
||||
flushChange(next);
|
||||
},
|
||||
);
|
||||
insertText: (text) => {
|
||||
textareaInsert.insertText(
|
||||
text,
|
||||
latestHtmlRef.current,
|
||||
(next) => commitHtml(next),
|
||||
(next) => commitHtml(next, true),
|
||||
)
|
||||
},
|
||||
});
|
||||
})
|
||||
return () => onCommandReady(null)
|
||||
}, [commitHtml, onCommandReady, textareaInsert])
|
||||
|
||||
return () => props.onCommandReady?.(null);
|
||||
}, [props.onCommandReady, ti, flushChange]);
|
||||
const handleFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
try {
|
||||
const file = event.target.files?.[0]
|
||||
event.target.value = ''
|
||||
if (!file || !onImageUpload) return
|
||||
if (!file.type.startsWith('image/')) {
|
||||
toast.error('이미지 파일만 업로드할 수 있습니다.')
|
||||
return
|
||||
}
|
||||
|
||||
const compressed = await compressImage(file, {
|
||||
maxBytes: maxImageBytes,
|
||||
maxWidth: imageMaxWidth,
|
||||
maxHeight: imageMaxHeight,
|
||||
mimeType: imageMimeType,
|
||||
quality: imageQuality,
|
||||
})
|
||||
|
||||
if (compressed.size > maxImageBytes) {
|
||||
toast.error('이미지 용량이 제한을 초과합니다.')
|
||||
return
|
||||
}
|
||||
|
||||
const url = resolveUploadUrl(await onImageUpload(compressed))
|
||||
if (!url) {
|
||||
toast.error('이미지 업로드 응답이 올바르지 않습니다.')
|
||||
return
|
||||
}
|
||||
|
||||
const current = latestHtmlRef.current
|
||||
const textarea = textareaRef.current
|
||||
const imageTag = `<img src="${url}" alt="" />`
|
||||
const start = textarea?.selectionStart ?? current.length
|
||||
const end = textarea?.selectionEnd ?? current.length
|
||||
const next = `${current.slice(0, start)}${imageTag}${current.slice(end)}`
|
||||
commitHtml(next)
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const position = start + imageTag.length
|
||||
textarea?.focus()
|
||||
textarea?.setSelectionRange(position, position)
|
||||
})
|
||||
} catch (error) {
|
||||
if (onImageUploadError) onImageUploadError(error)
|
||||
else toast.error('이미지 업로드에 실패했습니다.')
|
||||
}
|
||||
}
|
||||
|
||||
const previewHtml = React.useMemo(() => sanitizeHtmlForPreview(html), [html])
|
||||
|
||||
return (
|
||||
<div className={cn("rounded-md border bg-white", className)}>
|
||||
{label && (
|
||||
<div className="border-b px-3 py-2 text-sm font-semibold">
|
||||
{label}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={cn('rounded-md border bg-background', className)}>
|
||||
{label ? <div className="border-b px-3 py-2 text-sm font-semibold">{label}</div> : null}
|
||||
<div className="flex flex-col gap-2 px-3 py-2">
|
||||
<div className="flex items-center justify-between text-xs text-gray-500">
|
||||
<div className="text-muted-foreground flex items-center justify-between text-xs">
|
||||
<span>HTML 모드</span>
|
||||
{onImageUpload && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePickImage}
|
||||
className="rounded border px-2 py-1 text-xs hover:bg-gray-50"
|
||||
>
|
||||
{onImageUpload ? (
|
||||
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
|
||||
이미지 업로드
|
||||
</button>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="min-h-[200px] w-full resize-y border bg-white p-2 text-sm font-mono outline-none"
|
||||
className="min-h-[200px] w-full resize-y rounded-md border bg-background p-2 font-mono text-sm outline-none"
|
||||
value={html}
|
||||
onChange={handleTextChange}
|
||||
onBlur={handleBlur}
|
||||
onChange={(event) => commitHtml(event.target.value)}
|
||||
onBlur={() => flushChange(latestHtmlRef.current)}
|
||||
placeholder={placeholder}
|
||||
rows={rows}
|
||||
{...ti.bindSelectionHandlers}
|
||||
/>
|
||||
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleFile}
|
||||
{...textareaInsert.bindSelectionHandlers}
|
||||
/>
|
||||
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
|
||||
</div>
|
||||
{showPreview && (
|
||||
<div className={cn("border-t p-3", previewClassName)}>
|
||||
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
||||
<div className="rounded-md border bg-gray-50 p-3 text-sm leading-relaxed">
|
||||
<div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{showPreview ? (
|
||||
<div className={cn('border-t p-3', previewClassName)}>
|
||||
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
||||
<div className="rounded-md border bg-muted/30 p-3 text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,195 +1,119 @@
|
||||
"use client";
|
||||
'use client'
|
||||
|
||||
import React from "react";
|
||||
import { cn } from "@kri/common/ui";
|
||||
import type { KriEditorProps } from "./types";
|
||||
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
||||
import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
||||
import * as React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { KriEditorProps } from './types'
|
||||
import { useDebouncedChange } from './hooks/useDebouncedChange'
|
||||
import { useTextareaInsert } from './hooks/useTextareaInsert'
|
||||
|
||||
type SmsEditorProps = Omit<KriEditorProps, "mode"> & {
|
||||
mode: "sms";
|
||||
};
|
||||
type SmsEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'sms' }
|
||||
|
||||
export function KriEditorSms(props: SmsEditorProps) {
|
||||
const {
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "문자 내용을 입력하세요...",
|
||||
className,
|
||||
debounceMs = 350,
|
||||
smsTitle = "",
|
||||
changeSmsType,
|
||||
onEditorReady,
|
||||
} = props;
|
||||
function calculateBytes(value: string): number {
|
||||
return Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 127 ? 2 : 1), 0)
|
||||
}
|
||||
|
||||
const [text, setText] = React.useState<string>(value || "");
|
||||
const [byteSize, setByteSize] = React.useState(0);
|
||||
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null);
|
||||
const latestTextRef = React.useRef(text);
|
||||
const lastTypeRef = React.useRef<"SMS" | "LMS" | null>(null);
|
||||
export function KriEditorSms({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '문자 내용을 입력하세요...',
|
||||
className,
|
||||
debounceMs = 350,
|
||||
smsTitle = '',
|
||||
changeSmsType,
|
||||
onEditorReady,
|
||||
onCommandReady,
|
||||
smsMaxBytes = 90,
|
||||
lmsMaxBytes = 2000,
|
||||
isSmsReadOnly = false,
|
||||
}: SmsEditorProps) {
|
||||
const [text, setText] = React.useState(value || '')
|
||||
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
|
||||
const latestTextRef = React.useRef(text)
|
||||
const lastTypeRef = React.useRef<'SMS' | 'LMS' | null>(null)
|
||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
|
||||
const textareaInsert = useTextareaInsert(textareaRef)
|
||||
const byteSize = React.useMemo(() => calculateBytes(text), [text])
|
||||
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS'
|
||||
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
|
||||
|
||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs);
|
||||
const ti = useTextareaInsert(textareaRef);
|
||||
const commitText = React.useCallback((next: string, immediate = false) => {
|
||||
setText(next)
|
||||
latestTextRef.current = next
|
||||
if (immediate) flushChange(next)
|
||||
else scheduleChange(next)
|
||||
}, [flushChange, scheduleChange])
|
||||
|
||||
// 한글은 2byte, 영문/숫자/특수문자는 1byte로 계산
|
||||
const calculateBytes = React.useCallback((str: string): number => {
|
||||
let bytes = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charAt(i);
|
||||
if (escape(char).length > 4) {
|
||||
bytes += 2;
|
||||
} else {
|
||||
bytes += 1;
|
||||
}
|
||||
React.useEffect(() => {
|
||||
if ((value || '') !== latestTextRef.current) {
|
||||
setText(value || '')
|
||||
latestTextRef.current = value || ''
|
||||
}
|
||||
return bytes;
|
||||
}, []);
|
||||
|
||||
const hasTitle = (smsTitle?.length ?? 0) > 0;
|
||||
const messageType: "SMS" | "LMS" = (byteSize > 90 || hasTitle) ? "LMS" : "SMS";
|
||||
const maxBytes = messageType === "LMS" ? 2000 : 90;
|
||||
const messageTypeColor = messageType === "LMS" ? 'bg-blue-500' : 'bg-red-500';
|
||||
|
||||
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const next = e.target.value;
|
||||
const bytes = calculateBytes(next);
|
||||
|
||||
// 최대 바이트 초과 방지
|
||||
if (bytes > 2000) {
|
||||
return;
|
||||
}
|
||||
|
||||
setText(next);
|
||||
setByteSize(bytes);
|
||||
latestTextRef.current = next;
|
||||
scheduleChange(next);
|
||||
};
|
||||
|
||||
const handleBlur = () => {
|
||||
flushChange(latestTextRef.current);
|
||||
};
|
||||
|
||||
// 외부 value 변경 시 동기화
|
||||
React.useEffect(() => {
|
||||
if ((value || "") !== latestTextRef.current) {
|
||||
const newText = value || "";
|
||||
setText(newText);
|
||||
setByteSize(calculateBytes(newText));
|
||||
latestTextRef.current = newText;
|
||||
}
|
||||
}, [value, calculateBytes]);
|
||||
|
||||
// 바이트 계산 초기화
|
||||
React.useEffect(() => {
|
||||
setByteSize(calculateBytes(text));
|
||||
}, [text, calculateBytes]);
|
||||
}, [value])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!changeSmsType) return;
|
||||
if (lastTypeRef.current === messageType) return;
|
||||
|
||||
lastTypeRef.current = messageType;
|
||||
changeSmsType(messageType);
|
||||
}, [messageType, changeSmsType]);
|
||||
|
||||
// onEditorReady 콜백
|
||||
React.useEffect(() => {
|
||||
if (textareaRef.current && onEditorReady) {
|
||||
onEditorReady(textareaRef.current);
|
||||
}
|
||||
}, [onEditorReady]);
|
||||
if (lastTypeRef.current === messageType) return
|
||||
lastTypeRef.current = messageType
|
||||
changeSmsType?.(messageType)
|
||||
}, [changeSmsType, messageType])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!props.onCommandReady) return;
|
||||
onEditorReady?.(textareaRef.current)
|
||||
}, [onEditorReady])
|
||||
|
||||
props.onCommandReady({
|
||||
React.useEffect(() => {
|
||||
if (!onCommandReady) return
|
||||
onCommandReady({
|
||||
focus: () => textareaRef.current?.focus(),
|
||||
insertText: (placeholder: string) => {
|
||||
const current = latestTextRef.current ?? "";
|
||||
|
||||
ti.insertText(
|
||||
placeholder,
|
||||
current,
|
||||
(next) => {
|
||||
// 로컬 반영
|
||||
setText(next);
|
||||
setByteSize(calculateBytes(next));
|
||||
latestTextRef.current = next;
|
||||
},
|
||||
(next) => {
|
||||
// 부모 반영(즉시) - debounce를 이기기 위해 flush 권장
|
||||
flushChange(next);
|
||||
},
|
||||
);
|
||||
insertText: (insertedText) => {
|
||||
textareaInsert.insertText(
|
||||
insertedText,
|
||||
latestTextRef.current,
|
||||
(next) => commitText(next),
|
||||
(next) => commitText(next, true),
|
||||
)
|
||||
},
|
||||
});
|
||||
|
||||
return () => props.onCommandReady?.(null);
|
||||
}, [props.onCommandReady, ti, calculateBytes, flushChange]);
|
||||
})
|
||||
return () => onCommandReady(null)
|
||||
}, [commitText, onCommandReady, textareaInsert])
|
||||
|
||||
return (
|
||||
<div className={cn("w-full max-w-[320px] mx-auto", className)}>
|
||||
{label && (
|
||||
<div className="mb-2 text-sm font-semibold">
|
||||
{label}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 휴대전화 디자인 */}
|
||||
<div className="relative w-full h-[600px] bg-white rounded-[40px] shadow-2xl border-8 border-gray-800 overflow-hidden">
|
||||
{/* 상단 노치 */}
|
||||
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-32 h-6 bg-gray-800 rounded-b-2xl z-10" />
|
||||
|
||||
{/* 스크린 영역 */}
|
||||
<div className="h-full bg-gray-50 pt-8 pb-4 px-4 flex flex-col">
|
||||
{/* 헤더 - 바이트 및 타입 표시 */}
|
||||
<div className="flex justify-between items-center mb-3 px-2">
|
||||
<span className="text-xs text-gray-600 font-medium">
|
||||
{byteSize}/{maxBytes}byte
|
||||
</span>
|
||||
<span className={`${messageTypeColor} text-white px-3 py-1 rounded-md text-xs font-bold`}>
|
||||
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
|
||||
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
|
||||
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
|
||||
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
|
||||
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
|
||||
<div className="mb-3 flex items-center justify-between px-2">
|
||||
<span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span>
|
||||
<span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', messageType === 'LMS' ? 'bg-blue-500' : 'bg-red-500')}>
|
||||
{messageType}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 메시지 본문 (textarea) */}
|
||||
<div className="flex-1 bg-white rounded-2xl shadow-sm overflow-hidden flex flex-col">
|
||||
{/* LMS 제목 */}
|
||||
{smsTitle && (
|
||||
<div className="px-4 pt-3 pb-2">
|
||||
<div className="font-bold text-sm text-gray-800">
|
||||
{smsTitle}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Textarea - 에디터 */}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="flex-1 w-full p-4 text-sm text-gray-700 outline-none resize-none bg-transparent leading-relaxed"
|
||||
value={text}
|
||||
onChange={handleTextChange}
|
||||
onBlur={handleBlur}
|
||||
placeholder={placeholder}
|
||||
style={{ minHeight: smsTitle ? '320px' : '360px' }}
|
||||
{...ti.bindSelectionHandlers}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 바이트 초과 경고 */}
|
||||
{byteSize > maxBytes && (
|
||||
<div className="mt-2 px-2">
|
||||
<p className="text-xs text-red-600 font-medium text-center">
|
||||
⚠️ 최대 용량 초과 ({byteSize - maxBytes}byte)
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 하단 홈 버튼 */}
|
||||
<div className="absolute bottom-2 left-1/2 -translate-x-1/2 w-32 h-1 bg-gray-800 rounded-full" />
|
||||
<div className="flex flex-1 flex-col overflow-hidden rounded-2xl bg-white shadow-sm">
|
||||
{smsTitle ? <div className="px-4 pt-3 pb-2 text-sm font-bold text-gray-800">{smsTitle}</div> : null}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="w-full flex-1 resize-none bg-transparent p-4 text-sm leading-relaxed text-gray-700 outline-none"
|
||||
value={text}
|
||||
readOnly={isSmsReadOnly}
|
||||
onChange={(event) => {
|
||||
const next = event.target.value
|
||||
if (calculateBytes(next) <= lmsMaxBytes) commitText(next)
|
||||
}}
|
||||
onBlur={() => flushChange(latestTextRef.current)}
|
||||
placeholder={placeholder}
|
||||
style={{ minHeight: smsTitle ? '320px' : '360px' }}
|
||||
{...textareaInsert.bindSelectionHandlers}
|
||||
/>
|
||||
</div>
|
||||
{byteSize > maxBytes ? (
|
||||
<p className="mt-2 px-2 text-center text-xs font-medium text-red-600">
|
||||
최대 용량을 {byteSize - maxBytes}byte 초과했습니다.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="absolute bottom-2 left-1/2 h-1 w-32 -translate-x-1/2 rounded-full bg-gray-800" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -18,9 +18,10 @@ import TableHeader from "@tiptap/extension-table-header";
|
||||
import TableCell from "@tiptap/extension-table-cell";
|
||||
|
||||
import { toast } from "sonner";
|
||||
import { cn } from "@kri/common/ui";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import type { KriEditorProps, KriEditorMode, ToolbarState } from "./types";
|
||||
import type { KriEditorProps, ToolbarState } from "./types";
|
||||
import { resolveUploadUrl } from "./types";
|
||||
import { FontSize } from "./extensions/font-size";
|
||||
import { Div } from "./extensions/div";
|
||||
import { compressImage } from "./utils/imageCompression";
|
||||
@@ -31,10 +32,6 @@ import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
||||
|
||||
type ViewMode = "wysiwyg" | "html";
|
||||
|
||||
function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode {
|
||||
return mode ?? editorMode ?? "wysiwyg";
|
||||
}
|
||||
|
||||
function getToolbarState(editor: Editor): ToolbarState {
|
||||
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; color?: string | null };
|
||||
const hl = editor.getAttributes("highlight") as { color?: string | null };
|
||||
@@ -76,8 +73,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
showPreview = false,
|
||||
previewClassName,
|
||||
|
||||
mode: modeProp,
|
||||
editorMode,
|
||||
mode = "wysiwyg",
|
||||
debounceMs = 350,
|
||||
|
||||
onImageUpload,
|
||||
@@ -90,9 +86,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
|
||||
allowBase64 = false,
|
||||
sanitizeHtml: sanitizeHtmlOpt = true,
|
||||
toolbar = {},
|
||||
} = props;
|
||||
|
||||
const mode = resolveMode(modeProp, editorMode);
|
||||
const showHtmlToggle = mode === "both";
|
||||
|
||||
const LINK_HTML_ATTRS = {
|
||||
@@ -108,6 +104,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
|
||||
const [view, setView] = useState<ViewMode>("wysiwyg");
|
||||
const [wysiwygKey, setWysiwygKey] = useState<number>(0);
|
||||
const [previewSource, setPreviewSource] = useState(value ?? "");
|
||||
const viewRef = useRef<ViewMode>("wysiwyg");
|
||||
|
||||
useEffect(() => {
|
||||
@@ -188,7 +185,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
|
||||
onUpdate: ({ editor }) => {
|
||||
if (viewRef.current === "html") return;
|
||||
scheduleChange(editor.getHTML());
|
||||
const nextHtml = editor.getHTML();
|
||||
setPreviewSource(nextHtml);
|
||||
scheduleChange(nextHtml);
|
||||
},
|
||||
|
||||
editorProps: {
|
||||
@@ -225,8 +224,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
if (pos && linkType) {
|
||||
const $pos = view.state.doc.resolve(pos.pos);
|
||||
|
||||
const pickHref = (marks: readonly any[] | null | undefined) =>
|
||||
marks?.find(m => m.type === linkType)?.attrs?.href as string | undefined;
|
||||
const pickHref = (marks: readonly { type: unknown; attrs?: Record<string, unknown> }[] | null | undefined) => {
|
||||
const mark = marks?.find((candidate) => candidate.type === linkType);
|
||||
const value = mark?.attrs?.href;
|
||||
return typeof value === "string" ? value : undefined;
|
||||
};
|
||||
|
||||
href =
|
||||
pickHref($pos.marks()) ||
|
||||
@@ -245,7 +247,6 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
// 링크 열기 + 에디터 클릭 처리(커서 이동 등) 막기
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
console.log(LINK_HTML_ATTRS.rel.replaceAll(" ",","))
|
||||
window.open(href, LINK_HTML_ATTRS.target, LINK_HTML_ATTRS.rel.replaceAll(" ",","));
|
||||
return true;
|
||||
},
|
||||
@@ -300,40 +301,31 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
}, [editor, restoreSelection]);
|
||||
|
||||
|
||||
const normalizeLinkUrl = (raw: string): string => {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return "";
|
||||
const normalizeLinkUrl = (raw: string): string => {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return "";
|
||||
|
||||
// 이미 프로토콜이 있으면 그대로 사용
|
||||
if (/^https?:\/\//i.test(trimmed) || /^mailto:/i.test(trimmed) || /^tel:/i.test(trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// 프로토콜이 없으면 https:// 를 기본으로 붙여준다.
|
||||
return `https://${trimmed}`;
|
||||
};
|
||||
|
||||
const toggleLink = useCallback(() => {
|
||||
if (!editor) return;
|
||||
restoreSelection();
|
||||
|
||||
const prev = (editor.getAttributes("link").href as string | undefined) ?? "";
|
||||
if (editor.isActive("link")) {
|
||||
if(confirm(`링크를 해제 하시겠습니까?\r\nLink: ${prev}`)){
|
||||
editor.chain().focus().unsetLink().run();
|
||||
return;
|
||||
}
|
||||
if (/^https?:\/\//i.test(trimmed) || /^mailto:/i.test(trimmed) || /^tel:/i.test(trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const url = window.prompt("링크 URL을 입력하세요", prev);
|
||||
if (url === null) return;
|
||||
return `https://${trimmed}`;
|
||||
};
|
||||
|
||||
const setLink = useCallback((url: string) => {
|
||||
if (!editor) return;
|
||||
restoreSelection();
|
||||
const normalized = normalizeLinkUrl(url);
|
||||
if (!normalized) return;
|
||||
|
||||
editor.chain().focus().extendMarkRange("link").setLink({ href: normalized }).run();
|
||||
}, [editor, restoreSelection]);
|
||||
|
||||
const unsetLink = useCallback(() => {
|
||||
if (!editor) return;
|
||||
restoreSelection();
|
||||
editor.chain().focus().extendMarkRange("link").unsetLink().run();
|
||||
}, [editor, restoreSelection]);
|
||||
|
||||
const insertTable = useCallback(() => {
|
||||
if (!editor) return;
|
||||
restoreSelection();
|
||||
@@ -403,7 +395,7 @@ const normalizeLinkUrl = (raw: string): string => {
|
||||
return;
|
||||
}
|
||||
|
||||
const { url } = await onImageUpload(compressed);
|
||||
const url = resolveUploadUrl(await onImageUpload(compressed));
|
||||
|
||||
if (!url || typeof url !== "string") {
|
||||
toast.error("이미지 업로드 응답이 올바르지 않습니다.");
|
||||
@@ -480,6 +472,7 @@ const normalizeLinkUrl = (raw: string): string => {
|
||||
}, [editor, view, props.onEditorReady]);
|
||||
|
||||
useEffect(() => {
|
||||
setPreviewSource(value ?? "");
|
||||
if (!editor) return;
|
||||
if (viewRef.current === "html") return;
|
||||
if (value == null) return;
|
||||
@@ -564,13 +557,12 @@ const normalizeLinkUrl = (raw: string): string => {
|
||||
}, [editor, props.onCommandReady, restoreSelection, flushChange, htmlTi]);
|
||||
|
||||
const previewHtml = useMemo(() => {
|
||||
const raw = optimisticHtmlRef.current || "";
|
||||
return sanitizeHtmlOpt ? sanitizeHtml(raw) : raw;
|
||||
}, [optimisticHtmlRef, sanitizeHtmlOpt]);
|
||||
return sanitizeHtmlOpt ? sanitizeHtml(previewSource) : previewSource;
|
||||
}, [previewSource, sanitizeHtmlOpt]);
|
||||
|
||||
if (!editor) {
|
||||
return (
|
||||
<div className={cn("rounded-lg border bg-white", className)}>
|
||||
<div className={cn("rounded-lg border bg-background", className)}>
|
||||
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
|
||||
<div className="p-3 text-sm text-muted-foreground">에디터 로딩 중…</div>
|
||||
</div>
|
||||
@@ -578,31 +570,36 @@ const normalizeLinkUrl = (raw: string): string => {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("rounded-lg border bg-white", className)}>
|
||||
<div className={cn("rounded-lg border bg-background", className)}>
|
||||
{label?.trim() ? <div className="border-b p-2 font-semibold">{label}</div> : null}
|
||||
|
||||
<div className="border-b">
|
||||
<Toolbar
|
||||
editor={editor}
|
||||
state={tb}
|
||||
className="flex-nowrap"
|
||||
canImageUpload={canImageUpload}
|
||||
onPickImage={handlePickImage}
|
||||
showHtmlToggle={showHtmlToggle}
|
||||
isHtmlView={view === "html"}
|
||||
onToggleHtmlView={onToggleHtmlView}
|
||||
onSetFontSize={setFontSize}
|
||||
onSetTextColor={setTextColor}
|
||||
onUnsetTextColor={unsetTextColor}
|
||||
onSetHighlight={setHighlight}
|
||||
onUnsetHighlight={unsetHighlight}
|
||||
onToggleLink={toggleLink}
|
||||
onInsertTable={insertTable}
|
||||
onAddRow={addRow}
|
||||
onAddColumn={addColumn}
|
||||
onDeleteTable={deleteTable}
|
||||
/>
|
||||
</div>
|
||||
{toolbar !== false ? (
|
||||
<div className="border-b">
|
||||
<Toolbar
|
||||
editor={editor}
|
||||
state={tb}
|
||||
config={toolbar}
|
||||
className="flex-nowrap"
|
||||
canImageUpload={canImageUpload}
|
||||
onPickImage={handlePickImage}
|
||||
showHtmlToggle={showHtmlToggle}
|
||||
isHtmlView={view === "html"}
|
||||
onToggleHtmlView={onToggleHtmlView}
|
||||
onSetFontSize={setFontSize}
|
||||
onSetTextColor={setTextColor}
|
||||
onUnsetTextColor={unsetTextColor}
|
||||
onSetHighlight={setHighlight}
|
||||
onUnsetHighlight={unsetHighlight}
|
||||
linkUrl={(editor.getAttributes("link").href as string | undefined) ?? ""}
|
||||
onSetLink={setLink}
|
||||
onUnsetLink={unsetLink}
|
||||
onInsertTable={insertTable}
|
||||
onAddRow={addRow}
|
||||
onAddColumn={addColumn}
|
||||
onDeleteTable={deleteTable}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} disabled={!canImageUpload} />
|
||||
|
||||
@@ -617,6 +614,7 @@ const normalizeLinkUrl = (raw: string): string => {
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onChange={(e) => {
|
||||
htmlDraftRef.current = e.target.value;
|
||||
setPreviewSource(htmlDraftRef.current);
|
||||
scheduleChange(htmlDraftRef.current);
|
||||
}}
|
||||
onBlur={() => flushChange(htmlDraftRef.current)}
|
||||
@@ -629,7 +627,7 @@ const normalizeLinkUrl = (raw: string): string => {
|
||||
{showPreview && (
|
||||
<div className={cn("border-t p-3", previewClassName)}>
|
||||
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
||||
<div className="rounded-md border bg-gray-50 p-3">
|
||||
<div className="rounded-md border bg-muted/30 p-3">
|
||||
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,2 +1,13 @@
|
||||
export { KriEditor } from "./KriEditor";
|
||||
export type { KriEditorProps, KriEditorMode, UploadResult, ToolbarState, KriEditorCommand } from "./types";
|
||||
export { KriEditor } from './KriEditor'
|
||||
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
|
||||
export { KriEditorSms } from './KriEditorSms'
|
||||
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
|
||||
export type {
|
||||
KriEditorCommand,
|
||||
KriEditorMode,
|
||||
KriEditorProps,
|
||||
KriEditorToolbarConfig,
|
||||
KriEditorToolbarFeature,
|
||||
KriEditorUploadResult,
|
||||
ToolbarState,
|
||||
} from './types'
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
"use client";
|
||||
'use client'
|
||||
|
||||
import type { Editor } from "@tiptap/react";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { cn } from "@kri/common/ui";
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import {
|
||||
AlignCenter,
|
||||
AlignLeft,
|
||||
AlignRight,
|
||||
Bold,
|
||||
Code2,
|
||||
Highlighter,
|
||||
Image as ImageIcon,
|
||||
Italic,
|
||||
@@ -23,72 +15,58 @@ import {
|
||||
List,
|
||||
ListOrdered,
|
||||
Palette,
|
||||
Strikethrough,
|
||||
Table2,
|
||||
Underline,
|
||||
Strikethrough,
|
||||
Code2,
|
||||
} from "lucide-react";
|
||||
import { ToolbarButton } from "./ToolbarButton";
|
||||
import type { ToolbarState } from "../types";
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { KriEditorToolbarConfig, KriEditorToolbarFeature, ToolbarState } from '../types'
|
||||
import { ToolbarButton } from './ToolbarButton'
|
||||
|
||||
type Props = {
|
||||
editor: Editor;
|
||||
state: ToolbarState;
|
||||
className?: string;
|
||||
|
||||
canImageUpload: boolean;
|
||||
onPickImage: () => void;
|
||||
|
||||
showHtmlToggle: boolean;
|
||||
isHtmlView: boolean;
|
||||
onToggleHtmlView: () => void;
|
||||
|
||||
onSetFontSize: (px: string) => void;
|
||||
|
||||
onSetTextColor: (hex: string) => void;
|
||||
onUnsetTextColor: () => void;
|
||||
|
||||
onSetHighlight: (hex: string) => void;
|
||||
onUnsetHighlight: () => void;
|
||||
|
||||
onToggleLink: () => void;
|
||||
|
||||
onInsertTable: () => void;
|
||||
onAddRow: () => void;
|
||||
onAddColumn: () => void;
|
||||
onDeleteTable: () => void;
|
||||
};
|
||||
interface ToolbarProps {
|
||||
editor: Editor
|
||||
state: ToolbarState
|
||||
config?: KriEditorToolbarConfig
|
||||
className?: string
|
||||
canImageUpload: boolean
|
||||
onPickImage: () => void
|
||||
showHtmlToggle: boolean
|
||||
isHtmlView: boolean
|
||||
onToggleHtmlView: () => void
|
||||
onSetFontSize: (value: string) => void
|
||||
onSetTextColor: (value: string) => void
|
||||
onUnsetTextColor: () => void
|
||||
onSetHighlight: (value: string) => void
|
||||
onUnsetHighlight: () => void
|
||||
linkUrl: string
|
||||
onSetLink: (url: string) => void
|
||||
onUnsetLink: () => void
|
||||
onInsertTable: () => void
|
||||
onAddRow: () => void
|
||||
onAddColumn: () => void
|
||||
onDeleteTable: () => void
|
||||
}
|
||||
|
||||
const PRESET_COLORS = [
|
||||
"#111827",
|
||||
"#374151",
|
||||
"#6B7280",
|
||||
"#9CA3AF",
|
||||
"#D1D5DB",
|
||||
"#EF4444",
|
||||
"#F97316",
|
||||
"#F59E0B",
|
||||
"#84CC16",
|
||||
"#22C55E",
|
||||
"#06B6D4",
|
||||
"#3B82F6",
|
||||
"#6366F1",
|
||||
"#A855F7",
|
||||
"#EC4899",
|
||||
];
|
||||
'#111827', '#374151', '#6B7280', '#9CA3AF', '#D1D5DB', '#EF4444', '#F97316', '#F59E0B',
|
||||
'#84CC16', '#22C55E', '#06B6D4', '#3B82F6', '#6366F1', '#A855F7', '#EC4899',
|
||||
]
|
||||
|
||||
const HIGHLIGHT_COLORS = ['#FEF3C7', '#FDE68A', '#A7F3D0', '#BAE6FD', '#DDD6FE', '#FBCFE8', '#FFE4E6', '#E5E7EB', '#F5F5F4', '#FFFFFF']
|
||||
|
||||
function Swatch({ color }: { color: string | null }) {
|
||||
return (
|
||||
<span
|
||||
className="ml-1 inline-block h-2 w-2 rounded-full border align-middle"
|
||||
style={{ backgroundColor: color ?? "transparent" }}
|
||||
/>
|
||||
);
|
||||
return <span className="ml-1 inline-block size-2 rounded-full border" style={{ backgroundColor: color ?? 'transparent' }} />
|
||||
}
|
||||
|
||||
export function Toolbar({
|
||||
editor,
|
||||
state,
|
||||
config,
|
||||
className,
|
||||
canImageUpload,
|
||||
onPickImage,
|
||||
@@ -100,230 +78,206 @@ export function Toolbar({
|
||||
onUnsetTextColor,
|
||||
onSetHighlight,
|
||||
onUnsetHighlight,
|
||||
onToggleLink,
|
||||
linkUrl,
|
||||
onSetLink,
|
||||
onUnsetLink,
|
||||
onInsertTable,
|
||||
onAddRow,
|
||||
onAddColumn,
|
||||
onDeleteTable,
|
||||
}: Props) {
|
||||
}: ToolbarProps) {
|
||||
const enabled = (feature: KriEditorToolbarFeature) => config?.[feature] !== false
|
||||
const showTextStyle = enabled('bold') || enabled('italic') || enabled('underline') || enabled('strike')
|
||||
const showColors = enabled('textColor') || enabled('highlight')
|
||||
const showLists = enabled('bulletList') || enabled('orderedList')
|
||||
const [linkOpen, setLinkOpen] = useState(false)
|
||||
const [linkDraft, setLinkDraft] = useState(linkUrl)
|
||||
|
||||
useEffect(() => {
|
||||
if (linkOpen) setLinkDraft(linkUrl)
|
||||
}, [linkOpen, linkUrl])
|
||||
|
||||
const applyLink = () => {
|
||||
const next = linkDraft.trim()
|
||||
if (!next) return
|
||||
onSetLink(next)
|
||||
setLinkOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("flex items-center gap-1 whitespace-nowrap px-2 py-1", className)}>
|
||||
<select
|
||||
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
|
||||
value={state.fontSize}
|
||||
onChange={(e) => onSetFontSize(e.target.value)}
|
||||
title="폰트 크기"
|
||||
>
|
||||
{["12px","14px","16px","18px","20px","24px","28px","32px"].map((v) => (
|
||||
<option key={v} value={v}>
|
||||
{v.replace("px","")}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className={cn('flex items-center gap-1 overflow-x-auto whitespace-nowrap px-2 py-1', className)}>
|
||||
{enabled('fontSize') ? (
|
||||
<select
|
||||
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
|
||||
value={state.fontSize}
|
||||
onChange={(event) => onSetFontSize(event.target.value)}
|
||||
title="폰트 크기"
|
||||
>
|
||||
{['12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px'].map((value) => (
|
||||
<option key={value} value={value}>{value.replace('px', '')}</option>
|
||||
))}
|
||||
</select>
|
||||
) : null}
|
||||
|
||||
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||
{enabled('fontSize') && showTextStyle ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||
|
||||
<ToolbarButton
|
||||
active={state.isBold}
|
||||
disabled={!editor.can().chain().focus().toggleBold().run()}
|
||||
onClick={() => editor.chain().focus().toggleBold().run()}
|
||||
title="굵게"
|
||||
>
|
||||
<Bold className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
{enabled('bold') ? (
|
||||
<ToolbarButton active={state.isBold} disabled={!editor.can().chain().focus().toggleBold().run()} onClick={() => editor.chain().focus().toggleBold().run()} title="굵게">
|
||||
<Bold className="size-4" />
|
||||
</ToolbarButton>
|
||||
) : null}
|
||||
{enabled('italic') ? (
|
||||
<ToolbarButton active={state.isItalic} disabled={!editor.can().chain().focus().toggleItalic().run()} onClick={() => editor.chain().focus().toggleItalic().run()} title="기울임">
|
||||
<Italic className="size-4" />
|
||||
</ToolbarButton>
|
||||
) : null}
|
||||
{enabled('underline') ? (
|
||||
<ToolbarButton active={state.isUnderline} onClick={() => editor.chain().focus().toggleUnderline().run()} title="밑줄">
|
||||
<Underline className="size-4" />
|
||||
</ToolbarButton>
|
||||
) : null}
|
||||
{enabled('strike') ? (
|
||||
<ToolbarButton active={state.isStrike} onClick={() => editor.chain().focus().toggleStrike().run()} title="취소선">
|
||||
<Strikethrough className="size-4" />
|
||||
</ToolbarButton>
|
||||
) : null}
|
||||
|
||||
<ToolbarButton
|
||||
active={state.isItalic}
|
||||
disabled={!editor.can().chain().focus().toggleItalic().run()}
|
||||
onClick={() => editor.chain().focus().toggleItalic().run()}
|
||||
title="기울임"
|
||||
>
|
||||
<Italic className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
{showTextStyle && showColors ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||
|
||||
<ToolbarButton active={state.isUnderline} onClick={() => editor.chain().focus().toggleUnderline().run()} title="밑줄">
|
||||
<Underline className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
{enabled('textColor') ? (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<span>
|
||||
<ToolbarButton title="텍스트 색상" active={Boolean(state.textColor)}>
|
||||
<Palette className="size-4" /><Swatch color={state.textColor} />
|
||||
</ToolbarButton>
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-56" align="start">
|
||||
<div className="text-muted-foreground mb-2 text-xs">텍스트 색상</div>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{PRESET_COLORS.map((color) => (
|
||||
<button key={color} type="button" className="size-6 rounded border" style={{ backgroundColor: color }} onMouseDown={(event) => event.preventDefault()} onClick={() => onSetTextColor(color)} aria-label={`색상 ${color}`} />
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<input type="color" className="h-8 w-10 cursor-pointer rounded-md border p-1" onMouseDown={(event) => event.preventDefault()} onChange={(event) => onSetTextColor(event.target.value)} aria-label="사용자 지정 텍스트 색상" />
|
||||
<button type="button" className="text-muted-foreground text-xs underline" onMouseDown={(event) => event.preventDefault()} onClick={onUnsetTextColor}>색상 제거</button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
) : null}
|
||||
|
||||
<ToolbarButton active={state.isStrike} onClick={() => editor.chain().focus().toggleStrike().run()} title="취소선">
|
||||
<Strikethrough className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
{enabled('highlight') ? (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<span>
|
||||
<ToolbarButton title="하이라이트" active={Boolean(state.highlightColor)}>
|
||||
<Highlighter className="size-4" /><Swatch color={state.highlightColor} />
|
||||
</ToolbarButton>
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-56" align="start">
|
||||
<div className="text-muted-foreground mb-2 text-xs">하이라이트</div>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{HIGHLIGHT_COLORS.map((color) => (
|
||||
<button key={color} type="button" className="size-6 rounded border" style={{ backgroundColor: color }} onMouseDown={(event) => event.preventDefault()} onClick={() => onSetHighlight(color)} aria-label={`하이라이트 ${color}`} />
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<input type="color" className="h-8 w-10 cursor-pointer rounded-md border p-1" onMouseDown={(event) => event.preventDefault()} onChange={(event) => onSetHighlight(event.target.value)} aria-label="사용자 지정 하이라이트" />
|
||||
<button type="button" className="text-muted-foreground text-xs underline" onMouseDown={(event) => event.preventDefault()} onClick={onUnsetHighlight}>하이라이트 제거</button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
) : null}
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<span>
|
||||
<ToolbarButton title="텍스트 색상" active={Boolean(state.textColor)}>
|
||||
<Palette className="h-4 w-4" />
|
||||
<Swatch color={state.textColor} />
|
||||
</ToolbarButton>
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-56" align="start">
|
||||
<div className="mb-2 text-xs text-muted-foreground">텍스트 색상</div>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{PRESET_COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
className="h-6 w-6 rounded border"
|
||||
style={{ backgroundColor: c }}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onSetTextColor(c)}
|
||||
aria-label={`color ${c}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
className="h-8 w-10 cursor-pointer rounded-md border p-1"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onChange={(e) => onSetTextColor(e.target.value)}
|
||||
aria-label="custom text color"
|
||||
/>
|
||||
<button type="button" className="text-xs text-muted-foreground underline" onMouseDown={(e) => e.preventDefault()} onClick={onUnsetTextColor}>
|
||||
색상 제거
|
||||
</button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{showColors && enabled('align') ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<span>
|
||||
<ToolbarButton active={Boolean(state.highlightColor)} title="하이라이트">
|
||||
<Highlighter className="h-4 w-4" />
|
||||
<Swatch color={state.highlightColor} />
|
||||
</ToolbarButton>
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-56" align="start">
|
||||
<div className="mb-2 text-xs text-muted-foreground">하이라이트</div>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{["#FEF3C7", "#FDE68A", "#A7F3D0", "#BAE6FD", "#DDD6FE", "#FBCFE8", "#FFE4E6", "#E5E7EB", "#F5F5F4", "#FFFFFF"].map(
|
||||
(c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
className="h-6 w-6 rounded border"
|
||||
style={{ backgroundColor: c }}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onSetHighlight(c)}
|
||||
aria-label={`highlight ${c}`}
|
||||
{enabled('align') ? (
|
||||
<>
|
||||
<ToolbarButton active={state.align === 'left'} onClick={() => editor.chain().focus().setTextAlign('left').run()} title="왼쪽 정렬"><AlignLeft className="size-4" /></ToolbarButton>
|
||||
<ToolbarButton active={state.align === 'center'} onClick={() => editor.chain().focus().setTextAlign('center').run()} title="가운데 정렬"><AlignCenter className="size-4" /></ToolbarButton>
|
||||
<ToolbarButton active={state.align === 'right'} onClick={() => editor.chain().focus().setTextAlign('right').run()} title="오른쪽 정렬"><AlignRight className="size-4" /></ToolbarButton>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{enabled('align') && showLists ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||
|
||||
{enabled('bulletList') ? <ToolbarButton active={state.isBulletList} onClick={() => editor.chain().focus().toggleBulletList().run()} title="불릿"><List className="size-4" /></ToolbarButton> : null}
|
||||
{enabled('orderedList') ? <ToolbarButton active={state.isOrderedList} onClick={() => editor.chain().focus().toggleOrderedList().run()} title="번호"><ListOrdered className="size-4" /></ToolbarButton> : null}
|
||||
|
||||
{showLists && (enabled('link') || enabled('image') || enabled('table')) ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
|
||||
|
||||
{enabled('link') ? (
|
||||
<Popover open={linkOpen} onOpenChange={setLinkOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<span>
|
||||
<ToolbarButton active={state.isLink} title={state.isLink ? '링크 수정' : '링크 삽입'}>
|
||||
<Link2 className="size-4" />
|
||||
</ToolbarButton>
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-80" align="start">
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
applyLink()
|
||||
}}
|
||||
>
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="kri-editor-link-url" className="text-sm font-medium">링크 URL</label>
|
||||
<Input
|
||||
id="kri-editor-link-url"
|
||||
value={linkDraft}
|
||||
onChange={(event) => setLinkDraft(event.target.value)}
|
||||
placeholder="https://example.com"
|
||||
autoFocus
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
className="h-8 w-10 cursor-pointer rounded-md border p-1"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onChange={(e) => onSetHighlight(e.target.value)}
|
||||
aria-label="custom highlight color"
|
||||
/>
|
||||
<button type="button" className="text-xs text-muted-foreground underline" onMouseDown={(e) => e.preventDefault()} onClick={onUnsetHighlight}>
|
||||
하이라이트 제거
|
||||
</button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
{state.isLink ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onUnsetLink()
|
||||
setLinkOpen(false)
|
||||
}}
|
||||
>
|
||||
링크 해제
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="submit" size="sm" disabled={!linkDraft.trim()}>적용</Button>
|
||||
</div>
|
||||
</form>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
) : null}
|
||||
{enabled('image') ? <ToolbarButton title={canImageUpload ? '이미지 업로드' : 'onImageUpload 미설정'} disabled={!canImageUpload} onClick={onPickImage}><ImageIcon className="size-4" /></ToolbarButton> : null}
|
||||
|
||||
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||
{enabled('table') ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild><span><ToolbarButton title="표"><Table2 className="size-4" /></ToolbarButton></span></DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-44">
|
||||
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onInsertTable() }}>표 삽입</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onAddRow() }} disabled={!state.inTable}>행 추가</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onAddColumn() }} disabled={!state.inTable}>열 추가</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={(event) => { event.preventDefault(); onDeleteTable() }} disabled={!state.inTable} className="text-destructive">표 삭제</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : null}
|
||||
|
||||
<ToolbarButton active={state.align === "left"} onClick={() => editor.chain().focus().setTextAlign("left").run()} title="왼쪽 정렬">
|
||||
<AlignLeft className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton active={state.align === "center"} onClick={() => editor.chain().focus().setTextAlign("center").run()} title="가운데 정렬">
|
||||
<AlignCenter className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton active={state.align === "right"} onClick={() => editor.chain().focus().setTextAlign("right").run()} title="오른쪽 정렬">
|
||||
<AlignRight className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
|
||||
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||
|
||||
<ToolbarButton active={state.isBulletList} onClick={() => editor.chain().focus().toggleBulletList().run()} title="불릿">
|
||||
<List className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton active={state.isOrderedList} onClick={() => editor.chain().focus().toggleOrderedList().run()} title="번호">
|
||||
<ListOrdered className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
|
||||
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||
|
||||
<ToolbarButton active={state.isLink} title={state.isLink ? "링크 해제" : "링크 삽입"} onClick={onToggleLink}>
|
||||
<Link2 className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
|
||||
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||
|
||||
<ToolbarButton title={canImageUpload ? "이미지 업로드" : "onImageUpload 미설정"} disabled={!canImageUpload} onClick={onPickImage}>
|
||||
<ImageIcon className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<span>
|
||||
<ToolbarButton title="표">
|
||||
<Table2 className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
</span>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-44">
|
||||
<DropdownMenuItem
|
||||
onSelect={(e) => {
|
||||
e.preventDefault();
|
||||
onInsertTable();
|
||||
}}
|
||||
>
|
||||
표 삽입
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuItem
|
||||
onSelect={(e) => {
|
||||
e.preventDefault();
|
||||
onAddRow();
|
||||
}}
|
||||
disabled={!state.inTable}
|
||||
>
|
||||
행 추가
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onSelect={(e) => {
|
||||
e.preventDefault();
|
||||
onAddColumn();
|
||||
}}
|
||||
disabled={!state.inTable}
|
||||
>
|
||||
열 추가
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuItem
|
||||
onSelect={(e) => {
|
||||
e.preventDefault();
|
||||
onDeleteTable();
|
||||
}}
|
||||
disabled={!state.inTable}
|
||||
className="text-destructive"
|
||||
>
|
||||
표 삭제
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{showHtmlToggle && (
|
||||
{showHtmlToggle && enabled('html') ? (
|
||||
<>
|
||||
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||
<ToolbarButton active={isHtmlView} title={isHtmlView ? "WYSIWYG로" : "HTML 편집"} onClick={onToggleHtmlView}>
|
||||
<Code2 className="h-4 w-4" />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton active={isHtmlView} title={isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집'} onClick={onToggleHtmlView}><Code2 className="size-4" /></ToolbarButton>
|
||||
</>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,87 +1,76 @@
|
||||
import {Editor} from "@tiptap/react";
|
||||
import type { Editor } from '@tiptap/react'
|
||||
|
||||
export type UploadResult = { url: string };
|
||||
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms'
|
||||
export type KriEditorUploadResult = string | { url: string }
|
||||
|
||||
export type KriEditorMode = "wysiwyg" | "both" | "html" | "sms";
|
||||
export type KriEditorToolbarFeature =
|
||||
| 'fontSize'
|
||||
| 'bold'
|
||||
| 'italic'
|
||||
| 'underline'
|
||||
| 'strike'
|
||||
| 'textColor'
|
||||
| 'highlight'
|
||||
| 'align'
|
||||
| 'bulletList'
|
||||
| 'orderedList'
|
||||
| 'link'
|
||||
| 'image'
|
||||
| 'table'
|
||||
| 'html'
|
||||
|
||||
export type KriEditorToolbarConfig = Partial<Record<KriEditorToolbarFeature, boolean>>
|
||||
|
||||
export type KriEditorCommand = {
|
||||
focus: () => void;
|
||||
insertText: (text: string) => void; // placeholder/merge-field 삽입
|
||||
};
|
||||
focus: () => void
|
||||
insertText: (text: string) => void
|
||||
}
|
||||
|
||||
export type KriEditorProps = {
|
||||
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void;
|
||||
|
||||
onCommandReady?: (cmd: KriEditorCommand | null) => void;
|
||||
|
||||
label?: string;
|
||||
|
||||
value: string;
|
||||
onChange: (html: string) => void;
|
||||
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
|
||||
showPreview?: boolean;
|
||||
previewClassName?: string;
|
||||
|
||||
/**
|
||||
* 모드:
|
||||
* - "wysiwyg": WYSIWYG 전용
|
||||
* - "html": HTML 전용
|
||||
* - "both": 툴바에서 WYSIWYG / HTML 전환 가능
|
||||
* - "sms": SMS 문자 전용 (링크만)
|
||||
*
|
||||
* props.mode 가 없으면 editorMode 를 참고하고,
|
||||
* 둘 다 없으면 "wysiwyg" 으로 동작.
|
||||
*/
|
||||
mode?: KriEditorMode;
|
||||
editorMode?: KriEditorMode;
|
||||
|
||||
// 이미지 업로드 (없으면 이미지 버튼 비활성)
|
||||
onImageUpload?: (file: File) => Promise<UploadResult>;
|
||||
|
||||
// 이미지 압축 옵션
|
||||
maxImageBytes?: number;
|
||||
imageMaxWidth?: number;
|
||||
imageMaxHeight?: number;
|
||||
imageQuality?: number;
|
||||
imageMimeType?: "image/webp" | "image/jpeg";
|
||||
|
||||
// base64 허용 여부 (기본: false)
|
||||
allowBase64?: boolean;
|
||||
|
||||
// HTML을 setHTML 전에 sanitize 할지 여부 (기본: true)
|
||||
sanitizeHtml?: boolean;
|
||||
|
||||
// HTML 전용 모드에서 textarea rows
|
||||
rows?: number;
|
||||
|
||||
// 이미지 업로드 실패 시 콜백
|
||||
onImageUploadError?: (error: unknown) => void;
|
||||
|
||||
// onChange 디바운스 시간 (ms)
|
||||
debounceMs?: number;
|
||||
|
||||
// SMS 모드 전용 props
|
||||
smsTitle?: string; // LMS 제목용
|
||||
changeSmsType?: (type: "SMS" | "LMS") => void;
|
||||
};
|
||||
isSmsReadOnly?: boolean
|
||||
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
|
||||
onCommandReady?: (command: KriEditorCommand | null) => void
|
||||
label?: string
|
||||
value: string
|
||||
onChange: (html: string) => void
|
||||
placeholder?: string
|
||||
className?: string
|
||||
showPreview?: boolean
|
||||
previewClassName?: string
|
||||
mode?: KriEditorMode
|
||||
onImageUpload?: (file: File) => Promise<KriEditorUploadResult>
|
||||
maxImageBytes?: number
|
||||
imageMaxWidth?: number
|
||||
imageMaxHeight?: number
|
||||
imageQuality?: number
|
||||
imageMimeType?: 'image/webp' | 'image/jpeg'
|
||||
allowBase64?: boolean
|
||||
sanitizeHtml?: boolean
|
||||
rows?: number
|
||||
onImageUploadError?: (error: unknown) => void
|
||||
debounceMs?: number
|
||||
smsTitle?: string
|
||||
changeSmsType?: (type: 'SMS' | 'LMS') => void
|
||||
smsMaxBytes?: number
|
||||
lmsMaxBytes?: number
|
||||
toolbar?: KriEditorToolbarConfig | false
|
||||
}
|
||||
|
||||
export type ToolbarState = {
|
||||
fontSize: string;
|
||||
textColor: string | null;
|
||||
highlightColor: string | null;
|
||||
fontSize: string
|
||||
textColor: string | null
|
||||
highlightColor: string | null
|
||||
isBold: boolean
|
||||
isItalic: boolean
|
||||
isUnderline: boolean
|
||||
isStrike: boolean
|
||||
align: 'left' | 'center' | 'right'
|
||||
isBulletList: boolean
|
||||
isOrderedList: boolean
|
||||
isLink: boolean
|
||||
inTable: boolean
|
||||
}
|
||||
|
||||
isBold: boolean;
|
||||
isItalic: boolean;
|
||||
isUnderline: boolean;
|
||||
isStrike: boolean;
|
||||
|
||||
align: "left" | "center" | "right";
|
||||
isBulletList: boolean;
|
||||
isOrderedList: boolean;
|
||||
isLink: boolean;
|
||||
|
||||
inTable: boolean;
|
||||
};
|
||||
export function resolveUploadUrl(result: KriEditorUploadResult): string {
|
||||
return typeof result === 'string' ? result : result.url
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { Editor } from '@tiptap/react';
|
||||
import type { Editor } from '@tiptap/react'
|
||||
|
||||
export function isTipTapEditor(editor: any): editor is Editor {
|
||||
return editor && typeof editor.chain === 'function';
|
||||
export function isTipTapEditor(value: unknown): value is Editor {
|
||||
return Boolean(value && typeof value === 'object' && 'chain' in value && typeof value.chain === 'function')
|
||||
}
|
||||
|
||||
export function isTextAreaElement(element: any): element is HTMLTextAreaElement {
|
||||
return element instanceof HTMLTextAreaElement;
|
||||
}
|
||||
export function isTextAreaElement(value: unknown): value is HTMLTextAreaElement {
|
||||
return typeof HTMLTextAreaElement !== 'undefined' && value instanceof HTMLTextAreaElement
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
interface BodyTitleProps {
|
||||
titleText: string;
|
||||
}
|
||||
|
||||
const BodyTitle = ({titleText}:BodyTitleProps) => {
|
||||
return (
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="font-bold text-2xl">{titleText}</h1>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default BodyTitle
|
||||
@@ -1,143 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Menu, X, ZoomIn, ZoomOut, LogOut } from "lucide-react";
|
||||
import Image from "next/image";
|
||||
import { topMenus } from "@/config/menu.data";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import type {LoginUser} from "@/types/auth";
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
|
||||
interface HeaderProps {
|
||||
isMain: boolean;
|
||||
menuOpen: boolean;
|
||||
activeTopId: string;
|
||||
isViewProjectTitle: boolean;
|
||||
fontSize: number;
|
||||
onToggleMenu: () => void;
|
||||
onNavigate: (path: string) => void;
|
||||
decreaseFontSize: () => void;
|
||||
increaseFontSize: () => void;
|
||||
}
|
||||
|
||||
export const Header = ({
|
||||
isMain,
|
||||
menuOpen,
|
||||
activeTopId,
|
||||
isViewProjectTitle,
|
||||
fontSize,
|
||||
onToggleMenu,
|
||||
onNavigate,
|
||||
decreaseFontSize,
|
||||
increaseFontSize,
|
||||
}: HeaderProps) => {
|
||||
const router = useRouter();
|
||||
const { auth } = useAuth();
|
||||
const mounted = useMounted();
|
||||
const [userInfo, setUserInfo] = useState<LoginUser|undefined>(undefined);
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const projectName = useMemo(() => selectedProject?.prjctName ?? "", [selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
if(auth.user){
|
||||
setUserInfo(auth.user);
|
||||
}
|
||||
else{
|
||||
router.replace("/logout");
|
||||
}
|
||||
}, [auth.user, mounted, router])
|
||||
|
||||
return (
|
||||
<header className="bg-white border-b border-gray-200 sticky top-0 z-40">
|
||||
<div className="flex items-center justify-between px-4 h-16">
|
||||
<div className="flex items-center gap-4">
|
||||
{/* 햄버거 메뉴 */}
|
||||
<div className="w-5">
|
||||
{isMain? null :
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => onToggleMenu()}
|
||||
>
|
||||
{menuOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
{/* 로고 */}
|
||||
<div
|
||||
className="flex items-center gap-2 cursor-pointer"
|
||||
onClick={() => onNavigate("/")}
|
||||
>
|
||||
<div className="w-20 h-10 flex items-center justify-center">
|
||||
<Image
|
||||
src="/kri_logo.png"
|
||||
alt="KRI 로고"
|
||||
width={120}
|
||||
height={40}
|
||||
className="object-contain"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 상단 메뉴 */}
|
||||
<nav className="flex items-center gap-1 ml-25">
|
||||
{topMenus.map((m) => (
|
||||
<Button
|
||||
key={m.id}
|
||||
variant={activeTopId === m.id ? "default" : "ghost"}
|
||||
onClick={() => onNavigate(m.path)}
|
||||
>
|
||||
{m.label}
|
||||
</Button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
<div className="flex flex-grow justify-center">
|
||||
{isViewProjectTitle && projectName &&
|
||||
<h1 className="font-bold text-2xl ml-3">{projectName}</h1>
|
||||
}
|
||||
</div>
|
||||
{/* 우측 컨트롤 */}
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-1 border-r pr-4">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => decreaseFontSize()}
|
||||
title="폰트 작게"
|
||||
>
|
||||
<ZoomOut className="w-4 h-4" />
|
||||
</Button>
|
||||
<span className="text-xs text-gray-500 min-w-[3rem] text-center">
|
||||
{fontSize}px
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => increaseFontSize()}
|
||||
title="폰트 크게"
|
||||
>
|
||||
<ZoomIn className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<span className="text-sm text-gray-600 hidden sm:inline">{userInfo?.userName || ""}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
onClick={() => onNavigate("/logout")}
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">로그아웃</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
78
src/components/layout/KriHeader.tsx
Normal file
78
src/components/layout/KriHeader.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { Menu, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { KriNavigationItem } from './types'
|
||||
|
||||
export interface KriHeaderProps {
|
||||
logo?: ReactNode
|
||||
homePath?: string
|
||||
menus?: KriNavigationItem[]
|
||||
activeMenuId?: string
|
||||
menuOpen?: boolean
|
||||
showMenuButton?: boolean
|
||||
onToggleMenu?: () => void
|
||||
onNavigate?: (path: string, item?: KriNavigationItem) => void
|
||||
center?: ReactNode
|
||||
right?: ReactNode
|
||||
sticky?: boolean
|
||||
className?: string
|
||||
innerClassName?: string
|
||||
}
|
||||
|
||||
export function KriHeader({
|
||||
logo,
|
||||
homePath = '/',
|
||||
menus = [],
|
||||
activeMenuId,
|
||||
menuOpen = false,
|
||||
showMenuButton = true,
|
||||
onToggleMenu,
|
||||
onNavigate,
|
||||
center,
|
||||
right,
|
||||
sticky = true,
|
||||
className,
|
||||
innerClassName,
|
||||
}: KriHeaderProps) {
|
||||
return (
|
||||
<header className={cn('border-b bg-background', sticky && 'sticky top-0 z-40', className)}>
|
||||
<div className={cn('flex h-16 items-center justify-between gap-4 px-4', innerClassName)}>
|
||||
<div className="flex min-w-0 items-center gap-4">
|
||||
{showMenuButton && onToggleMenu ? (
|
||||
<Button type="button" variant="ghost" size="icon" onClick={onToggleMenu} aria-label={menuOpen ? '메뉴 닫기' : '메뉴 열기'}>
|
||||
{menuOpen ? <X className="size-5" /> : <Menu className="size-5" />}
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{logo ? (
|
||||
<button type="button" className="flex shrink-0 items-center cursor-pointer" onClick={() => onNavigate?.(homePath)}>
|
||||
{logo}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{menus.length ? (
|
||||
<nav className="hidden items-center gap-1 md:flex">
|
||||
{menus.map((item) => (
|
||||
<Button
|
||||
key={item.id}
|
||||
type="button"
|
||||
variant={activeMenuId === item.id ? 'default' : 'ghost'}
|
||||
disabled={item.disabled || !item.path}
|
||||
onClick={() => item.path && onNavigate?.(item.path, item)}
|
||||
>
|
||||
{item.label}
|
||||
</Button>
|
||||
))}
|
||||
</nav>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1 text-center">{center}</div>
|
||||
<div className="flex shrink-0 items-center gap-2">{right}</div>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
50
src/components/layout/KriMainLayout.tsx
Normal file
50
src/components/layout/KriMainLayout.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
'use client'
|
||||
|
||||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface KriMainLayoutProps {
|
||||
children: ReactNode
|
||||
header?: ReactNode
|
||||
sidebar?: ReactNode
|
||||
sidebarOpen?: boolean
|
||||
onSidebarOpenChange?: (open: boolean) => void
|
||||
fullHeight?: boolean
|
||||
className?: string
|
||||
bodyClassName?: string
|
||||
mainClassName?: string
|
||||
mainStyle?: CSSProperties
|
||||
}
|
||||
|
||||
export function KriMainLayout({
|
||||
children,
|
||||
header,
|
||||
sidebar,
|
||||
sidebarOpen = false,
|
||||
onSidebarOpenChange,
|
||||
fullHeight = true,
|
||||
className,
|
||||
bodyClassName,
|
||||
mainClassName,
|
||||
mainStyle,
|
||||
}: KriMainLayoutProps) {
|
||||
return (
|
||||
<div className={cn('flex flex-col bg-muted/30', fullHeight && 'min-h-screen', className)}>
|
||||
{header}
|
||||
<div className={cn('flex min-h-0 flex-1', bodyClassName)}>
|
||||
{sidebar}
|
||||
<main className={cn('min-w-0 flex-1 overflow-y-auto p-4', mainClassName)} style={mainStyle}>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
{sidebar && sidebarOpen ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="사이드바 닫기"
|
||||
className="fixed inset-0 z-20 bg-primary/20 lg:hidden"
|
||||
onClick={() => onSidebarOpenChange?.(false)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
22
src/components/layout/KriPageTitle.tsx
Normal file
22
src/components/layout/KriPageTitle.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface KriPageTitleProps {
|
||||
title: ReactNode
|
||||
description?: ReactNode
|
||||
actions?: ReactNode
|
||||
className?: string
|
||||
titleClassName?: string
|
||||
}
|
||||
|
||||
export function KriPageTitle({ title, description, actions, className, titleClassName }: KriPageTitleProps) {
|
||||
return (
|
||||
<div className={cn('flex items-start justify-between gap-4', className)}>
|
||||
<div className="min-w-0">
|
||||
<h1 className={cn('text-2xl font-bold tracking-tight', titleClassName)}>{title}</h1>
|
||||
{description ? <div className="text-muted-foreground mt-1 text-sm">{description}</div> : null}
|
||||
</div>
|
||||
{actions ? <div className="flex shrink-0 items-center gap-2">{actions}</div> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
129
src/components/layout/KriSidebar.tsx
Normal file
129
src/components/layout/KriSidebar.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { KriNavigationItem } from './types'
|
||||
|
||||
export interface KriSidebarProps {
|
||||
items: KriNavigationItem[]
|
||||
isOpen: boolean
|
||||
pathname?: string
|
||||
header?: React.ReactNode
|
||||
openItemIds?: string[]
|
||||
defaultOpenItemIds?: string[]
|
||||
onOpenItemIdsChange?: (ids: string[]) => void
|
||||
onNavigate?: (path: string, item: KriNavigationItem) => void
|
||||
className?: string
|
||||
contentClassName?: string
|
||||
}
|
||||
|
||||
function isActive(item: KriNavigationItem, pathname: string): boolean {
|
||||
if (item.match) return item.match(pathname)
|
||||
if (item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`))) return true
|
||||
return item.children?.some((child) => isActive(child, pathname)) ?? false
|
||||
}
|
||||
|
||||
export function KriSidebar({
|
||||
items,
|
||||
isOpen,
|
||||
pathname = '',
|
||||
header,
|
||||
openItemIds,
|
||||
defaultOpenItemIds = [],
|
||||
onOpenItemIdsChange,
|
||||
onNavigate,
|
||||
className,
|
||||
contentClassName,
|
||||
}: KriSidebarProps) {
|
||||
const [internalOpenIds, setInternalOpenIds] = React.useState(defaultOpenItemIds)
|
||||
const currentOpenIds = openItemIds ?? internalOpenIds
|
||||
|
||||
const setOpenIds = (next: string[]) => {
|
||||
if (openItemIds === undefined) setInternalOpenIds(next)
|
||||
onOpenItemIdsChange?.(next)
|
||||
}
|
||||
|
||||
const toggleItem = (id: string) => {
|
||||
setOpenIds(currentOpenIds.includes(id) ? currentOpenIds.filter((value) => value !== id) : [...currentOpenIds, id])
|
||||
}
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
'fixed top-16 left-0 z-30 h-[calc(100vh-4rem)] overflow-y-auto border-r bg-background transition-all duration-300 lg:static lg:top-0 lg:h-auto lg:translate-x-0',
|
||||
isOpen ? 'w-64 translate-x-0' : 'w-64 -translate-x-full lg:w-0 lg:border-r-0',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className={cn('h-full space-y-4 overflow-y-auto p-4', contentClassName)}>
|
||||
{header}
|
||||
<nav className="space-y-1">
|
||||
{items.map((item) => {
|
||||
const active = isActive(item, pathname)
|
||||
const hasChildren = Boolean(item.children?.length)
|
||||
const opened = currentOpenIds.includes(item.id)
|
||||
const Icon = item.icon
|
||||
|
||||
if (!hasChildren) {
|
||||
return (
|
||||
<Button
|
||||
key={item.id}
|
||||
type="button"
|
||||
variant={active ? 'secondary' : 'ghost'}
|
||||
className="w-full justify-start"
|
||||
disabled={item.disabled || !item.path}
|
||||
onClick={() => item.path && onNavigate?.(item.path, item)}
|
||||
>
|
||||
{Icon ? <Icon className="size-4" /> : null}
|
||||
<span>{item.label}</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={item.id} className="space-y-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant={active ? 'secondary' : 'ghost'}
|
||||
className="w-full justify-between"
|
||||
disabled={item.disabled}
|
||||
onClick={() => toggleItem(item.id)}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
{Icon ? <Icon className="size-4" /> : null}
|
||||
<span>{item.label}</span>
|
||||
</span>
|
||||
<ChevronDown className={cn('size-4 transition-transform', opened && 'rotate-180')} />
|
||||
</Button>
|
||||
|
||||
{opened ? (
|
||||
<div className="ml-6 space-y-1">
|
||||
{item.children?.map((child) => {
|
||||
const childActive = isActive(child, pathname)
|
||||
const ChildIcon = child.icon
|
||||
return (
|
||||
<Button
|
||||
key={child.id}
|
||||
type="button"
|
||||
variant={childActive ? 'secondary' : 'ghost'}
|
||||
className="w-full justify-start"
|
||||
disabled={child.disabled || !child.path}
|
||||
onClick={() => child.path && onNavigate?.(child.path, child)}
|
||||
>
|
||||
{ChildIcon ? <ChildIcon className="size-4" /> : null}
|
||||
<span>{child.label}</span>
|
||||
</Button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {useState, useEffect, ReactNode} from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { Header } from "@/components/layout/Header";
|
||||
import { Sidebar } from "@/components/layout/Sidebar";
|
||||
import {useFontSize} from "@/hooks/useFontSize";
|
||||
import {projectSideMenus, manageSideMenus, topMenus} from "@/config/menu.data";
|
||||
import {cn} from "@/lib/utils";
|
||||
import {FONT_SIZE} from "@/const/commonConst";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
|
||||
type MainLayoutProps = {
|
||||
children: ReactNode;
|
||||
initialFontSize: number; // 🔥 추가
|
||||
};
|
||||
|
||||
const MainLayout = ({ children, initialFontSize }: MainLayoutProps) => {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject();
|
||||
const [menuOpen, setMenuOpen] = useState(true);
|
||||
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
|
||||
|
||||
const isMain = pathname === "/";
|
||||
const isProjectMenu = !pathname.startsWith("/manage");
|
||||
const isViewProjectTitle = !isMain && isProjectMenu && !pathname.startsWith("/project/info")
|
||||
const activeTop = topMenus.find((m) => m.match?.(pathname)) ?? topMenus[0];
|
||||
const sideMenus = isProjectMenu ? projectSideMenus : manageSideMenus;
|
||||
|
||||
// 2단 메뉴 open 상태
|
||||
const [openMenus, setOpenMenus] = useState<Record<string, boolean>>(() => {
|
||||
const initial: Record<string, boolean> = {};
|
||||
|
||||
sideMenus.forEach((item) => {
|
||||
if (
|
||||
item.children?.some((child) => pathname === child.path || pathname.startsWith(child.path + "/"))
|
||||
) {
|
||||
initial[item.id] = true;
|
||||
}
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
const movePage = (path: string) => {
|
||||
router.push(path);
|
||||
};
|
||||
|
||||
const toggleSideMenu = (id: string) => {
|
||||
setOpenMenus((prev) => ({ ...prev, [id]: !prev[id] }));
|
||||
};
|
||||
|
||||
const decreaseFontSize = () =>{
|
||||
setFontSize(Math.max(FONT_SIZE.MIN, fontSize - 2));
|
||||
}
|
||||
|
||||
const increaseFontSize = () =>{
|
||||
setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2));
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSelectedProjectHydrated) return;
|
||||
|
||||
if(!isMain && isProjectMenu && !selectedProject){
|
||||
alert("옳지 않은 접근입니다.");
|
||||
router.replace("/");
|
||||
}
|
||||
}, [isMain, isProjectMenu, isSelectedProjectHydrated, router, selectedProject]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"bg-gray-50 flex flex-col",
|
||||
isMain ? "min-h-screen" : "h-screen overflow-hidden"
|
||||
)}
|
||||
>
|
||||
{/* 헤더 - 고정 폰트 크기 */}
|
||||
<Header
|
||||
isMain={isMain}
|
||||
menuOpen={menuOpen}
|
||||
activeTopId={activeTop.id}
|
||||
isViewProjectTitle={isViewProjectTitle}
|
||||
fontSize={fontSize}
|
||||
onToggleMenu={() => setMenuOpen((prev) => !prev)}
|
||||
onNavigate={movePage}
|
||||
decreaseFontSize={decreaseFontSize}
|
||||
increaseFontSize={increaseFontSize}
|
||||
/>
|
||||
|
||||
{/* 본문 */}
|
||||
<div className={cn("flex flex-1", !isMain && "min-h-0")}>
|
||||
{/* 사이드바 - 고정 폰트 크기 */}
|
||||
{!isMain && (
|
||||
<Sidebar
|
||||
isProjectMenu={isProjectMenu}
|
||||
sideMenus={sideMenus}
|
||||
isOpen={menuOpen}
|
||||
pathname={pathname}
|
||||
openMenus={openMenus}
|
||||
onToggleMenu={toggleSideMenu}
|
||||
onNavigate={movePage}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 메인 콘텐츠만 가변 폰트 크기 적용 */}
|
||||
<main
|
||||
className={cn(
|
||||
"flex-1 p-4",
|
||||
!isMain && "min-h-0 overflow-y-auto"
|
||||
)}
|
||||
// 전역 CSS 변수(--content-font-size)를 실제 렌더에 적용
|
||||
// SSR 단계에서의 초기 폰트 값을 FOUC 없이 유지하기 위해 fallback을 함께 지정
|
||||
style={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
|
||||
>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{/* 모바일 오버레이 */}
|
||||
{!isMain && menuOpen && (
|
||||
<div
|
||||
className="fixed inset-0 z-20 lg:hidden"
|
||||
onClick={() => setMenuOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MainLayout;
|
||||
@@ -1,123 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { SideMenuItem } from "@/config/menu.types";
|
||||
import {SidebarProjectSearch} from "@/components/layout/SidebarProjectSearch";
|
||||
|
||||
interface SidebarProps {
|
||||
isProjectMenu: boolean;
|
||||
sideMenus: SideMenuItem[];
|
||||
isOpen: boolean;
|
||||
pathname: string;
|
||||
openMenus: Record<string, boolean>;
|
||||
onToggleMenu: (id: string) => void;
|
||||
onNavigate: (path: string) => void;
|
||||
}
|
||||
|
||||
export const Sidebar = ({
|
||||
isProjectMenu,
|
||||
sideMenus,
|
||||
isOpen,
|
||||
pathname,
|
||||
openMenus,
|
||||
onToggleMenu,
|
||||
onNavigate,
|
||||
}: SidebarProps) => {
|
||||
const isSideActive = (item: SideMenuItem, current: string) => {
|
||||
if (item.path) {
|
||||
return current === item.path || current.startsWith(item.path + "/");
|
||||
}
|
||||
if (item.children) {
|
||||
return item.children.some(
|
||||
(c) => current === c.path || current.startsWith(c.path + "/")
|
||||
);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={`
|
||||
fixed lg:static top-16 lg:top-0 left-0
|
||||
h-[calc(100vh-4rem)] bg-white border-r border-gray-200
|
||||
transition-all duration-300 z-30 overflow-y-auto
|
||||
lg:translate-x-0
|
||||
${
|
||||
isOpen
|
||||
? "w-64 translate-x-0"
|
||||
: "w-64 -translate-x-full lg:w-0 lg:border-r-0"
|
||||
}
|
||||
`}
|
||||
>
|
||||
<div className="p-4 space-y-4 overflow-y-auto h-full">
|
||||
{isProjectMenu &&
|
||||
<SidebarProjectSearch/>
|
||||
}
|
||||
|
||||
{/* 좌측 메뉴 */}
|
||||
<nav className="space-y-1">
|
||||
{sideMenus.map((item) => {
|
||||
const hasChildren = !!item.children?.length;
|
||||
const opened = openMenus[item.id] ?? false;
|
||||
const active = isSideActive(item, pathname);
|
||||
|
||||
if (!hasChildren && item.path) {
|
||||
return (
|
||||
<Button
|
||||
key={item.id}
|
||||
variant={active ? "secondary" : "ghost"}
|
||||
className="w-full justify-start"
|
||||
onClick={() => onNavigate(item.path!)}
|
||||
>
|
||||
<item.icon className="w-4 h-4" />
|
||||
<span className="ml-2">{item.label}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={item.id} className="space-y-1">
|
||||
<Button
|
||||
variant={active ? "secondary" : "ghost"}
|
||||
className="w-full justify-between"
|
||||
onClick={() => onToggleMenu(item.id)}
|
||||
>
|
||||
<span className="flex items-center">
|
||||
<item.icon className="w-4 h-4" />
|
||||
<span className="ml-2">{item.label}</span>
|
||||
</span>
|
||||
<ChevronDown
|
||||
className={`w-4 h-4 transition-transform ${
|
||||
opened ? "rotate-180" : ""
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
|
||||
{opened && item.children && (
|
||||
<div className="ml-6 space-y-1">
|
||||
{item.children.map((child) => {
|
||||
const childActive =
|
||||
pathname === child.path ||
|
||||
pathname.startsWith(child.path + "/");
|
||||
return (
|
||||
<Button
|
||||
key={child.id}
|
||||
variant={childActive ? "secondary" : "ghost"}
|
||||
className="w-full justify-start"
|
||||
onClick={() => onNavigate(child.path)}
|
||||
>
|
||||
<span className="ml-1">{child.label}</span>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
9
src/components/layout/index.ts
Normal file
9
src/components/layout/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export { KriHeader } from './KriHeader'
|
||||
export { KriMainLayout } from './KriMainLayout'
|
||||
export { KriPageTitle } from './KriPageTitle'
|
||||
export { KriSidebar } from './KriSidebar'
|
||||
export type { KriNavigationItem } from './types'
|
||||
export type { KriHeaderProps } from './KriHeader'
|
||||
export type { KriMainLayoutProps } from './KriMainLayout'
|
||||
export type { KriPageTitleProps } from './KriPageTitle'
|
||||
export type { KriSidebarProps } from './KriSidebar'
|
||||
11
src/components/layout/types.ts
Normal file
11
src/components/layout/types.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import type { ComponentType, ReactNode } from 'react'
|
||||
|
||||
export interface KriNavigationItem {
|
||||
id: string
|
||||
label: ReactNode
|
||||
path?: string
|
||||
icon?: ComponentType<{ className?: string }>
|
||||
children?: KriNavigationItem[]
|
||||
disabled?: boolean
|
||||
match?: (pathname: string) => boolean
|
||||
}
|
||||
44
src/components/list-contact/CollapsibleHistorySection.tsx
Normal file
44
src/components/list-contact/CollapsibleHistorySection.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
'use client'
|
||||
|
||||
import { useId, useState, type ReactNode } from 'react'
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react'
|
||||
|
||||
export type CollapsibleHistorySectionProps = {
|
||||
title: string
|
||||
defaultOpen?: boolean
|
||||
showDivider?: boolean
|
||||
headerExtra?: ReactNode
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
const CollapsibleHistorySection = ({
|
||||
title,
|
||||
defaultOpen = false,
|
||||
showDivider = true,
|
||||
headerExtra,
|
||||
children,
|
||||
}: CollapsibleHistorySectionProps) => {
|
||||
const [open, setOpen] = useState(defaultOpen)
|
||||
const contentId = useId()
|
||||
|
||||
return (
|
||||
<div className={`space-y-2 ${showDivider ? 'border-t pt-3' : ''}`}>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-2 text-left text-sm font-semibold cursor-pointer"
|
||||
aria-expanded={open}
|
||||
aria-controls={contentId}
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
{open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
{title}
|
||||
</button>
|
||||
{headerExtra}
|
||||
</div>
|
||||
{open ? <div id={contentId}>{children}</div> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CollapsibleHistorySection
|
||||
346
src/components/list-contact/ListContactEventPanel.tsx
Normal file
346
src/components/list-contact/ListContactEventPanel.tsx
Normal file
@@ -0,0 +1,346 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { RefreshCw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
|
||||
import CollapsibleHistorySection from '@/components/list-contact/CollapsibleHistorySection'
|
||||
import { useAddListEventMutation, useListEventHistoryQuery, useReserveMutation } from '@/query/list'
|
||||
import { useSendResultBySidQuery } from '@/query/message'
|
||||
import { clientEnv } from '@/lib/env.client'
|
||||
import { ChannelType } from '@kri/common/noti-hub'
|
||||
import type { SendResultInfo } from '@/types/message'
|
||||
import { formatKst } from '@kri/common'
|
||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
||||
import { RESULT_CODE_RESERVATION, RESULT_CODE_UNUSED } from '@/const/projectConst'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
||||
|
||||
const RefreshIconButton = ({ onRefresh, isFetching }: { onRefresh: () => void; isFetching: boolean }) => (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="새로고침"
|
||||
disabled={isFetching}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onRefresh()
|
||||
}}
|
||||
>
|
||||
<RefreshCw className={cn('h-4 w-4', isFetching && 'animate-spin')} />
|
||||
</Button>
|
||||
)
|
||||
|
||||
type ContactEventSectionProps = {
|
||||
title: string
|
||||
prjctIdx: number
|
||||
sid: string
|
||||
resultCodeType: ResultCodeType
|
||||
resultCodes: ResultCode[]
|
||||
showReservation?: boolean
|
||||
showInput?: boolean
|
||||
submitting: boolean
|
||||
onSubmit: (resultCd: number, memo: string, resveDt: string) => Promise<void>
|
||||
}
|
||||
|
||||
const EventHistoryList = ({
|
||||
isLoading,
|
||||
history,
|
||||
resultCodeType,
|
||||
resultCodes,
|
||||
}: {
|
||||
isLoading: boolean
|
||||
history: ReturnType<typeof useListEventHistoryQuery>['data']
|
||||
resultCodeType: ResultCodeType
|
||||
resultCodes: ResultCode[]
|
||||
}) => {
|
||||
const filteredHistory = (history ?? [])
|
||||
.filter((item) => item.eventTy === resultCodeType)
|
||||
.sort((a, b) => new Date(b.regDt).getTime() - new Date(a.regDt).getTime())
|
||||
|
||||
const resolveLabel = (resultCd: number) =>
|
||||
resultCodes.find((code) => code.resultCdTy === resultCodeType && code.resultCd === resultCd)?.resultCdLbl ??
|
||||
String(resultCd)
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
||||
}
|
||||
|
||||
if (filteredHistory.length === 0) {
|
||||
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">이력이 없습니다.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-h-60 overflow-y-auto rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-muted">
|
||||
<tr>
|
||||
<th className="p-2 text-left">결과</th>
|
||||
<th className="p-2 text-left">메모</th>
|
||||
<th className="p-2 text-left">등록자</th>
|
||||
<th className="p-2 text-left">일시</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredHistory.map((item) => (
|
||||
<tr key={item.listEventHistIdx} className="border-t">
|
||||
<td className="p-2">
|
||||
{item.resultCd}.{resolveLabel(item.resultCd)}
|
||||
</td>
|
||||
<td className="p-2">{item.memo || '-'}</td>
|
||||
<td className="p-2">{item.regUser}</td>
|
||||
<td className="p-2">{formatKst(item.regDt, 'dateHourMin')}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ContactEventSection = ({
|
||||
title,
|
||||
prjctIdx,
|
||||
sid,
|
||||
resultCodeType,
|
||||
resultCodes,
|
||||
showReservation = false,
|
||||
showInput = true,
|
||||
submitting,
|
||||
onSubmit,
|
||||
}: ContactEventSectionProps) => {
|
||||
const [resultCd, setResultCd] = useState('')
|
||||
const [memo, setMemo] = useState('')
|
||||
const [resveDt, setResveDt] = useState('')
|
||||
|
||||
const codes = resultCodes.filter((code) => code.resultCdTy === resultCodeType && code.resultCd !== RESULT_CODE_UNUSED)
|
||||
const isReservationSelected = resultCd === String(RESULT_CODE_RESERVATION)
|
||||
|
||||
const historyQuery = useListEventHistoryQuery(prjctIdx, sid, true)
|
||||
|
||||
const handleResultCdChange = (next: string) => {
|
||||
setResultCd(next)
|
||||
if (next === String(RESULT_CODE_RESERVATION) && !resveDt) {
|
||||
setResveDt(getNearestFutureDateTime())
|
||||
}
|
||||
}
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!resultCd) {
|
||||
alert('결과 코드를 선택해주세요.')
|
||||
return
|
||||
}
|
||||
if (isReservationSelected && !resveDt) {
|
||||
alert('예약 날짜/시간을 선택해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
await onSubmit(Number(resultCd), memo, isReservationSelected ? resveDt : '')
|
||||
setMemo('')
|
||||
setResveDt('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3 rounded-lg border bg-white p-4">
|
||||
<h2 className="text-lg font-bold">{title}</h2>
|
||||
|
||||
{showInput ? (
|
||||
<>
|
||||
<RadioGroup value={resultCd} onValueChange={handleResultCdChange} className="grid grid-cols-2 gap-2">
|
||||
{codes.map((code) => (
|
||||
<label key={code.resultCdUUID} className="flex items-center gap-2 text-sm font-bold cursor-pointer">
|
||||
<RadioGroupItem value={String(code.resultCd)} />
|
||||
{code.resultCd}.{code.resultCdLbl}
|
||||
</label>
|
||||
))}
|
||||
</RadioGroup>
|
||||
|
||||
<textarea
|
||||
placeholder="메모"
|
||||
value={memo}
|
||||
onChange={(e) => setMemo(e.target.value)}
|
||||
className="flex min-h-[70px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||
/>
|
||||
|
||||
{showReservation && isReservationSelected ? (
|
||||
<KriDateTimePicker value={resveDt} onChange={setResveDt} placeholder="예약 날짜/시간" />
|
||||
) : null}
|
||||
|
||||
<Button type="button" className="w-full" disabled={submitting} onClick={handleAdd}>
|
||||
{title} 추가
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<CollapsibleHistorySection
|
||||
title={`${title}(최근순)`}
|
||||
showDivider={showInput}
|
||||
headerExtra={<RefreshIconButton onRefresh={() => historyQuery.refetch()} isFetching={historyQuery.isFetching} />}
|
||||
>
|
||||
<EventHistoryList isLoading={historyQuery.isLoading} history={historyQuery.data} resultCodeType={resultCodeType} resultCodes={resultCodes} />
|
||||
</CollapsibleHistorySection>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results: SendResultInfo[] }) => {
|
||||
if (isLoading) {
|
||||
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">발송 이력이 없습니다.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-h-60 overflow-y-auto rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-muted">
|
||||
<tr>
|
||||
<th className="p-2 text-left">수신처</th>
|
||||
<th className="p-2 text-left">결과</th>
|
||||
<th className="p-2 text-left">발송일시</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{results.map((item) => (
|
||||
<tr key={item.cmid} className="border-t">
|
||||
<td className="p-2">{item.destEml || item.destTel || '-'}</td>
|
||||
<td className="p-2">{item.resultViewLabel || item.resultLabel || item.resultCode}</td>
|
||||
<td className="p-2">{formatKst(item.sendDt, 'dateHourMin')}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SendResultHistory = ({ sid, prjctCd }: { sid: string; prjctCd: string }) => {
|
||||
const [tab, setTab] = useState<'email' | 'sms'>('email')
|
||||
|
||||
const emailQuery = useSendResultBySidQuery(sid, prjctCd, clientEnv.REQUEST_SVC, ChannelType.EMAIL, tab === 'email')
|
||||
const smsQuery = useSendResultBySidQuery(sid, prjctCd, clientEnv.REQUEST_SVC, ChannelType.SMS, tab === 'sms')
|
||||
const activeQuery = tab === 'email' ? emailQuery : smsQuery
|
||||
|
||||
const handleTabClick = (e: React.MouseEvent, next: 'email' | 'sms') => {
|
||||
e.stopPropagation()
|
||||
setTab(next)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2 rounded-lg border bg-white p-4">
|
||||
<CollapsibleHistorySection
|
||||
title="발송 현황(최근순)"
|
||||
showDivider={false}
|
||||
headerExtra={
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={tab === 'email' ? 'default' : 'outline'}
|
||||
onClick={(e) => handleTabClick(e, 'email')}
|
||||
>
|
||||
이메일
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={tab === 'sms' ? 'default' : 'outline'}
|
||||
onClick={(e) => handleTabClick(e, 'sms')}
|
||||
>
|
||||
문자
|
||||
</Button>
|
||||
<RefreshIconButton onRefresh={() => activeQuery.refetch()} isFetching={activeQuery.isFetching} />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<SendResultTable isLoading={activeQuery.isLoading} results={activeQuery.data ?? []} />
|
||||
</CollapsibleHistorySection>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export type ListContactEventPanelProps = {
|
||||
prjctIdx: number
|
||||
sid: string
|
||||
prjctCd: string
|
||||
userId: string
|
||||
userRole: number
|
||||
resultCodes: ResultCode[]
|
||||
useContactSenario: boolean
|
||||
contactSenario?: string
|
||||
}
|
||||
|
||||
const ListContactEventPanel = ({
|
||||
prjctIdx,
|
||||
sid,
|
||||
prjctCd,
|
||||
userId,
|
||||
userRole,
|
||||
resultCodes,
|
||||
useContactSenario,
|
||||
contactSenario,
|
||||
}: ListContactEventPanelProps) => {
|
||||
const addListEventMutation = useAddListEventMutation(prjctIdx, sid)
|
||||
const reserveMutation = useReserveMutation(prjctIdx, sid)
|
||||
const showContactInput = userRole !== FIELD_INTERVIEWER_ROLE
|
||||
const showInterviewInput = userRole !== CONTACT_INTERVIEWER_ROLE
|
||||
|
||||
const handleAddEvent = (resultCodeType: ResultCodeType) => async (resultCd: number, memo: string, resveDt: string) => {
|
||||
await addListEventMutation.mutateAsync({
|
||||
prjctIdx,
|
||||
sid: Number(sid),
|
||||
resultCodeType,
|
||||
resultCd,
|
||||
memo,
|
||||
})
|
||||
|
||||
if (resveDt) {
|
||||
await reserveMutation.mutateAsync({ prjctIdx, sid: Number(sid), userId, resveDt })
|
||||
}
|
||||
|
||||
alert('등록되었습니다.')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-[80vh] space-y-4 overflow-y-auto pr-1">
|
||||
<ContactEventSection
|
||||
title="컨택결과"
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
resultCodeType={ResultCodeType.CONTACT}
|
||||
resultCodes={resultCodes}
|
||||
showReservation
|
||||
showInput={showContactInput}
|
||||
submitting={addListEventMutation.isPending || reserveMutation.isPending}
|
||||
onSubmit={handleAddEvent(ResultCodeType.CONTACT)}
|
||||
/>
|
||||
|
||||
<SendResultHistory sid={sid} prjctCd={prjctCd} />
|
||||
|
||||
<ContactEventSection
|
||||
title="인터뷰 요원 확인사항"
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
resultCodeType={ResultCodeType.INTERVIEW}
|
||||
resultCodes={resultCodes}
|
||||
showInput={showInterviewInput}
|
||||
submitting={addListEventMutation.isPending}
|
||||
onSubmit={handleAddEvent(ResultCodeType.INTERVIEW)}
|
||||
/>
|
||||
|
||||
{useContactSenario && contactSenario ? (
|
||||
<div className="space-y-2 rounded-lg border bg-white p-4">
|
||||
<h2 className="text-lg font-bold border-b pb-2">컨택 시나리오</h2>
|
||||
<div className="text-base leading-relaxed" dangerouslySetInnerHTML={{ __html: contactSenario }} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListContactEventPanel
|
||||
285
src/components/list-contact/ListContactInfoPanel.tsx
Normal file
285
src/components/list-contact/ListContactInfoPanel.tsx
Normal file
@@ -0,0 +1,285 @@
|
||||
'use client'
|
||||
|
||||
import { useRef, useState, type ReactNode } from 'react'
|
||||
import { Mail, MessageSquare, Paperclip, Phone, QrCode } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useUploadListItemFileMutation } from '@/query/list'
|
||||
import { ListHeaderConst } from '@/const/listConst'
|
||||
import type { listHeader, ListSearchWithFullResult } from '@/types/list'
|
||||
import type { MessageSendChannel } from '@/types/message'
|
||||
import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess'
|
||||
import { substituteSurveyUrl } from '@/lib/surveyUrl'
|
||||
import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
|
||||
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
||||
import { ctiClient } from '@/lib/cti/ctiClient'
|
||||
import { useCtiConnectionStatus } from '@/hooks/useCtiConnectionStatus'
|
||||
import { useCtiAgentStatus } from '@/hooks/useCtiAgentStatus'
|
||||
import { CTI_ON_CALL_STATUSES } from '@/const/ctiConst'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type ListContactInfoPanelProps = {
|
||||
prjctIdx: number
|
||||
sid: string
|
||||
itrntPrjctCd: string
|
||||
userRole: number
|
||||
isEditing: boolean
|
||||
listHeaders: listHeader[]
|
||||
detail?: ListSearchWithFullResult
|
||||
surveyUrl?: string
|
||||
formValues: Record<number, string>
|
||||
onFieldChange: (listHderId: number, value: string) => void
|
||||
onSaved?: () => void
|
||||
}
|
||||
|
||||
export const buildInitialValues = (listHeaders: listHeader[], detail?: ListSearchWithFullResult) => {
|
||||
const values: Record<number, string> = {}
|
||||
|
||||
for (const header of listHeaders) {
|
||||
if (header.listHderTy === ListHeaderConst.SID) continue
|
||||
if (!isListFieldVisibleForContact(header)) continue
|
||||
if (header.listHderTy === ListHeaderConst.MEMO) {
|
||||
values[header.listHderId] = detail?.memo ?? ''
|
||||
continue
|
||||
}
|
||||
values[header.listHderId] = detail?.itemList?.[header.listHderId] ?? ''
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
|
||||
const disabledContrastClass = 'disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60'
|
||||
|
||||
const FieldRow = ({ label, children }: { label: string; children: ReactNode }) => (
|
||||
<div className="flex items-center gap-3">
|
||||
<Label className="w-24 shrink-0 text-sm font-bold text-foreground">{label}</Label>
|
||||
<div className="min-w-0 flex-1">{children}</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const ListContactInfoPanel = ({
|
||||
prjctIdx,
|
||||
sid,
|
||||
itrntPrjctCd,
|
||||
userRole,
|
||||
isEditing,
|
||||
listHeaders,
|
||||
detail,
|
||||
surveyUrl,
|
||||
formValues,
|
||||
onFieldChange,
|
||||
onSaved,
|
||||
}: ListContactInfoPanelProps) => {
|
||||
const { showDialog } = useDialog()
|
||||
const uploadItemFileMutation = useUploadListItemFileMutation(prjctIdx, sid)
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const [uploadingHeaderId, setUploadingHeaderId] = useState<number | null>(null)
|
||||
const [sendTarget, setSendTarget] = useState<{ channel: MessageSendChannel; headerId: number } | null>(null)
|
||||
const ctiConnectionStatus = useCtiConnectionStatus()
|
||||
const isCtiReady = ctiConnectionStatus === 'open'
|
||||
const ctiAgentStatus = useCtiAgentStatus()
|
||||
const isOnCall = ctiAgentStatus !== null && (CTI_ON_CALL_STATUSES as readonly string[]).includes(ctiAgentStatus)
|
||||
|
||||
const visibleHeaders = listHeaders
|
||||
.filter((header) => isListFieldVisibleForContact(header))
|
||||
.sort((a, b) => a.listHderOrder - b.listHderOrder)
|
||||
|
||||
const substitutedSurveyUrl = surveyUrl ? substituteSurveyUrl(surveyUrl, sid) : ''
|
||||
const hasSurveyResponse = detail?.surveyResult?.lastResultCd !== undefined
|
||||
|
||||
const handleStartSurvey = () => {
|
||||
if (!substitutedSurveyUrl) return
|
||||
window.open(substitutedSurveyUrl, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
const handleSend = (channel: MessageSendChannel, headerId: number) => {
|
||||
setSendTarget({ channel, headerId })
|
||||
showDialog('singleMessageSendDialog')
|
||||
}
|
||||
|
||||
const handleCall = (telNum: string, listHderId: number) => {
|
||||
if (!telNum || !isCtiReady || isOnCall) return
|
||||
ctiClient.makeCall({ dialNumber: telNum, prjctIdx, sid: Number(sid), listHderId })
|
||||
}
|
||||
|
||||
const handlePickFile = (listHderId: number) => {
|
||||
setUploadingHeaderId(listHderId)
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleFileSelected = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
e.target.value = ''
|
||||
if (!file || uploadingHeaderId === null) return
|
||||
|
||||
await uploadItemFileMutation.mutateAsync({ listHderId: uploadingHeaderId, file })
|
||||
setUploadingHeaderId(null)
|
||||
alert('파일이 업로드되었습니다.')
|
||||
onSaved?.()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4 rounded-lg border bg-white p-4">
|
||||
<h2 className="text-lg font-bold">리스트 정보</h2>
|
||||
<input type="file" ref={fileInputRef} className="hidden" onChange={handleFileSelected} />
|
||||
|
||||
{visibleHeaders.map((header) => {
|
||||
if (header.listHderTy === ListHeaderConst.SID) return null
|
||||
|
||||
const editable = isEditing && isListFieldEditableForContact(header, userRole)
|
||||
const value = formValues[header.listHderId] ?? ''
|
||||
const onChange = (next: string) => onFieldChange(header.listHderId, next)
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.MEMO) {
|
||||
return (
|
||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
||||
<textarea
|
||||
className={`flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed ${disabledContrastClass}`}
|
||||
value={value}
|
||||
disabled={!editable}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
</FieldRow>
|
||||
)
|
||||
}
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.TEL_NUM) {
|
||||
return (
|
||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={value}
|
||||
disabled={!editable}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className={disabledContrastClass}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')}
|
||||
disabled={!isCtiReady || isOnCall}
|
||||
title={!isCtiReady ? '전화 시스템에 연결되어 있지 않습니다.' : undefined}
|
||||
onClick={() => handleCall(value, header.listHderId)}
|
||||
>
|
||||
<Phone className="h-4 w-4" />
|
||||
{isOnCall ? '통화중' : '전화'}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="shrink-0 gap-2"
|
||||
onClick={() => handleSend('sms', header.listHderId)}
|
||||
>
|
||||
<MessageSquare className="h-4 w-4" />
|
||||
발송
|
||||
</Button>
|
||||
</div>
|
||||
</FieldRow>
|
||||
)
|
||||
}
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.EMAIL) {
|
||||
return (
|
||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={value}
|
||||
disabled={!editable}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className={disabledContrastClass}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="shrink-0 gap-2"
|
||||
onClick={() => handleSend('email', header.listHderId)}
|
||||
>
|
||||
<Mail className="h-4 w-4" />
|
||||
발송
|
||||
</Button>
|
||||
</div>
|
||||
</FieldRow>
|
||||
)
|
||||
}
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.FILE) {
|
||||
return (
|
||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-sm">{value || '업로드된 파일 없음'}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="shrink-0 gap-2"
|
||||
disabled={!editable || uploadItemFileMutation.isPending}
|
||||
onClick={() => handlePickFile(header.listHderId)}
|
||||
>
|
||||
<Paperclip className="h-4 w-4" />
|
||||
업로드
|
||||
</Button>
|
||||
</div>
|
||||
</FieldRow>
|
||||
)
|
||||
}
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.CONTENT_ITEM && (header.filterContents?.length ?? 0) > 0) {
|
||||
return (
|
||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
||||
<KriSingleSelect
|
||||
items={header.filterContents ?? []}
|
||||
value={value}
|
||||
disabled={!editable}
|
||||
onChange={onChange}
|
||||
getValue={(item) => item}
|
||||
getLabel={(item) => item}
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
className={disabledContrastClass}
|
||||
/>
|
||||
</FieldRow>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
||||
<Input
|
||||
value={value}
|
||||
disabled={!editable}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className={disabledContrastClass}
|
||||
/>
|
||||
</FieldRow>
|
||||
)
|
||||
})}
|
||||
|
||||
{surveyUrl ? (
|
||||
<FieldRow label="Web">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" className="gap-2" onClick={handleStartSurvey}>
|
||||
조사 시작
|
||||
</Button>
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('surveyQrDialog')}>
|
||||
<QrCode className="h-4 w-4" />
|
||||
QR
|
||||
</Button>
|
||||
{!hasSurveyResponse && <span className="text-sm text-muted-foreground">[응답없음]</span>}
|
||||
</div>
|
||||
</FieldRow>
|
||||
) : null}
|
||||
|
||||
<SurveyQrDialog url={substitutedSurveyUrl} />
|
||||
<SingleMessageSendDialog
|
||||
channel={sendTarget?.channel ?? 'sms'}
|
||||
prjctIdx={prjctIdx}
|
||||
itrntPrjctCd={itrntPrjctCd}
|
||||
sid={sid}
|
||||
destHeaderId={sendTarget?.headerId ?? 0}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListContactInfoPanel
|
||||
61
src/components/list-contact/ListUpdateHistoryPanel.tsx
Normal file
61
src/components/list-contact/ListUpdateHistoryPanel.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { useListUpdateHistoryQuery } from '@/query/list'
|
||||
import type { listHeader } from '@/types/list'
|
||||
import CollapsibleHistorySection from '@/components/list-contact/CollapsibleHistorySection'
|
||||
import { formatKst } from '@kri/common'
|
||||
|
||||
export type ListUpdateHistoryPanelProps = {
|
||||
prjctIdx: number
|
||||
sid: string
|
||||
listHeaders: listHeader[]
|
||||
}
|
||||
|
||||
const ListUpdateHistoryPanel = ({ prjctIdx, sid, listHeaders }: ListUpdateHistoryPanelProps) => {
|
||||
const headerNameById = useMemo(
|
||||
() => new Map(listHeaders.map((header) => [header.listHderId, header.listHderNm])),
|
||||
[listHeaders],
|
||||
)
|
||||
const historyQuery = useListUpdateHistoryQuery(prjctIdx, sid, true)
|
||||
const history = historyQuery.data ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-2 rounded-lg border bg-white p-4">
|
||||
<CollapsibleHistorySection title="수정 이력" showDivider={false}>
|
||||
{historyQuery.isLoading ? (
|
||||
<div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
||||
) : history.length === 0 ? (
|
||||
<div className="rounded-md border p-4 text-center text-sm text-muted-foreground">수정 이력이 없습니다.</div>
|
||||
) : (
|
||||
<div className="max-h-60 overflow-y-auto rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-muted">
|
||||
<tr>
|
||||
<th className="p-2 text-left">항목</th>
|
||||
<th className="p-2 text-left">변경 전</th>
|
||||
<th className="p-2 text-left">변경 후</th>
|
||||
<th className="p-2 text-left">수정자</th>
|
||||
<th className="p-2 text-left">일시</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{history.map((item) => (
|
||||
<tr key={item.listUpdateHistIdx} className="border-t">
|
||||
<td className="p-2">{headerNameById.get(item.listHderId) ?? item.listHderId}</td>
|
||||
<td className="p-2">{item.beforeVal || '-'}</td>
|
||||
<td className="p-2">{item.afterVal || '-'}</td>
|
||||
<td className="p-2">{item.regUser}</td>
|
||||
<td className="p-2">{formatKst(item.regDt, 'dateHourMin')}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CollapsibleHistorySection>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListUpdateHistoryPanel
|
||||
77
src/components/list/ListManageActions.tsx
Normal file
77
src/components/list/ListManageActions.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
Download,
|
||||
FileClock,
|
||||
Mail,
|
||||
MessageSquareMore,
|
||||
RotateCcw,
|
||||
Upload,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { ListDownloadMode } from '@/types/list'
|
||||
import type { MessageSendMode } from '@/components/dialog/MessageSendDialog'
|
||||
|
||||
export type ListManageActionsProps = {
|
||||
onReset: () => void
|
||||
onHeaderManage: () => void
|
||||
onUpload: () => void
|
||||
onDownload: (mode: ListDownloadMode) => void
|
||||
onMessageSend: (mode: MessageSendMode) => void
|
||||
onMessageHistory: () => void
|
||||
}
|
||||
|
||||
export function ListManageActions({
|
||||
onReset,
|
||||
onHeaderManage,
|
||||
onUpload,
|
||||
onDownload,
|
||||
onMessageSend,
|
||||
onMessageHistory,
|
||||
}: ListManageActionsProps) {
|
||||
return (
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2 flex-wrap">
|
||||
<Button variant="destructive" className="text-base gap-2" onClick={onReset}>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
리스트 초기화
|
||||
</Button>
|
||||
<Button className="text-base" onClick={onHeaderManage}>
|
||||
헤더 관리
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={onUpload}>
|
||||
<Upload className="w-4 h-4" />
|
||||
리스트 업로드
|
||||
</Button>
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list')}>
|
||||
<Download className="w-4 h-4" />
|
||||
리스트
|
||||
</Button>
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('contact-history')}>
|
||||
<Download className="w-4 h-4" />
|
||||
컨택 이력
|
||||
</Button>
|
||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list-change-history')}>
|
||||
<Download className="w-4 h-4" />
|
||||
리스트 변경 이력
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={() => onDownload('upload-file')}>
|
||||
<Download className="w-4 h-4" />
|
||||
업로드 파일(.zip)
|
||||
</Button>
|
||||
</div>
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('email')}>
|
||||
<Mail className="w-4 h-4" />
|
||||
이메일 발송
|
||||
</Button>
|
||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('sms')}>
|
||||
<MessageSquareMore className="w-4 h-4" />
|
||||
문자 발송
|
||||
</Button>
|
||||
<Button className="text-base gap-2" onClick={onMessageHistory}>
|
||||
<FileClock className="w-4 h-4" />
|
||||
발송 이력
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
500
src/components/list/ListSearchTable.tsx
Normal file
500
src/components/list/ListSearchTable.tsx
Normal file
@@ -0,0 +1,500 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import type { PaginationState, SortingState } from '@tanstack/react-table'
|
||||
import { Funnel, PencilLine } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { DataTable } from '@/components/data-table/DataTable'
|
||||
import type { DataTableColumn, SelectMode } from '@/components/data-table/DataTable.type'
|
||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||
import ListBatchEditDialog, { type BatchEditRow } from '@/components/dialog/ListBatchEditDialog'
|
||||
import ListFilterDialog from '@/components/dialog/ListFilterDialog'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useListSearchQuery, useUpdateListMutation } from '@/query/list'
|
||||
import { getListColumns, LIST_IS_USE_LABEL, type ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import { useAssignTargetRows } from '@/components/assign/AssignTargetList'
|
||||
import { ListHeaderAssignConst, ListHeaderConst } from '@/const/listConst'
|
||||
import {
|
||||
createEmptyListFilter,
|
||||
type FilterHeaderOption,
|
||||
type FilterOperator,
|
||||
type FilterRow,
|
||||
type FilterValueOption,
|
||||
type listHeader,
|
||||
type ListFilter,
|
||||
ListFilterMatchType,
|
||||
ListFilterOperator,
|
||||
type ListHeaderAssignType,
|
||||
type ListOtherItemFilterCondition,
|
||||
type ListSearchRequest,
|
||||
} from '@/types/list'
|
||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import {
|
||||
applyListAccessFilter,
|
||||
getLockedListFilterHeaderTypes,
|
||||
isListFilterVisibleByAccess,
|
||||
isListHeaderVisibleByAccess,
|
||||
} from '@/utils/listAccess'
|
||||
|
||||
export type ListSearchTableProps = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
userRole: number
|
||||
userId: string
|
||||
userCmpn: string
|
||||
resultCodes: ResultCode[]
|
||||
listHeaders: listHeader[]
|
||||
enableBatchEdit?: boolean
|
||||
refreshKey?: number
|
||||
selectMode?: SelectMode
|
||||
filterActions?: ReactNode
|
||||
rightActions?: ReactNode
|
||||
excludeFilterHeaderTypes?: number[]
|
||||
externalAssignFilter?: { type: ListHeaderAssignType; values: string[]; condition?: 'assigned' | 'unassigned' }
|
||||
onCurrentFilterChange?: (filter: ListFilter) => void
|
||||
onSelectedRowsChange?: (rows: ListTableRow[]) => void
|
||||
onRowClick?: (row: ListTableRow) => void
|
||||
onRowDoubleClick?: (row: ListTableRow) => void
|
||||
maxTableHeight?: string
|
||||
initialPagination?: PaginationState
|
||||
onPaginationChange?: (pagination: PaginationState) => void
|
||||
focusRowId?: string
|
||||
}
|
||||
|
||||
const toSidSet = (value: string) =>
|
||||
value
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter((item) => item.length > 0)
|
||||
|
||||
const sanitizeSidInput = (value: string) => {
|
||||
let result = ''
|
||||
let lastChar: 'digit' | 'comma' | 'tilde' | null = null
|
||||
let segmentHasTilde = false
|
||||
|
||||
for (const ch of value) {
|
||||
if (/[0-9]/.test(ch)) {
|
||||
result += ch
|
||||
lastChar = 'digit'
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === ',' && lastChar === 'digit') {
|
||||
result += ch
|
||||
lastChar = 'comma'
|
||||
segmentHasTilde = false
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '~' && lastChar === 'digit' && !segmentHasTilde) {
|
||||
result += ch
|
||||
lastChar = 'tilde'
|
||||
segmentHasTilde = true
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
const toFilterCondition = (row: FilterRow, usesListValue: boolean): Omit<ListOtherItemFilterCondition, 'listHderId'> => {
|
||||
if (row.operator === 'empty') {
|
||||
return { operator: ListFilterOperator.POSITIVE, matchType: ListFilterMatchType.EMPTY, values: [] }
|
||||
}
|
||||
if (row.operator === 'notEmpty') {
|
||||
return { operator: ListFilterOperator.NEGATIVE, matchType: ListFilterMatchType.EMPTY, values: [] }
|
||||
}
|
||||
|
||||
const values = usesListValue ? row.multiValues : [row.textValue.trim()]
|
||||
|
||||
if (row.operator === 'eq') {
|
||||
return { operator: ListFilterOperator.POSITIVE, matchType: ListFilterMatchType.EXACT, values }
|
||||
}
|
||||
if (row.operator === 'neq') {
|
||||
return { operator: ListFilterOperator.NEGATIVE, matchType: ListFilterMatchType.EXACT, values }
|
||||
}
|
||||
if (row.operator === 'contains') {
|
||||
return { operator: ListFilterOperator.POSITIVE, matchType: ListFilterMatchType.CONTAINS, values }
|
||||
}
|
||||
return { operator: ListFilterOperator.NEGATIVE, matchType: ListFilterMatchType.CONTAINS, values }
|
||||
}
|
||||
|
||||
const isAssignHeaderType = (value: number): value is ListHeaderAssignType =>
|
||||
value === ListHeaderAssignConst.OUTSOURCE ||
|
||||
value === ListHeaderAssignConst.CONTACT_INTERVIEWER ||
|
||||
value === ListHeaderAssignConst.FIELD_INTERVIEWER
|
||||
|
||||
const TEXT_LIKE_OPERATORS: FilterOperator[] = ['eq', 'neq', 'contains', 'notContains', 'empty', 'notEmpty']
|
||||
const ASSIGN_LIKE_OPERATORS: FilterOperator[] = ['eq', 'neq', 'empty', 'notEmpty']
|
||||
const IS_USE_OPERATORS: FilterOperator[] = ['eq', 'neq']
|
||||
const FILE_OPERATORS: FilterOperator[] = ['empty', 'notEmpty']
|
||||
|
||||
const getAllowedOperators = (listHderTy: number): FilterOperator[] => {
|
||||
if (listHderTy === ListHeaderConst.IS_USE) return IS_USE_OPERATORS
|
||||
if (isAssignHeaderType(listHderTy) || listHderTy === ListHeaderConst.CONTENT_ITEM) return ASSIGN_LIKE_OPERATORS
|
||||
if (listHderTy === ListHeaderConst.FILE) return FILE_OPERATORS
|
||||
return TEXT_LIKE_OPERATORS
|
||||
}
|
||||
|
||||
const IS_USE_VALUE_OPTIONS: FilterValueOption[] = Object.entries(LIST_IS_USE_LABEL).map(([value, label]) => ({
|
||||
value,
|
||||
label,
|
||||
}))
|
||||
|
||||
export function ListSearchTable({
|
||||
prjctIdx,
|
||||
enabled,
|
||||
userRole,
|
||||
userId,
|
||||
userCmpn,
|
||||
resultCodes,
|
||||
listHeaders,
|
||||
enableBatchEdit = false,
|
||||
refreshKey = 0,
|
||||
selectMode = 'multi',
|
||||
filterActions,
|
||||
rightActions,
|
||||
excludeFilterHeaderTypes,
|
||||
externalAssignFilter,
|
||||
onCurrentFilterChange,
|
||||
onSelectedRowsChange,
|
||||
onRowClick,
|
||||
onRowDoubleClick,
|
||||
maxTableHeight = '66vh',
|
||||
initialPagination,
|
||||
onPaginationChange,
|
||||
focusRowId,
|
||||
}: ListSearchTableProps) {
|
||||
const { showDialog } = useDialog()
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const [searchContactResult, setSearchContactResult] = useState<string[]>([])
|
||||
const [searchInterviewResult, setSearchInterviewResult] = useState<string[]>([])
|
||||
const [searchSurveyResult, setSearchSurveyResult] = useState<string[]>([])
|
||||
const [pagination, setPagination] = useState<PaginationState>(initialPagination ?? { pageIndex: 0, pageSize: 25 })
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
const [filterRows, setFilterRows] = useState<FilterRow[]>([])
|
||||
const [batchRows, setBatchRows] = useState<BatchEditRow[]>([])
|
||||
|
||||
const updateListMutation = useUpdateListMutation(prjctIdx)
|
||||
|
||||
const outsourceTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: ListHeaderAssignConst.OUTSOURCE })
|
||||
const contactTargetRows = useAssignTargetRows({
|
||||
prjctIdx,
|
||||
enabled,
|
||||
assignType: ListHeaderAssignConst.CONTACT_INTERVIEWER,
|
||||
})
|
||||
const fieldTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: ListHeaderAssignConst.FIELD_INTERVIEWER })
|
||||
|
||||
const getValueOptionsForHeader = useCallback(
|
||||
(header: listHeader): FilterValueOption[] | undefined => {
|
||||
if (header.listHderTy === ListHeaderConst.IS_USE) return IS_USE_VALUE_OPTIONS
|
||||
if (header.listHderTy === ListHeaderAssignConst.OUTSOURCE) {
|
||||
return outsourceTargetRows.map((row) => ({ value: row.id, label: row.name }))
|
||||
}
|
||||
if (header.listHderTy === ListHeaderAssignConst.CONTACT_INTERVIEWER) {
|
||||
return contactTargetRows.map((row) => ({ value: row.id, label: row.name }))
|
||||
}
|
||||
if (header.listHderTy === ListHeaderAssignConst.FIELD_INTERVIEWER) {
|
||||
return fieldTargetRows.map((row) => ({ value: row.id, label: row.name }))
|
||||
}
|
||||
if (header.listHderTy === ListHeaderConst.CONTENT_ITEM) {
|
||||
return header.filterContents?.map((content) => ({ value: content, label: content }))
|
||||
}
|
||||
return undefined
|
||||
},
|
||||
[contactTargetRows, fieldTargetRows, outsourceTargetRows],
|
||||
)
|
||||
|
||||
const accessibleListHeaders = useMemo(
|
||||
() => listHeaders.filter((header) => isListHeaderVisibleByAccess(header, userRole)),
|
||||
[listHeaders, userRole],
|
||||
)
|
||||
|
||||
const accessibleFilterHeaders = useMemo(
|
||||
() =>
|
||||
listHeaders.filter(
|
||||
(header) =>
|
||||
header.listHderTy !== ListHeaderConst.SID &&
|
||||
isListFilterVisibleByAccess(header, userRole) &&
|
||||
!excludeFilterHeaderTypes?.includes(header.listHderTy),
|
||||
),
|
||||
[listHeaders, userRole, excludeFilterHeaderTypes],
|
||||
)
|
||||
|
||||
const accessibleFilterHeaderById = useMemo(
|
||||
() => new Map(accessibleFilterHeaders.map((header) => [header.listHderId, header])),
|
||||
[accessibleFilterHeaders],
|
||||
)
|
||||
|
||||
const lockedListFilterHeaderTypes = useMemo(() => getLockedListFilterHeaderTypes(userRole), [userRole])
|
||||
|
||||
const listSearchRequest = useMemo<ListSearchRequest>(() => {
|
||||
const sort = sorting?.[0] ?? { id: 'sid', desc: false as const }
|
||||
const listFilter = createEmptyListFilter()
|
||||
listFilter.sidSet = toSidSet(searchText)
|
||||
listFilter.memoConditions = []
|
||||
listFilter.resultCodeMap = {
|
||||
[ResultCodeType.CONTACT]: searchContactResult.map(Number),
|
||||
[ResultCodeType.INTERVIEW]: searchInterviewResult.map(Number),
|
||||
[ResultCodeType.SURVEY]: searchSurveyResult.map(Number),
|
||||
}
|
||||
|
||||
filterRows.forEach((row) => {
|
||||
const header = accessibleFilterHeaderById.get(row.headerId)
|
||||
if (!header || lockedListFilterHeaderTypes.has(header.listHderTy)) return
|
||||
|
||||
const isEmptyOperator = row.operator === 'empty' || row.operator === 'notEmpty'
|
||||
const usesListValue = getValueOptionsForHeader(header) !== undefined
|
||||
const condition = toFilterCondition(row, usesListValue)
|
||||
const hasValue = isEmptyOperator || condition.values.some((value) => value.trim().length > 0)
|
||||
if (!hasValue) return
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.IS_USE) {
|
||||
listFilter.listUseConditions.push(condition)
|
||||
return
|
||||
}
|
||||
|
||||
if (isAssignHeaderType(header.listHderTy)) {
|
||||
listFilter.assignConditions.push({ assignType: header.listHderTy, ...condition })
|
||||
return
|
||||
}
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.MEMO) {
|
||||
listFilter.memoConditions.push(condition)
|
||||
return
|
||||
}
|
||||
|
||||
listFilter.otherItemConditions.push({
|
||||
listHderId: row.headerId,
|
||||
...condition,
|
||||
})
|
||||
})
|
||||
|
||||
if (externalAssignFilter) {
|
||||
if (externalAssignFilter.condition === 'assigned') {
|
||||
listFilter.assignConditions.push({
|
||||
assignType: externalAssignFilter.type,
|
||||
operator: ListFilterOperator.NEGATIVE,
|
||||
matchType: ListFilterMatchType.EMPTY,
|
||||
})
|
||||
} else if (externalAssignFilter.condition === 'unassigned') {
|
||||
listFilter.assignConditions.push({
|
||||
assignType: externalAssignFilter.type,
|
||||
operator: ListFilterOperator.POSITIVE,
|
||||
matchType: ListFilterMatchType.EMPTY,
|
||||
})
|
||||
} else {
|
||||
listFilter.assignUserMap[externalAssignFilter.type] = externalAssignFilter.values
|
||||
}
|
||||
}
|
||||
|
||||
const restrictedListFilter = applyListAccessFilter(listFilter, { userRole, userId, userCmpn })
|
||||
|
||||
return {
|
||||
listFilter: restrictedListFilter,
|
||||
pageRequest: {
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? 'desc' : 'asc',
|
||||
},
|
||||
}
|
||||
}, [
|
||||
accessibleFilterHeaderById,
|
||||
externalAssignFilter,
|
||||
filterRows,
|
||||
getValueOptionsForHeader,
|
||||
lockedListFilterHeaderTypes,
|
||||
pagination.pageIndex,
|
||||
pagination.pageSize,
|
||||
searchContactResult,
|
||||
searchInterviewResult,
|
||||
searchSurveyResult,
|
||||
searchText,
|
||||
sorting,
|
||||
userCmpn,
|
||||
userId,
|
||||
userRole,
|
||||
])
|
||||
|
||||
const listSearchQuery = useListSearchQuery(prjctIdx, listSearchRequest, enabled)
|
||||
const { refetch } = listSearchQuery
|
||||
|
||||
const columns = useMemo<DataTableColumn<ListTableRow, unknown>[]>(() => {
|
||||
if (!listHeaders.length) return []
|
||||
return getListColumns(listHeaders, resultCodes, userRole)
|
||||
}, [listHeaders, resultCodes, userRole])
|
||||
|
||||
const viewList = useMemo<ListTableRow[]>(
|
||||
() => (listSearchQuery.data?.content ?? []).map((row) => ({ ...row, ...row.itemList })),
|
||||
[listSearchQuery.data],
|
||||
)
|
||||
|
||||
const totalCount = listSearchQuery.data?.totalElements ?? 0
|
||||
const pageCount = listSearchQuery.data?.totalPages ?? 0
|
||||
|
||||
const headerOptions = useMemo(
|
||||
() =>
|
||||
accessibleListHeaders.map((header) => ({
|
||||
id: header.listHderId,
|
||||
label: header.listHderNm,
|
||||
})),
|
||||
[accessibleListHeaders],
|
||||
)
|
||||
|
||||
const filterHeaderOptions = useMemo<FilterHeaderOption[]>(
|
||||
() =>
|
||||
accessibleFilterHeaders.map((header) => ({
|
||||
id: header.listHderId,
|
||||
label: header.listHderNm,
|
||||
allowedOperators: getAllowedOperators(header.listHderTy),
|
||||
valueOptions: getValueOptionsForHeader(header),
|
||||
disabled: lockedListFilterHeaderTypes.has(header.listHderTy),
|
||||
})),
|
||||
[accessibleFilterHeaders, getValueOptionsForHeader, lockedListFilterHeaderTypes],
|
||||
)
|
||||
|
||||
const handleSearchClick = () => {
|
||||
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
||||
}
|
||||
|
||||
const handleFilterConfirm = async (rows: FilterRow[]) => {
|
||||
setFilterRows(rows)
|
||||
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
||||
}
|
||||
|
||||
const handleBatchConfirm = async (rows: BatchEditRow[]) => {
|
||||
setBatchRows(rows)
|
||||
const updateContents = Object.fromEntries(rows.map((row) => [String(row.headerId), row.value]))
|
||||
await updateListMutation.mutateAsync({
|
||||
updateContents,
|
||||
listFilter: listSearchRequest.listFilter,
|
||||
})
|
||||
await listSearchQuery.refetch()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
onCurrentFilterChange?.(listSearchRequest.listFilter)
|
||||
}, [listSearchRequest.listFilter, onCurrentFilterChange])
|
||||
|
||||
useEffect(() => {
|
||||
onPaginationChange?.(pagination)
|
||||
}, [pagination, onPaginationChange])
|
||||
|
||||
useEffect(() => {
|
||||
setFilterRows((prev) => {
|
||||
const next = prev.filter((row) => {
|
||||
const header = accessibleFilterHeaderById.get(row.headerId)
|
||||
return !!header && !lockedListFilterHeaderTypes.has(header.listHderTy)
|
||||
})
|
||||
return next.length === prev.length ? prev : next
|
||||
})
|
||||
}, [accessibleFilterHeaderById, lockedListFilterHeaderTypes])
|
||||
|
||||
useEffect(() => {
|
||||
if (!refreshKey) return
|
||||
refetch()
|
||||
}, [refetch, refreshKey])
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Search SID"
|
||||
className="h-9 bg-white flex-1 min-w-0"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(sanitizeSidInput(e.target.value))}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<KriMultiSelect
|
||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.CONTACT)}
|
||||
value={searchContactResult}
|
||||
onChange={setSearchContactResult}
|
||||
getValue={(item) => String(item.resultCd)}
|
||||
getLabel={(item) => item.resultCdLbl}
|
||||
placeholder="컨택 결과"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<KriMultiSelect
|
||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.INTERVIEW)}
|
||||
value={searchInterviewResult}
|
||||
onChange={setSearchInterviewResult}
|
||||
getValue={(item) => String(item.resultCd)}
|
||||
getLabel={(item) => item.resultCdLbl}
|
||||
placeholder="면접 결과"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<KriMultiSelect
|
||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.SURVEY)}
|
||||
value={searchSurveyResult}
|
||||
onChange={setSearchSurveyResult}
|
||||
getValue={(item) => String(item.resultCd)}
|
||||
getLabel={(item) => item.resultCdLbl}
|
||||
placeholder="설문 결과"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<Button className="text-lg shrink-0" onClick={handleSearchClick}>
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap justify-between">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listFilterDialog')}>
|
||||
<Funnel className="w-4 h-4" />
|
||||
필터
|
||||
</Button>
|
||||
{filterActions}
|
||||
{enableBatchEdit ? (
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')}>
|
||||
<PencilLine className="w-4 h-4" />
|
||||
일괄 수정
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{rightActions ? <div className="flex items-center gap-2 flex-wrap">{rightActions}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<DataTable<ListTableRow>
|
||||
columns={columns}
|
||||
data={viewList}
|
||||
getRowId={(row) => String(row.sid)}
|
||||
focusRowId={focusRowId}
|
||||
isClient={false}
|
||||
pageCount={pageCount}
|
||||
totalCount={totalCount}
|
||||
pagination={pagination}
|
||||
onPaginationChange={setPagination}
|
||||
onSortingChange={setSorting}
|
||||
selectMode={selectMode}
|
||||
onRowSelectionChange={onSelectedRowsChange}
|
||||
onRowClick={onRowClick}
|
||||
onRowDoubleClick={onRowDoubleClick}
|
||||
pageSizeOptions={[25, 50, 100]}
|
||||
maxBodyHeight={maxTableHeight}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ListFilterDialog headerOptions={filterHeaderOptions} initialRows={filterRows} onConfirm={handleFilterConfirm} />
|
||||
{enableBatchEdit ? (
|
||||
<ListBatchEditDialog
|
||||
headerOptions={headerOptions}
|
||||
appliedFilters={Object.fromEntries(filterRows.map((row) => [row.headerId, row.multiValues]))}
|
||||
initialRows={batchRows}
|
||||
onConfirm={handleBatchConfirm}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {useCallback, useEffect, useRef, useState} from "react";
|
||||
import {useCallback, useEffect, useMemo, useRef, useState} from "react";
|
||||
import {
|
||||
ChannelType,
|
||||
MessageType,
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
Template,
|
||||
TemplateSms,
|
||||
TemplateSummary
|
||||
} from "@/types/messageTemplate";
|
||||
} from "@kri/common/noti-hub";
|
||||
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
|
||||
import {Label} from "@/components/ui/label";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
@@ -21,7 +21,7 @@ import {Button} from "@/components/ui/button";
|
||||
import { isBlank } from "@kri/common";
|
||||
import {cn} from "@/lib/utils";
|
||||
import {ProjectMainTemplateUpdateRequest} from "@/types/project";
|
||||
import { DataVerification } from "@/types/common";
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import {
|
||||
useTemplateListQuery,
|
||||
useMainTemplateIdxQuery,
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
useUploadTemplateBodyImageMutation,
|
||||
} from "@/query/message";
|
||||
import {listHeader} from "@/types/list";
|
||||
import {useListHeaderQuery} from "@/query/list";
|
||||
|
||||
interface MessageTemplateProps {
|
||||
pageTitle: string;
|
||||
@@ -43,7 +44,6 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
const editorCmdRef = useRef<KriEditorCommand | null>(null);
|
||||
const sessionTempUrlsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
const [listHderList, setListHderList] = useState<listHeader[]>([]);
|
||||
const [selectedTemplate, setSelectedTemplate] = useState<Template>(defaultTemplate);
|
||||
const [selectedTemplateIdx, setSelectedTemplateIdx] = useState<number | null>(null);
|
||||
|
||||
@@ -67,9 +67,11 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled);
|
||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled);
|
||||
const templateDetailQuery = useTemplateQuery(selectedTemplateIdx ?? 0, enabled && !!selectedTemplateIdx);
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
|
||||
const templateList: TemplateSummary[] = templateListQuery.data ?? [];
|
||||
const mainTemplateIdx = mainTemplateQuery.data ?? null;
|
||||
const templateList = useMemo<TemplateSummary[]>(() => templateListQuery.data ?? [], [templateListQuery.data]);
|
||||
const mainTemplateIdx = useMemo<number | null>(() => mainTemplateQuery.data ?? null, [mainTemplateQuery.data]);
|
||||
const listHderList = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
|
||||
// Mutations
|
||||
const saveTemplateMutation = useSaveTemplateMutation(chnnlTy, itrntPrjctCd);
|
||||
@@ -79,6 +81,9 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
// 대표 템플릿 체크 상태(사용자 의도)
|
||||
const [mainDesired, setMainDesired] = useState(false);
|
||||
|
||||
// 대표 템플릿 최초 1회 자동 선택 여부
|
||||
const mainTemplateAppliedRef = useRef(false);
|
||||
|
||||
// selectedProject 변경 시 초기화
|
||||
useEffect(() => {
|
||||
if (!selectedProject) return;
|
||||
@@ -89,11 +94,17 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
setSelectedTemplateIdx(null);
|
||||
setSelectedTemplate(projectDefaultTemplate);
|
||||
setMainDesired(false);
|
||||
mainTemplateAppliedRef.current = false;
|
||||
|
||||
// TODO: 프로젝트별 리스트 헤더 조회로 교체
|
||||
setListHderList([]);
|
||||
}, [selectedProject, defaultTemplate]);
|
||||
|
||||
// 대표 템플릿이 있으면 최초 1회 자동 선택
|
||||
useEffect(() => {
|
||||
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return;
|
||||
mainTemplateAppliedRef.current = true;
|
||||
if (mainTemplateIdx) setSelectedTemplateIdx(mainTemplateIdx);
|
||||
}, [enabled, mainTemplateQuery.isSuccess, mainTemplateIdx]);
|
||||
|
||||
// 템플릿 상세가 도착하면 draft에 주입
|
||||
useEffect(() => {
|
||||
const d = templateDetailQuery.data;
|
||||
@@ -205,11 +216,11 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
};
|
||||
|
||||
const handleImageUpload = useCallback(
|
||||
async (file: File): Promise<{ url: string }> => {
|
||||
if (!selectedProject) return { url: "" };
|
||||
async (file: File): Promise<string> => {
|
||||
if (!selectedProject) return "";
|
||||
const url = await uploadBodyImageMutation.mutateAsync(file);
|
||||
sessionTempUrlsRef.current.add(url);
|
||||
return { url };
|
||||
return url;
|
||||
},
|
||||
[selectedProject, uploadBodyImageMutation]
|
||||
);
|
||||
@@ -364,7 +375,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-h-32 overflow-y-auto">
|
||||
<div className="max-h-50 overflow-y-auto">
|
||||
{listHderList.map((h) => {
|
||||
const placeholder = `[\$${h.listHderNm}]`;
|
||||
return (
|
||||
@@ -376,10 +387,10 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
handleVariableClick(placeholder);
|
||||
}}
|
||||
>
|
||||
<div className="py-2 px-3 text-center border-r text-base">
|
||||
<div className="py-2 px-3 text-center border-r text-sm">
|
||||
{h.listHderNm}
|
||||
</div>
|
||||
<div className="py-2 px-3 text-center text-base">
|
||||
<div className="py-2 px-3 text-center text-sm">
|
||||
{placeholder}
|
||||
</div>
|
||||
</div>
|
||||
@@ -436,7 +447,9 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
|
||||
{!isSms && (
|
||||
<KriEditor
|
||||
editorMode={"both"}
|
||||
//mode="both"
|
||||
mode="wysiwyg"
|
||||
showPreview={true}
|
||||
value={selectedTemplate.tmplatBody ?? "<p></p>"}
|
||||
onChange={(html: string) => setTemplateBody(html)}
|
||||
placeholder="이메일 내용을 입력해 주세요"
|
||||
@@ -453,7 +466,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
{isSms && (
|
||||
<div className="mt-6 lg:mt-0 lg:border-l lg:pl-6">
|
||||
<KriEditor
|
||||
editorMode={"sms"}
|
||||
mode="sms"
|
||||
value={(selectedTemplate as TemplateSms).tmplatBody ?? ""}
|
||||
onChange={(html: string) => setTemplateBody(html)}
|
||||
placeholder="문자 내용을 입력해 주세요"
|
||||
|
||||
92
src/components/progress/DateProgressSection.tsx
Normal file
92
src/components/progress/DateProgressSection.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { KriLineChart } from '@/components/chart'
|
||||
import type { ProgressDateResponse } from '@/types/progress'
|
||||
import type { ResultCodeColumn } from './resultCodeColumns'
|
||||
|
||||
export type DateProgressSectionProps = {
|
||||
title: string
|
||||
subtitle: string
|
||||
rows: ProgressDateResponse[]
|
||||
resultCodeColumns: ResultCodeColumn[]
|
||||
}
|
||||
|
||||
export function DateProgressSection({ title, subtitle, rows, resultCodeColumns }: DateProgressSectionProps) {
|
||||
const sortedRows = useMemo(
|
||||
() => [...rows].sort((a, b) => (a.contactDate ?? '').localeCompare(b.contactDate ?? '')),
|
||||
[rows],
|
||||
)
|
||||
|
||||
const categories = useMemo(() => sortedRows.map((row) => row.contactDate ?? ''), [sortedRows])
|
||||
|
||||
const series = useMemo(() => {
|
||||
const totalSeries = {
|
||||
name: 'Total',
|
||||
data: sortedRows.map((row) => row.totalCount ?? 0),
|
||||
option: { type: 'bar' },
|
||||
}
|
||||
|
||||
const resultSeries = resultCodeColumns.map(({ resultCd, label }) => ({
|
||||
name: label,
|
||||
data: sortedRows.map((row) => row.resultCodeCountMap?.[resultCd] ?? 0),
|
||||
}))
|
||||
|
||||
return [totalSeries, ...resultSeries]
|
||||
}, [sortedRows, resultCodeColumns])
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<p className="text-base font-semibold">{title}</p>
|
||||
<p className="text-xs text-muted-foreground">{subtitle}</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border p-2">
|
||||
<KriLineChart categories={categories} series={series} height={320} />
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border overflow-auto max-h-[320px]">
|
||||
<table className="w-full text-sm whitespace-nowrap">
|
||||
<thead className="sticky top-0 z-10 bg-blue-50">
|
||||
<tr>
|
||||
<th className="h-9 px-3 text-center font-semibold border-b">일자</th>
|
||||
<th className="h-9 px-3 text-center font-semibold border-b">시작</th>
|
||||
<th className="h-9 px-3 text-center font-semibold border-b">종료</th>
|
||||
<th className="h-9 px-3 text-center font-semibold border-b">Total</th>
|
||||
{resultCodeColumns.map(({ resultCd, label }) => (
|
||||
<th key={resultCd} className="h-9 px-3 text-center font-semibold border-b">
|
||||
{label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sortedRows.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4 + resultCodeColumns.length} className="h-16 text-center text-muted-foreground">
|
||||
데이터가 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{sortedRows.map((row, index) => (
|
||||
<tr key={`${row.contactDate}-${index}`} className="border-b last:border-b-0">
|
||||
<td className="h-9 px-3 text-center">{row.contactDate ?? '-'}</td>
|
||||
<td className="h-9 px-3 text-center">{row.startTime ?? '-'}</td>
|
||||
<td className="h-9 px-3 text-center">{row.endTime ?? '-'}</td>
|
||||
<td className="h-9 px-3 text-center">{(row.totalCount ?? 0).toLocaleString()}</td>
|
||||
{resultCodeColumns.map(({ resultCd }) => (
|
||||
<td key={resultCd} className="h-9 px-3 text-center">
|
||||
{(row.resultCodeCountMap?.[resultCd] ?? 0).toLocaleString()}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default DateProgressSection
|
||||
173
src/components/progress/ProgressPageContent.tsx
Normal file
173
src/components/progress/ProgressPageContent.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import KriDateRangePicker from "@/components/common/KriDateRangePicker";
|
||||
import { KriSelect } from "@/components/common/KriSelect";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useItrntUserList } from "@/hooks/useItrntUserList";
|
||||
import { useAssignedCmpnIdsQuery } from "@/query/project";
|
||||
import { useCmpnListQuery } from "@/query/cmpn";
|
||||
import { useResultCodesQuery } from "@/query/project";
|
||||
import { useDateProgressQuery, useLastDateProgressQuery, useUserProgressQuery } from "@/query/progress";
|
||||
import type { ProgressEventTypeValue } from "@/types/progress";
|
||||
import type { ResultCodeType } from "@/types/project";
|
||||
import { UserProgressTable } from "./UserProgressTable";
|
||||
import { DateProgressSection } from "./DateProgressSection";
|
||||
import { buildResultCodeColumns } from "./resultCodeColumns";
|
||||
import { isExternalManager, isFieldWorkUser, isInternalManager } from "@/utils/userRole";
|
||||
|
||||
const getFirstDayOfMonth = (date: Date) => {
|
||||
const d = new Date(date.getFullYear(), date.getMonth(), 1);
|
||||
return d.toISOString().slice(0, 10);
|
||||
};
|
||||
|
||||
const getLastDayOfMonth = (date: Date) => {
|
||||
const d = new Date(date.getFullYear(), date.getMonth() + 1, 0);
|
||||
return d.toISOString().slice(0, 10);
|
||||
};
|
||||
|
||||
export type ProgressPageContentProps = {
|
||||
eventTy: ProgressEventTypeValue;
|
||||
resultCdTy: ResultCodeType;
|
||||
pageTitle: string;
|
||||
domainLabel: string;
|
||||
personLabel: string;
|
||||
};
|
||||
|
||||
export function ProgressPageContent({ eventTy, resultCdTy, pageTitle, domainLabel, personLabel }: ProgressPageContentProps) {
|
||||
const mounted = useMounted();
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const { users, isLoading: usersLoading } = useItrntUserList();
|
||||
|
||||
const [dateRange, setDateRange] = useState(() => {
|
||||
const now = new Date();
|
||||
return { from: getFirstDayOfMonth(now), to: getLastDayOfMonth(now) };
|
||||
});
|
||||
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
|
||||
const [selectedCmpnId, setSelectedCmpnId] = useState("ALL");
|
||||
|
||||
const userRole = auth.user?.userRole ?? 0;
|
||||
const isFieldworkRole = isFieldWorkUser(userRole);
|
||||
const isExternalAdminRole = isExternalManager(userRole);
|
||||
const showCmpnSelect = isInternalManager(userRole);
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && !usersLoading && prjctIdx > 0 && !!dateRange.from && !!dateRange.to;
|
||||
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled);
|
||||
const resultCodeColumns = useMemo(
|
||||
() => buildResultCodeColumns(resultCodesQuery.data ?? [], resultCdTy),
|
||||
[resultCodesQuery.data, resultCdTy],
|
||||
);
|
||||
|
||||
const userNameMap = useMemo(() => {
|
||||
const map: Record<string, string> = {};
|
||||
(users ?? []).forEach((user) => {
|
||||
map[user.userId] = user.userNm;
|
||||
});
|
||||
return map;
|
||||
}, [users]);
|
||||
|
||||
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled && showCmpnSelect);
|
||||
const cmpnListQuery = useCmpnListQuery();
|
||||
|
||||
const cmpnOptions = useMemo(() => {
|
||||
const cmpnList = cmpnListQuery.data ?? [];
|
||||
const cmpnMap = new Map(cmpnList.map((cmpn) => [cmpn.cmpnId, cmpn]));
|
||||
const assignedIds = assignedCmpnIdsQuery.data ?? [];
|
||||
const ownCmpn = cmpnList.find((cmpn) => cmpn.ownCmpn);
|
||||
|
||||
const ids = new Set(assignedIds);
|
||||
if (ownCmpn) ids.add(ownCmpn.cmpnId);
|
||||
|
||||
return Array.from(ids)
|
||||
.map((cmpnId) => cmpnMap.get(cmpnId))
|
||||
.filter((cmpn): cmpn is NonNullable<typeof cmpn> => !!cmpn);
|
||||
}, [cmpnListQuery.data, assignedCmpnIdsQuery.data]);
|
||||
|
||||
const forcedUserId = isFieldworkRole ? auth.user?.userId : undefined;
|
||||
const forcedCmpnId = isExternalAdminRole ? auth.user?.userCmpn : undefined;
|
||||
const effectiveCmpnId = forcedCmpnId ?? (selectedCmpnId === "ALL" ? undefined : selectedCmpnId);
|
||||
|
||||
const searchRequest = useMemo(
|
||||
() => ({
|
||||
startDt: dateRange.from ? `${dateRange.from}T00:00:00` : undefined,
|
||||
endDt: dateRange.to ? `${dateRange.to}T23:59:59` : undefined,
|
||||
userId: forcedUserId,
|
||||
cmpnId: effectiveCmpnId,
|
||||
}),
|
||||
[dateRange.from, dateRange.to, forcedUserId, effectiveCmpnId],
|
||||
);
|
||||
|
||||
const filteredSearchRequest = useMemo(
|
||||
() => ({ ...searchRequest, userId: forcedUserId ?? (selectedUserId ?? undefined) }),
|
||||
[searchRequest, forcedUserId, selectedUserId],
|
||||
);
|
||||
|
||||
const userProgressQuery = useUserProgressQuery(prjctIdx, eventTy, searchRequest, enabled);
|
||||
const dateProgressQuery = useDateProgressQuery(prjctIdx, eventTy, filteredSearchRequest, enabled);
|
||||
const lastDateProgressQuery = useLastDateProgressQuery(prjctIdx, eventTy, filteredSearchRequest, enabled);
|
||||
|
||||
const handleSelectUser = (userId: string | null) => {
|
||||
setSelectedUserId(userId);
|
||||
};
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-8 text-sm">
|
||||
<AppPageTitle titleText={pageTitle} />
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<KriDateRangePicker value={dateRange} onChange={setDateRange} className="w-80" />
|
||||
{showCmpnSelect && (
|
||||
<KriSelect
|
||||
items={cmpnOptions}
|
||||
value={selectedCmpnId}
|
||||
onChange={setSelectedCmpnId}
|
||||
getValue={(cmpn) => cmpn.cmpnId}
|
||||
getLabel={(cmpn) => cmpn.cmpnAlias}
|
||||
placeholder="회사 선택"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<p className="text-base font-semibold">{domainLabel} 현황</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
기준 {personLabel} 목록을 기준으로 결과코드별 인원수를 확인할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
<UserProgressTable
|
||||
rows={userProgressQuery.data ?? []}
|
||||
resultCodeColumns={resultCodeColumns}
|
||||
userNameMap={userNameMap}
|
||||
selectedUserId={selectedUserId}
|
||||
onSelectUser={handleSelectUser}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DateProgressSection
|
||||
title={`일자별 ${domainLabel} 현황(전체)`}
|
||||
subtitle={`일자별 입력된 ${domainLabel} 진행 현황을 전체 결과를 기준으로 집계하는 현황입니다.`}
|
||||
rows={dateProgressQuery.data ?? []}
|
||||
resultCodeColumns={resultCodeColumns}
|
||||
/>
|
||||
|
||||
<DateProgressSection
|
||||
title={`일자별 ${domainLabel} 현황(마지막 기준)`}
|
||||
subtitle={`일자별 입력된 ${domainLabel} 진행 현황을 최고 결과를 기준으로 집계하는 현황입니다.`}
|
||||
rows={lastDateProgressQuery.data ?? []}
|
||||
resultCodeColumns={resultCodeColumns}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ProgressPageContent;
|
||||
152
src/components/progress/UserProgressTable.tsx
Normal file
152
src/components/progress/UserProgressTable.tsx
Normal file
@@ -0,0 +1,152 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { ProgressUserResponse } from '@/types/progress'
|
||||
import type { ResultCodeColumn } from './resultCodeColumns'
|
||||
|
||||
export type UserProgressTableProps = {
|
||||
rows: ProgressUserResponse[]
|
||||
resultCodeColumns: ResultCodeColumn[]
|
||||
userNameMap: Record<string, string>
|
||||
selectedUserId: string | null
|
||||
onSelectUser: (userId: string | null) => void
|
||||
}
|
||||
|
||||
type SortKey = 'userId' | 'totalCount' | `rc-${number}`
|
||||
type SortState = { key: SortKey; dir: 'asc' | 'desc' } | null
|
||||
|
||||
const getSortValue = (row: ProgressUserResponse, key: SortKey, userNameMap: Record<string, string>) => {
|
||||
if (key === 'userId') return userNameMap[row.userId ?? ''] ?? row.userId ?? ''
|
||||
if (key === 'totalCount') return row.totalCount ?? 0
|
||||
const resultCd = Number(key.slice(3))
|
||||
return row.resultCodeCountMap?.[resultCd] ?? 0
|
||||
}
|
||||
|
||||
const pct = (count: number, total: number) => (total > 0 ? `(${((count / total) * 100).toFixed(1)})` : '(0.0)')
|
||||
|
||||
const SortIcon = ({ column, sort }: { column: SortKey; sort: SortState }) => {
|
||||
if (!sort || sort.key !== column) return <ArrowUpDown className="size-3 text-muted-foreground" />
|
||||
return sort.dir === 'asc' ? <ArrowUp className="size-3" /> : <ArrowDown className="size-3" />
|
||||
}
|
||||
|
||||
export function UserProgressTable({
|
||||
rows,
|
||||
resultCodeColumns,
|
||||
userNameMap,
|
||||
selectedUserId,
|
||||
onSelectUser,
|
||||
}: UserProgressTableProps) {
|
||||
const [sort, setSort] = useState<SortState>(null)
|
||||
|
||||
const total = useMemo(() => {
|
||||
const totalCount = rows.reduce((acc, row) => acc + (row.totalCount ?? 0), 0)
|
||||
const resultCodeCountMap: Record<number, number> = {}
|
||||
resultCodeColumns.forEach(({ resultCd }) => {
|
||||
resultCodeCountMap[resultCd] = rows.reduce((acc, row) => acc + (row.resultCodeCountMap?.[resultCd] ?? 0), 0)
|
||||
})
|
||||
return { totalCount, resultCodeCountMap }
|
||||
}, [rows, resultCodeColumns])
|
||||
|
||||
const sortedRows = useMemo(() => {
|
||||
if (!sort) return rows
|
||||
const list = [...rows]
|
||||
list.sort((a, b) => {
|
||||
const av = getSortValue(a, sort.key, userNameMap)
|
||||
const bv = getSortValue(b, sort.key, userNameMap)
|
||||
const compared = typeof av === 'string' && typeof bv === 'string' ? av.localeCompare(bv, 'ko') : Number(av) - Number(bv)
|
||||
return sort.dir === 'asc' ? compared : -compared
|
||||
})
|
||||
return list
|
||||
}, [rows, sort, userNameMap])
|
||||
|
||||
const toggleSort = (key: SortKey) => {
|
||||
setSort((prev) => {
|
||||
if (!prev || prev.key !== key) return { key, dir: 'asc' }
|
||||
if (prev.dir === 'asc') return { key, dir: 'desc' }
|
||||
return null
|
||||
})
|
||||
}
|
||||
|
||||
const headerButtonClass = 'flex items-center gap-1 mx-auto cursor-pointer select-none'
|
||||
|
||||
return (
|
||||
<div className="rounded-md border overflow-auto max-h-[420px]">
|
||||
<table className="w-full text-sm whitespace-nowrap">
|
||||
<thead className="sticky top-0 z-20 bg-blue-50">
|
||||
<tr>
|
||||
<th className="h-9 px-3 text-center font-semibold border-b">
|
||||
<button type="button" className={headerButtonClass} onClick={() => toggleSort('userId')}>
|
||||
담당자 <SortIcon column="userId" sort={sort} />
|
||||
</button>
|
||||
</th>
|
||||
<th className="h-9 px-3 text-center font-semibold border-b">
|
||||
<button type="button" className={headerButtonClass} onClick={() => toggleSort('totalCount')}>
|
||||
Total <SortIcon column="totalCount" sort={sort} />
|
||||
</button>
|
||||
</th>
|
||||
{resultCodeColumns.map(({ resultCd, label }) => (
|
||||
<th key={resultCd} className="h-9 px-3 text-center font-semibold border-b">
|
||||
<button type="button" className={headerButtonClass} onClick={() => toggleSort(`rc-${resultCd}`)}>
|
||||
{label} <SortIcon column={`rc-${resultCd}`} sort={sort} />
|
||||
</button>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr className="sticky top-9 z-10 bg-gray-100 font-semibold border-b">
|
||||
<td className="h-9 px-3 text-center">Total</td>
|
||||
<td className="h-9 px-3 text-center">{total.totalCount.toLocaleString()}</td>
|
||||
{resultCodeColumns.map(({ resultCd }) => {
|
||||
const count = total.resultCodeCountMap[resultCd] ?? 0
|
||||
return (
|
||||
<td key={resultCd} className="h-9 px-3 text-center">
|
||||
{count.toLocaleString()} {pct(count, total.totalCount)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
|
||||
{sortedRows.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={2 + resultCodeColumns.length} className="h-16 text-center text-muted-foreground">
|
||||
데이터가 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
|
||||
{sortedRows.map((row) => {
|
||||
const userId = row.userId ?? ''
|
||||
const rowTotal = row.totalCount ?? 0
|
||||
const selected = selectedUserId === userId
|
||||
return (
|
||||
<tr
|
||||
key={userId}
|
||||
className={cn(
|
||||
'border-b last:border-b-0 cursor-pointer hover:bg-muted/50',
|
||||
selected && 'bg-muted font-semibold',
|
||||
)}
|
||||
onClick={() => onSelectUser(selected ? null : userId)}
|
||||
>
|
||||
<td className="h-9 px-3 text-center">{userNameMap[userId] ?? userId}</td>
|
||||
<td className="h-9 px-3 text-center">{rowTotal.toLocaleString()}</td>
|
||||
{resultCodeColumns.map(({ resultCd }) => {
|
||||
const count = row.resultCodeCountMap?.[resultCd] ?? 0
|
||||
return (
|
||||
<td key={resultCd} className="h-9 px-3 text-center">
|
||||
{count.toLocaleString()} {pct(count, rowTotal)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default UserProgressTable
|
||||
15
src/components/progress/resultCodeColumns.ts
Normal file
15
src/components/progress/resultCodeColumns.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { ResultCode, ResultCodeType } from "@/types/project";
|
||||
|
||||
export type ResultCodeColumn = {
|
||||
resultCd: number;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export const buildResultCodeColumns = (
|
||||
resultCodeArray: ResultCode[],
|
||||
resultCdTy: ResultCodeType,
|
||||
): ResultCodeColumn[] =>
|
||||
resultCodeArray
|
||||
.filter((rc) => rc.resultCdTy === resultCdTy)
|
||||
.sort((a, b) => a.resultCd - b.resultCd)
|
||||
.map((rc) => ({ resultCd: rc.resultCd, label: `${rc.resultCd}.${rc.resultCdLbl}` }));
|
||||
@@ -1,16 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { Provider as JotaiProvider } from "jotai";
|
||||
import { LoadingOverlay } from "@/components/common/LoadingOverlay";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import { QueryProvider } from "@kri/common/query";
|
||||
import { QueryLoadingSync } from "./QueryLoadingSync";
|
||||
import { CtiConnectionSync } from "./CtiConnectionSync";
|
||||
|
||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<JotaiProvider>
|
||||
<QueryProvider>
|
||||
<QueryLoadingSync />
|
||||
<LoadingOverlay />
|
||||
<CtiConnectionSync />
|
||||
<LoadingOverlayAdapter />
|
||||
{children}
|
||||
</QueryProvider>
|
||||
</JotaiProvider>
|
||||
|
||||
8
src/components/providers/CtiConnectionSync.tsx
Normal file
8
src/components/providers/CtiConnectionSync.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useCtiConnection } from "@/hooks/useCtiConnection";
|
||||
|
||||
export function CtiConnectionSync() {
|
||||
useCtiConnection();
|
||||
return null;
|
||||
}
|
||||
58
src/components/table-column/CmpnTableColumn.tsx
Normal file
58
src/components/table-column/CmpnTableColumn.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Pencil } from "lucide-react";
|
||||
import type { CmpnInfo } from "@/types/cmpn";
|
||||
|
||||
export type CmpnColumnsActions = {
|
||||
onEdit: (cmpnId: string) => void
|
||||
}
|
||||
|
||||
export const getCmpnColumns = (actions: CmpnColumnsActions): ColumnDef<CmpnInfo>[] => [
|
||||
{
|
||||
accessorKey: "cmpnId",
|
||||
header: "회사 ID",
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "cmpnAlias",
|
||||
header: "별칭",
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "cmpnTel",
|
||||
header: "전화번호",
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "ownCmpn",
|
||||
header: "자사 여부",
|
||||
cell: ({ row }) => (row.original.ownCmpn ? "Y" : "N"),
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "memo",
|
||||
header: "메모",
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "관리",
|
||||
cell: ({ row }) => (
|
||||
<div
|
||||
className="flex items-center justify-center gap-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => actions.onEdit(row.original.cmpnId)}
|
||||
aria-label="수정"
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false,
|
||||
},
|
||||
];
|
||||
@@ -1,46 +1,18 @@
|
||||
import { DataTableColumn } from "@/components/data-table/DataTable.type";
|
||||
import {ListContactResult, listHeader, ListResultBase, ListSendResult} from "@/types/list";
|
||||
import { ListHeaderAssignConst, ListHeaderConst } from "@/const/listConst";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {ListContactResult, listHeader, ListIsUse, ListResultBase, ListSendResult} from "@/types/list";
|
||||
import { ListHeaderConst, ListHeaderDefaultConst, ListHeaderDefaultFieldConst } from "@/const/listConst";
|
||||
import { formatKst } from "@kri/common";
|
||||
import { ResultCode, ResultCodeType } from "@/types/project";
|
||||
import { isListHeaderVisibleByAccess } from "@/utils/listAccess";
|
||||
|
||||
export type ListTableRow = Record<string, unknown>;
|
||||
|
||||
const getAssignColumns = (userRole: number): DataTableColumn<ListTableRow>[] => {
|
||||
const targets: Array<{ id: string; header: string; key: number }> = [];
|
||||
const DEFAULT_FIELD_BY_HEADER_TYPE: Record<number, string | undefined> = ListHeaderDefaultFieldConst;
|
||||
|
||||
if (userRole < 9000) {
|
||||
targets.push(
|
||||
{ id: "assignOutsource", header: "외주 SV", key: ListHeaderAssignConst.OUTSOURCE },
|
||||
{ id: "assignContactInterviewer", header: "컨택원", key: ListHeaderAssignConst.CONTACT_INTERVIEWER },
|
||||
{ id: "assignFieldInterviewer", header: "면접원", key: ListHeaderAssignConst.FIELD_INTERVIEWER }
|
||||
);
|
||||
} else if (userRole === 9002) {
|
||||
targets.push({
|
||||
id: "assignContactInterviewer",
|
||||
header: "컨택원",
|
||||
key: ListHeaderAssignConst.CONTACT_INTERVIEWER,
|
||||
});
|
||||
} else if (userRole === 9003) {
|
||||
targets.push({
|
||||
id: "assignFieldInterviewer",
|
||||
header: "면접원",
|
||||
key: ListHeaderAssignConst.FIELD_INTERVIEWER,
|
||||
});
|
||||
}
|
||||
|
||||
const columns: DataTableColumn<ListTableRow>[] = [];
|
||||
targets.forEach((target) => {
|
||||
columns.push({
|
||||
id: target.id,
|
||||
header: target.header,
|
||||
accessorFn: (row) => (row.assignList as Record<number, string> | undefined)?.[target.key] ?? "",
|
||||
enableSorting: false,
|
||||
});
|
||||
});
|
||||
|
||||
return columns;
|
||||
export const LIST_IS_USE_LABEL: Record<ListIsUse, string> = {
|
||||
[ListIsUse.UNUSABLE]: "불가",
|
||||
[ListIsUse.USABLE]: "허용",
|
||||
[ListIsUse.TEST]: "테스트",
|
||||
};
|
||||
|
||||
const getResultColumns = (resultCodeArray: ResultCode[]): DataTableColumn<ListTableRow>[] => {
|
||||
@@ -98,7 +70,7 @@ const getResultColumns = (resultCodeArray: ResultCode[]): DataTableColumn<ListTa
|
||||
id: "mailSendResult",
|
||||
header: "email 발송 결과",
|
||||
cell: ({ row }) =>
|
||||
formatSendResult(row.original.emailSendResult as ListSendResult | undefined),
|
||||
formatSendResult(row.original.mailSendResult as ListSendResult | undefined),
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
@@ -123,7 +95,15 @@ const getResultColumns = (resultCodeArray: ResultCode[]): DataTableColumn<ListTa
|
||||
},
|
||||
];
|
||||
|
||||
return columns;
|
||||
const resultColumnOrder = new Map([
|
||||
["contactResult", 0],
|
||||
["interviewResult", 1],
|
||||
["surveyStatus", 2],
|
||||
["mailSendResult", 3],
|
||||
["smsSendResult", 4],
|
||||
]);
|
||||
|
||||
return columns.sort((a, b) => (resultColumnOrder.get(a.id ?? "") ?? 0) - (resultColumnOrder.get(b.id ?? "") ?? 0));
|
||||
};
|
||||
|
||||
export const getListColumns = (
|
||||
@@ -131,49 +111,57 @@ export const getListColumns = (
|
||||
resultCodeArray: ResultCode[],
|
||||
userRole: number
|
||||
): DataTableColumn<ListTableRow>[] => {
|
||||
const visibleHeaders = listHeaders.filter((header) => {
|
||||
if (!header.useColView) return false;
|
||||
if (header.listHderTy === ListHeaderConst.SID) return true;
|
||||
const visibleHeaders = listHeaders
|
||||
.filter((header) => isListHeaderVisibleByAccess(header, userRole))
|
||||
.sort((a, b) => a.listHderOrder - b.listHderOrder);
|
||||
|
||||
if (
|
||||
header.listHderTy === ListHeaderAssignConst.OUTSOURCE ||
|
||||
header.listHderTy === ListHeaderAssignConst.CONTACT_INTERVIEWER ||
|
||||
header.listHderTy === ListHeaderAssignConst.FIELD_INTERVIEWER
|
||||
) {
|
||||
return false;
|
||||
const headerColumns: DataTableColumn<ListTableRow>[] = visibleHeaders.map((header) => {
|
||||
const field = DEFAULT_FIELD_BY_HEADER_TYPE[header.listHderTy];
|
||||
|
||||
if (field === ListHeaderDefaultFieldConst[ListHeaderDefaultConst.OUTSOURCE]) {
|
||||
return {
|
||||
id: `assign-${header.listHderTy}`,
|
||||
header: header.listHderNm,
|
||||
accessorFn: (row) => (row.assignList as Record<number, string> | undefined)?.[header.listHderTy] ?? "",
|
||||
enableSorting: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (userRole >= 9000) return header.useIntrvwerView;
|
||||
return true;
|
||||
if (field === ListHeaderDefaultFieldConst[ListHeaderDefaultConst.IS_USE]) {
|
||||
return {
|
||||
id: field,
|
||||
header: header.listHderNm,
|
||||
accessorFn: (row) => LIST_IS_USE_LABEL[row[field] as ListIsUse] ?? "",
|
||||
enableSorting: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (field) {
|
||||
return {
|
||||
id: field,
|
||||
header: header.listHderNm,
|
||||
accessorFn: (row) => row[field] ?? "",
|
||||
enableSorting: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.FILE) {
|
||||
return {
|
||||
id: `file-${header.listHderId}`,
|
||||
header: header.listHderNm,
|
||||
accessorFn: (row) => (row[String(header.listHderId)] ? "업로드O" : ""),
|
||||
enableSorting: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
accessorKey: String(header.listHderId),
|
||||
header: header.listHderNm,
|
||||
enableSorting: true,
|
||||
};
|
||||
});
|
||||
|
||||
const headerColumns: DataTableColumn<ListTableRow>[] = visibleHeaders.map((header) => ({
|
||||
accessorKey: String(header.listHderId),
|
||||
header: header.listHderNm,
|
||||
enableSorting: true,
|
||||
}));
|
||||
|
||||
const startLabel = userRole === 9003 ? "면접 시작" : "컨택 시작";
|
||||
const startColumn: DataTableColumn<ListTableRow> = {
|
||||
id: "contactStart",
|
||||
header: startLabel,
|
||||
cell: () => (
|
||||
<Button size="sm" variant="outline" className="h-8 px-2">
|
||||
{startLabel}
|
||||
</Button>
|
||||
),
|
||||
enableSorting: false,
|
||||
};
|
||||
|
||||
const sidColumnIndex = visibleHeaders.findIndex((header) => header.listHderTy === ListHeaderConst.SID);
|
||||
if (sidColumnIndex < 0) {
|
||||
headerColumns.unshift(startColumn);
|
||||
} else {
|
||||
headerColumns.splice(sidColumnIndex + 1, 0, startColumn);
|
||||
}
|
||||
|
||||
const resultColumns = getResultColumns(resultCodeArray);
|
||||
const assignColumns = userRole < 9000 ? getAssignColumns(userRole) : [];
|
||||
|
||||
return [...headerColumns, ...resultColumns, ...assignColumns];
|
||||
return [...headerColumns, ...resultColumns];
|
||||
};
|
||||
|
||||
@@ -3,7 +3,8 @@ import {Button} from "@/components/ui/button";
|
||||
import {Pencil, Trash2} from "lucide-react";
|
||||
import {UserInfo} from "@/types/user";
|
||||
import {formatKst} from "@kri/common";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import type { CmpnInfo } from "@/types/cmpn";
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +13,11 @@ export type UserColumnsActions = {
|
||||
onDelete: (userId: string) => void
|
||||
}
|
||||
|
||||
export const getUserColumns = (actions: UserColumnsActions, userRoleArray:MultiSelectOption[]): ColumnDef<UserInfo>[] => [
|
||||
export const getUserColumns = (
|
||||
actions: UserColumnsActions,
|
||||
userRoleArray:MultiSelectOption[],
|
||||
userCmpnArray: CmpnInfo[] = []
|
||||
): ColumnDef<UserInfo>[] => [
|
||||
{
|
||||
accessorKey: "userId",
|
||||
header: "아이디",
|
||||
@@ -20,6 +25,10 @@ export const getUserColumns = (actions: UserColumnsActions, userRoleArray:MultiS
|
||||
},
|
||||
{
|
||||
accessorKey: "userCmpn",
|
||||
cell: ({row}) => {
|
||||
const cmpn = userCmpnArray.find((c) => c.cmpnId === row.original.userCmpn);
|
||||
return cmpn?.cmpnAlias || row.original.userCmpn;
|
||||
},
|
||||
header: "소속",
|
||||
enableSorting: true,
|
||||
},
|
||||
|
||||
@@ -5,7 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-base font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
|
||||
220
src/components/ui/calendar.tsx
Normal file
220
src/components/ui/calendar.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
DayPicker,
|
||||
getDefaultClassNames,
|
||||
type DayButton,
|
||||
} from "react-day-picker"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) =>
|
||||
date.toLocaleString("default", { month: "short" }),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"relative flex flex-col gap-4 md:flex-row",
|
||||
defaultClassNames.months
|
||||
),
|
||||
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute inset-0 bg-popover opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"font-medium select-none",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "flex h-8 items-center gap-1 rounded-md pr-1 pl-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none",
|
||||
defaultClassNames.weekday
|
||||
),
|
||||
week: cn("mt-2 flex w-full", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"w-(--cell-size) select-none",
|
||||
defaultClassNames.week_number_header
|
||||
),
|
||||
week_number: cn(
|
||||
"text-[0.8rem] text-muted-foreground select-none",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"group/day relative aspect-square h-full w-full p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-md",
|
||||
props.showWeekNumber
|
||||
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
|
||||
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"rounded-l-md bg-accent",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"rounded-md bg-accent text-accent-foreground data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return (
|
||||
<div
|
||||
data-slot="calendar"
|
||||
ref={rootRef}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return (
|
||||
<ChevronRightIcon
|
||||
className={cn("size-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
className,
|
||||
day,
|
||||
modifiers,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toLocaleDateString()}
|
||||
data-selected-single={
|
||||
modifiers.selected &&
|
||||
!modifiers.range_start &&
|
||||
!modifiers.range_end &&
|
||||
!modifiers.range_middle
|
||||
}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
@@ -11,7 +11,6 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
"placeholder:text-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
58
src/components/ui/scroll-area.tsx
Normal file
58
src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="relative flex-1 rounded-full bg-border"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
@@ -42,7 +42,8 @@ function TabsTrigger({
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"cursor-pointer",
|
||||
"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
Reference in New Issue
Block a user