260427_01_ENH: 리스트 다이얼로그 및 리스트 작업 시작

This commit is contained in:
2026-04-27 09:55:51 +09:00
parent 1953b6528b
commit 6944064377
45 changed files with 2560 additions and 419 deletions

View File

@@ -1,25 +1,392 @@
"use client";
'use client'
import {useFontSizeValue} from "@/hooks/useFontSize";
import {useMounted} from "@/hooks/useMounted";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import BodyTitle from "@/components/layout/BodyTitle";
import {useSelectedProject} from "@/hooks/useSelectedProject";
import ProjectTitle from "@/components/layout/ProjectTitle";
import { useMemo, useState } from 'react'
import { PaginationState, SortingState } from '@tanstack/react-table'
import {
Download,
FileClock,
Funnel,
Mail,
MessageSquareMore,
PencilLine,
RotateCcw,
Upload,
} from 'lucide-react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { DataTable } from '@/components/data-table/DataTable'
import type { DataTableColumn } from '@/components/data-table/DataTable.type'
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
import { LoadingOverlay } from '@/components/common/LoadingOverlay'
import { useMounted } from '@/hooks/useMounted'
import { useAuth } from '@/hooks/useAuth'
import { useDialog } from '@/hooks/useDialog'
import { useSelectedProject } from '@/hooks/useSelectedProject'
import { useListHeaderQuery, useListSearchQuery } from '@/query/list'
import { useResultCodesQuery } from '@/query/project'
import { getListColumns, ListTableRow } from '@/components/table-column/ListTableColumn'
import { ListSearchRequest } from '@/types/list'
import { ResultCode, ResultCodeType } from '@/types/project'
import { ListHeaderAssignConst } from '@/const/listConst'
import ListResetDialog, { ListResetScope, ListResetTarget } from '@/components/dialog/ListResetDialog'
import ListUploadDialog, { ListUploadHistory, ValidationOption } from '@/components/dialog/ListUploadDialog'
import ListHeaderManageDialog, { ListHeaderManageRow } from '@/components/dialog/ListHeaderManageDialog'
import ListBatchEditDialog, { BatchEditRow } from '@/components/dialog/ListBatchEditDialog'
import ListFilterDialog, { FilterRow } from '@/components/dialog/ListFilterDialog'
import ListDownloadDialog, { ListDownloadMode } from '@/components/dialog/ListDownloadDialog'
import MessageSendDialog, {
MessageSendMode,
MessageSendPayload,
MessageTemplateOption,
} from '@/components/dialog/MessageSendDialog'
import MessageHistoryDialog, { MessageHistoryRow } from '@/components/dialog/MessageHistoryDialog'
const uploadHistoryMock: ListUploadHistory[] = [
{ round: 1, fileName: 'a.xlsx', userId: 'admin', uploadCount: 3500, uploadAt: '2025-10-30T11:00:00Z' },
{ round: 2, fileName: '1.xlsx', userId: 'admin', uploadCount: 100, uploadAt: '2025-10-30T12:00:00Z' },
{ round: 3, fileName: '2.xlsx', userId: 'admin', uploadCount: 2000, uploadAt: '2025-10-30T13:00:00Z' },
]
const messageTemplateMock: MessageTemplateOption[] = [
{
id: 'sms-1',
name: '[SMS] Contact Notice',
title: 'Survey Request',
body: 'Please participate in the survey.',
},
{
id: 'email-1',
name: '[EMAIL] Contact Notice',
title: 'Survey Participation Guide',
body: 'Please click the link and complete the survey.',
},
]
const messageHistoryMock: MessageHistoryRow[] = [
{
id: 1,
type: 'sms',
title: 'Survey Request',
templateName: 'SMS Template A',
sendInfo: '010-xxxx-xxxx',
targetHeader: 'Phone Number',
targetCount: 405,
successCount: 405,
failCount: 0,
createdAt: '03.06 14:37',
sendAt: '03.06 14:30 (Reserve)',
status: 'Done',
templatePreview: 'Please participate in the survey.',
targetPreview: ['010-1234-5678', '010-1234-1111'],
successPreview: ['sid 1: success', 'sid 2: success'],
failPreview: [],
},
{
id: 2,
type: 'email',
title: 'Please answer this survey',
templateName: 'EMAIL Template A',
sendInfo: 'info@kric.com',
targetHeader: 'Email',
targetCount: 405,
successCount: 395,
failCount: 10,
createdAt: '03.06 14:37',
sendAt: '03.06 14:47 (Instant)',
status: 'Requested',
templatePreview: 'Please click the link and complete the survey.',
targetPreview: ['aa@kric.com', 'bb@kric.com'],
successPreview: ['sid 3: success', 'sid 4: success'],
failPreview: ['sid 5: bounce', 'sid 6: invalid'],
},
]
const ListManagePage = () => {
const fontSize = useFontSizeValue();
const mounted = useMounted();
const mounted = useMounted()
const { auth } = useAuth()
const { showDialog } = useDialog()
const { selectedProject } = useSelectedProject()
if (!mounted) return <LoadingOverlay force />;
const [searchText, setSearchText] = useState('')
const [searchContactResult, setSearchContactResult] = useState<string[]>([])
const [searchInterviewResult, setSearchInterviewResult] = useState<string[]>([])
const [searchSurveyResult, setSearchSurveyResult] = useState<string[]>([])
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 })
const [sorting, setSorting] = useState<SortingState>([])
const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list')
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
const [filterRows, setFilterRows] = useState<FilterRow[]>([])
const [batchRows, setBatchRows] = useState<BatchEditRow[]>([])
const userRole = auth?.user?.userRole ?? 9000
const prjctIdx = selectedProject?.prjctIdx ?? 0
const enabled = mounted && prjctIdx > 0
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
const listSearchRequest = useMemo<ListSearchRequest>(() => {
const sort = sorting?.[0] ?? { id: 'sid', desc: true as const }
return {
listFilter: {
sidSet: [],
listUseSet: [],
assignUserMap: {
[ListHeaderAssignConst.OUTSOURCE]: [],
[ListHeaderAssignConst.CONTACT_INTERVIEWER]: [],
[ListHeaderAssignConst.FIELD_INTERVIEWER]: [],
},
memo: '',
otherItems: {},
},
pageRequest: {
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
sortBy: sort.id,
sortDir: sort.desc ? 'desc' : 'asc',
},
}
}, [pagination, sorting])
const listSearchQuery = useListSearchQuery(prjctIdx, listSearchRequest, enabled)
const columns = useMemo<DataTableColumn<ListTableRow, unknown>[]>(() => {
if (!listHeaderQuery.data) return []
return getListColumns(listHeaderQuery.data, resultCodeArray, userRole)
}, [listHeaderQuery.data, resultCodeArray, 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(
() =>
(listHeaderQuery.data ?? []).map((header) => ({
id: header.listHderId,
label: header.listHderNm,
})),
[listHeaderQuery.data],
)
const headerManageRows = useMemo<ListHeaderManageRow[]>(
() =>
(listHeaderQuery.data ?? []).map((header) => ({
id: header.listHderId,
name: header.listHderNm,
visible: header.useColView,
locked: header.listHderGrad === 0,
})),
[listHeaderQuery.data],
)
const filterHeaderOptions = useMemo(
() => headerOptions.map((item) => ({ ...item, values: ['A', 'B', 'C'] })),
[headerOptions],
)
const messageTargetHeaders = useMemo(() => {
const matched = headerOptions.filter((header) => /email|phone|tel/i.test(header.label))
return matched.length > 0 ? matched : headerOptions.slice(0, 1)
}, [headerOptions])
const handleSearchClick = () => {
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
}
const openDownloadDialog = (mode: ListDownloadMode) => {
setDownloadMode(mode)
showDialog('listDownloadDialog')
}
const openMessageDialog = (mode: MessageSendMode) => {
setMessageSendMode(mode)
showDialog('messageSendDialog')
}
const handleResetConfirm = async (payload: { target: ListResetTarget; scope: ListResetScope }) => {
void payload
alert('List reset action callback placeholder.')
}
const handleUploadConfirm = async (file: File, validation: ValidationOption) => {
void file
void validation
alert('List upload action callback placeholder.')
}
const handleDownloadTemplate = async () => {
alert('Template download callback placeholder.')
}
const handleHeaderManageConfirm = async (rows: ListHeaderManageRow[]) => {
void rows
alert('Header manage action callback placeholder.')
}
const handleFilterConfirm = async (rows: FilterRow[]) => {
setFilterRows(rows)
alert('Filter action callback placeholder.')
}
const handleBatchConfirm = async (rows: BatchEditRow[]) => {
setBatchRows(rows)
alert('Batch edit action callback placeholder.')
}
const handleDownloadConfirm = async (payload: { mode: ListDownloadMode; onlyFiltered: boolean }) => {
void payload
alert('Download action callback placeholder.')
}
const handleMessageSendConfirm = async (payload: MessageSendPayload) => {
void payload
alert('Message send action callback placeholder.')
}
if (!mounted) return <LoadingOverlay force />
return (
<div className="space-y-6 content-text-sm">
<div>
This is Manage List Page <span>{fontSize}</span>
<div className="flex gap-2 items-center">
<div className="flex flex-1 items-center gap-2 flex-wrap">
<Button variant="destructive" className="content-text-base gap-2" onClick={() => showDialog('listResetDialog')}>
<RotateCcw className="w-4 h-4" />
리스트 초기화
</Button>
<Button className="content-text-base" onClick={() => showDialog('listHeaderManageDialog')}>
헤더 관리
</Button>
<Button className="content-text-base gap-2" onClick={() => showDialog('listUploadDialog')}>
<Upload className="w-4 h-4" />
리스트 업로드
</Button>
<Button className="content-text-base bg-excel gap-2" onClick={() => openDownloadDialog('list')}>
<Download className="w-4 h-4" />
리스트
</Button>
<Button className="content-text-base bg-excel gap-2" onClick={() => openDownloadDialog('contact-history')}>
<Download className="w-4 h-4" />
컨택 이력
</Button>
<Button className="content-text-base bg-excel gap-2" onClick={() => openDownloadDialog('list-change-history')}>
<Download className="w-4 h-4" />
리스트 변경 이력
</Button>
<Button className="content-text-base gap-2" onClick={() => openDownloadDialog('upload-file')}>
<Download className="w-4 h-4" />
업로드 파일(.zip)
</Button>
</div>
<Button className="content-text-base bg-blue gap-2" onClick={() => openMessageDialog('email')}>
<Mail className="w-4 h-4" />
이메일 발송
</Button>
<Button className="content-text-base bg-blue gap-2" onClick={() => openMessageDialog('sms')}>
<MessageSquareMore className="w-4 h-4" />
문자 발송
</Button>
<Button className="content-text-base gap-2" onClick={() => showDialog('messageHistoryDialog')}>
<FileClock className="w-4 h-4" />
발송 이력
</Button>
</div>
</div>
);
};
export default ListManagePage;
<div className="flex gap-2 items-center">
<div className="flex flex-1 items-center gap-2 flex-wrap">
<Input
placeholder="SID ',' '~' 사용 가능"
className="w-100 h-9 bg-white"
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
/>
<KriMultiSelect
items={resultCodeArray.filter((item) => item.resultCdTy === ResultCodeType.CONTACT)}
value={searchContactResult}
onChange={setSearchContactResult}
getValue={(item) => String(item.resultCd)}
getLabel={(item) => item.resultCdLbl}
placeholder="컨택 결과"
widthClassName="w-70"
heightClassName="h-9"
/>
<KriMultiSelect
items={resultCodeArray.filter((item) => item.resultCdTy === ResultCodeType.INTERVIEW)}
value={searchInterviewResult}
onChange={setSearchInterviewResult}
getValue={(item) => String(item.resultCd)}
getLabel={(item) => item.resultCdLbl}
placeholder="면접 결과"
widthClassName="w-70"
heightClassName="h-9"
/>
<KriMultiSelect
items={resultCodeArray.filter((item) => item.resultCdTy === ResultCodeType.SURVEY)}
value={searchSurveyResult}
onChange={setSearchSurveyResult}
getValue={(item) => String(item.resultCd)}
getLabel={(item) => item.resultCdLbl}
placeholder="설문 결과"
widthClassName="w-70"
heightClassName="h-9"
/>
<Button className="content-text-lg" onClick={handleSearchClick}>
검색
</Button>
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listFilterDialog')}>
<Funnel className="w-4 h-4" />
필터
</Button>
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')}>
<PencilLine className="w-4 h-4" />
일괄 수정
</Button>
</div>
</div>
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
<DataTable<ListTableRow>
columns={columns}
data={viewList}
isClient={false}
pageCount={pageCount}
totalCount={totalCount}
onPaginationChange={setPagination}
onSortingChange={setSorting}
selectMode="click-event"
pageSizeOptions={[10, 20, 30, 50]}
/>
</div>
<ListResetDialog onConfirm={handleResetConfirm} />
<ListUploadDialog onUpload={handleUploadConfirm} onDownloadTemplate={handleDownloadTemplate} uploadHistory={uploadHistoryMock} />
<ListHeaderManageDialog rows={headerManageRows} onConfirm={handleHeaderManageConfirm} />
<ListFilterDialog headerOptions={filterHeaderOptions} initialRows={filterRows} onConfirm={handleFilterConfirm} />
<ListBatchEditDialog
headerOptions={headerOptions}
appliedFilters={Object.fromEntries(filterRows.map((row) => [row.headerId, row.multiValues]))}
initialRows={batchRows}
onConfirm={handleBatchConfirm}
/>
<ListDownloadDialog mode={downloadMode} onDownload={handleDownloadConfirm} />
<MessageSendDialog
mode={messageSendMode}
templateOptions={messageTemplateMock}
targetHeaderOptions={messageTargetHeaders}
defaultSenderEmail="info@kric.com"
defaultSenderName="Korea Research"
defaultSenderNumber="02-0000-0000"
onConfirm={handleMessageSendConfirm}
/>
<MessageHistoryDialog rows={messageHistoryMock} />
</div>
)
}
export default ListManagePage

View File

@@ -7,7 +7,7 @@ import BodyTitle from "@/components/layout/BodyTitle";
import { DataTable } from "@/components/data-table/DataTable";
import { getUserColumns } from "@/components/table-column/UserTableColumn";
import UserUpsertDialog from "@/components/dialog/UserUpsertDialog";
import {UserInfo, UserInfoSaveRequest} from "@/types/user";
import {UserInfoSaveRequest} from "@/types/user";
import UserUploadDialog from "@/components/dialog/UserUploadDialog";
import {useDialog} from "@/hooks/useDialog";
import {downloadBase64File, downloadFile} from "@/lib/utils";
@@ -17,6 +17,7 @@ import {MultiSelectOption} from "@/components/ui/multi-select";
import {useMounted} from "@/hooks/useMounted";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import {DEFAULT_COMPANY_NAME, EXTERNAL_USER_ROLE} from "@/const/userConst";
import {Upload} from "lucide-react";
import {
useRoleListQuery,
useUserCompaniesQuery,
@@ -203,8 +204,9 @@ const UserManagePage = () => {
</Button>
<Button
onClick={() => showDialog('userUploadDialog')}
className="gap-2 bg-green-600 hover:bg-green-700 content-text-lg"
className="gap-2 bg-excel content-text-lg"
>
<Upload className="w-4 h-4" />
면접원 일괄 등록
</Button>
</div>
@@ -240,4 +242,4 @@ const UserManagePage = () => {
);
}
export default UserManagePage;
export default UserManagePage;

View File

@@ -1,6 +1,5 @@
import {MessageType, TemplateEmail} from "@/types/messageTemplate";
import MessageTemplate from "@/components/message-template/MessageTemplate";
import BodyTitle from "@/components/layout/BodyTitle";
const EmailTemplatePage = () => {

View File

@@ -2,7 +2,6 @@
import {MessageType, TemplateSms} from "@/types/messageTemplate";
import MessageTemplate from "@/components/message-template/MessageTemplate";
import BodyTitle from "@/components/layout/BodyTitle";
const SmsTemplatePage = () => {

View File

@@ -119,6 +119,8 @@ const MainPage = () => {
itrntPrjctCd: projectInfo.itrntPrjctCd,
ownerDept: projectInfo.ownerDept,
ownerFw: projectInfo.ownerFw,
surveyTy: projectInfo.surveyTy,
ff: projectInfo.ff
} as SelectedProject);
router.push("/project/info");
@@ -132,6 +134,8 @@ const MainPage = () => {
itrntPrjctCd: projectInfo.itrntPrjctCd,
ownerDept: projectInfo.ownerDept,
ownerFw: projectInfo.ownerFw,
surveyTy: projectInfo.surveyTy,
ff: projectInfo.ff
} as SelectedProject);
router.push(`/list/manage`);

View File

@@ -6,7 +6,6 @@ import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {Input} from "@/components/ui/input";
import React, {useEffect, useRef, useState} from "react";
import {useRouter, useSearchParams} from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { useStorage } from "@/hooks/useStorage"
import { StorageKeys } from "@/store/storage/storage-keys";
import {apiError} from "@/lib/http-util";
@@ -18,10 +17,9 @@ const LoginPage = () => {
const searchParams = useSearchParams();
const typeParam = searchParams.get("type") ?? "";
const { auth } = useAuth();
const loginMutation = useLoginMutation();
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
const { get: getSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
const [error, setError] = useState<string | null>(null);
@@ -50,10 +48,10 @@ const LoginPage = () => {
}
useEffect(() => {
if(auth.user){
if (loginMutation.isSuccess) {
router.replace("/");
}
}, [auth.user]);
}, [loginMutation.isSuccess, router]);
// URL 쿼리 파라미터에서 type 수신
useEffect(() => {
@@ -185,4 +183,4 @@ const LoginPage = () => {
);
}
export default LoginPage;
export default LoginPage;

View File

@@ -12,7 +12,6 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
const {slug = []} = await context.params;
const [action] = slug;
console.log(slug)
const sid = (searchParams.get("sid") ?? "").trim();
const allowAction = ["start", "complete", "screen", "quota"]
if(slug.length === 1 && allowAction.includes(action.toLowerCase()) && sid.length > 0){

View File

@@ -0,0 +1,52 @@
import {NextRequest, NextResponse} from "next/server";
import {PageResponse, RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/server-api";
import {errorToResponse} from "@/lib/http-util";
import {listHeader, ListSearchRequest, ListSearchWithFullResult} from "@/types/list";
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if(action === "header") {
const result = await contactApi.get<listHeader[]>(
`/list-header/${slug[1]}`,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const POST = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if(action === "search-filter"){
const body: ListSearchRequest | null = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },
{ status: 400 }
);
}
const result = await contactApi.post<PageResponse<ListSearchWithFullResult>>(
`/list/search-filter/${slug[1]}`,
body,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -2,7 +2,7 @@ import {NextRequest, NextResponse} from "next/server";
import {createContactApi, createIntranetApi} from "@/lib/server-api";
import {errorToResponse} from "@/lib/http-util";
import {PageResponse, RouteContext} from "@/types/common";
import {IntranetProjectSearchResponse, ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project";
import {ProjectInfo, ProjectListRequest, ProjectOwnerResponse} from "@/types/project";
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
@@ -51,7 +51,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
const contactApi = await createContactApi();
if(action === "list"){
const body = await req.json().catch(() => null);
const body: ProjectListRequest | null = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },

View File

@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { createContactApi } from "@/lib/server-api";
import {UserInfo, UserUploadResponse} from "@/types/user";
import {ExcelUploadResult, UserInfo} from "@/types/user";
import {DataVerification, RouteContext} from "@/types/common";
import {errorToResponse} from "@/lib/http-util";
@@ -63,7 +63,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
const [action] = slug ?? [];
const contactApi = await createContactApi();
if (action === "excel") {
if (action === "excel-upload") {
const formData = await req.formData();
const file = formData.get("file") as File | null;
@@ -77,8 +77,8 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
const backendForm = new FormData();
backendForm.append("file", file, file.name);
const result = await contactApi.postForm<UserUploadResponse>(
"/user/excel",
const result = await contactApi.postForm<ExcelUploadResult>(
"/user/excel/upload",
backendForm
);

View File

@@ -113,6 +113,20 @@
--sidebar-ring: oklch(0.556 0 0);
}
.bg-excel {
background-color: var(--color-green-600);
}
.bg-excel:hover {
background-color: var(--color-green-700);
}
.bg-blue {
background-color: var(--color-blue-600);
}
.bg-blue:hover {
background-color: var(--color-blue-700);
}
/* 배율별 유틸 클래스 */
.content-text-xs {
font-size: calc(var(--content-font-size) * 0.75);
@@ -252,4 +266,4 @@
/* 리사이즈 중인 상태를 잡고 싶으면 */
.ProseMirror [data-resize-container][data-resize-state="resizing"] {
outline: 1px dashed #0ea5e9;
}
}

View File

@@ -0,0 +1,208 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { Plus, X } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
export type BatchEditOption = {
id: number
label: string
}
export type BatchEditRow = {
id: string
headerId: number
value: string
}
export type ListBatchEditDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
appliedFilters?: Record<number, string[]>
headerOptions: BatchEditOption[]
initialRows?: BatchEditRow[]
onConfirm: (rows: BatchEditRow[]) => void | Promise<void>
}
const createRow = (headerId: number): BatchEditRow => ({
id: crypto.randomUUID(),
headerId,
value: '',
})
const ListBatchEditDialog = ({
dialogId = 'listBatchEditDialog',
open,
onOpenChange,
appliedFilters = {},
headerOptions,
initialRows = [],
onConfirm,
}: ListBatchEditDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [rows, setRows] = useState<BatchEditRow[]>([])
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const defaultHeaderId = headerOptions[0]?.id ?? 0
useEffect(() => {
if (!resolvedOpen) return
if (initialRows.length > 0) {
setRows(initialRows.map((row) => ({ ...row })))
return
}
if (defaultHeaderId > 0) {
setRows([createRow(defaultHeaderId)])
}
}, [resolvedOpen, initialRows, defaultHeaderId])
const filterSummary = useMemo(() => {
return Object.entries(appliedFilters)
.map(([headerId, values]) => {
const headerLabel = headerOptions.find((opt) => opt.id === Number(headerId))?.label ?? headerId
return `${headerLabel}: ${values.join(', ')}`
})
.join(' / ')
}, [appliedFilters, headerOptions])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleAddRow = () => {
if (defaultHeaderId <= 0) return
setRows((prev) => [...prev, createRow(defaultHeaderId)])
}
const handleRemoveRow = (id: string) => {
setRows((prev) => prev.filter((row) => row.id !== id))
}
const handleChangeHeader = (id: string, headerId: number) => {
setRows((prev) => prev.map((row) => (row.id === id ? { ...row, headerId } : row)))
}
const handleChangeValue = (id: string, value: string) => {
setRows((prev) => prev.map((row) => (row.id === id ? { ...row, value } : row)))
}
const handleConfirm = async () => {
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
if (normalized.length === 0) {
alert('일괄 수정할 항목을 입력해 주세요.')
return
}
setSubmitting(true)
try {
await onConfirm(normalized)
handleOpenChange(false)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[900px]">
<DialogHeader>
<DialogTitle className="content-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>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
적용
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default ListBatchEditDialog

View File

@@ -0,0 +1,96 @@
'use client'
import { useState } from 'react'
import { Download } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
export type ListDownloadMode = 'list' | 'contact-history' | 'list-change-history' | 'upload-file'
export type ListDownloadDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
mode: ListDownloadMode
onDownload: (payload: { mode: ListDownloadMode; onlyFiltered: boolean }) => void | Promise<void>
}
const titleMap: Record<ListDownloadMode, string> = {
list: '리스트 다운로드',
'contact-history': '컨택 이력 다운로드',
'list-change-history': '리스트 수정 이력 다운로드',
'upload-file': '업로드 파일 다운로드',
}
const ListDownloadDialog = ({
dialogId = 'listDownloadDialog',
open,
onOpenChange,
mode,
onDownload,
}: ListDownloadDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [scope, setScope] = useState<'filtered' | 'all'>('filtered')
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleDownload = async () => {
setSubmitting(true)
try {
await onDownload({ mode, onlyFiltered: scope === 'filtered' })
handleOpenChange(false)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[560px]">
<DialogHeader>
<DialogTitle className="content-text-2xl font-bold">{titleMap[mode]}</DialogTitle>
</DialogHeader>
<div className="rounded-md border p-4 space-y-4">
<p className="content-text-lg font-semibold">다운로드 범위</p>
<RadioGroup value={scope} onValueChange={(v) => setScope(v as 'filtered' | 'all')} className="space-y-2">
<div className="flex items-center gap-2">
<RadioGroupItem value="filtered" id="download-scope-filtered" />
<Label htmlFor="download-scope-filtered">필터 적용 대상만</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="all" id="download-scope-all" />
<Label htmlFor="download-scope-all">전체 대상</Label>
</div>
</RadioGroup>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleDownload} disabled={submitting} className="gap-2">
<Download className="w-4 h-4" />
다운로드
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default ListDownloadDialog

View File

@@ -0,0 +1,280 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { Plus, X } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
export type FilterOperator = 'eq' | 'neq' | 'contains' | 'notContains'
export type FilterHeaderOption = {
id: number
label: string
values?: string[]
}
export type FilterRow = {
id: string
headerId: number
operator: FilterOperator
textValue: string
multiValues: string[]
}
export type ListFilterDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
headerOptions: FilterHeaderOption[]
initialRows?: FilterRow[]
onConfirm: (rows: FilterRow[]) => void | Promise<void>
}
const operatorLabel: Record<FilterOperator, string> = {
eq: '같음',
neq: '다름',
contains: '포함',
notContains: '포함하지 않음',
}
const createFilterRow = (headerId: number): FilterRow => ({
id: crypto.randomUUID(),
headerId,
operator: 'eq',
textValue: '',
multiValues: [],
})
const ListFilterDialog = ({
dialogId = 'listFilterDialog',
open,
onOpenChange,
headerOptions,
initialRows = [],
onConfirm,
}: ListFilterDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [rows, setRows] = useState<FilterRow[]>([])
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const defaultHeaderId = headerOptions[0]?.id ?? 0
useEffect(() => {
if (!resolvedOpen) return
if (initialRows.length > 0) {
setRows(initialRows.map((row) => ({ ...row })))
return
}
if (defaultHeaderId > 0) {
setRows([createFilterRow(defaultHeaderId)])
}
}, [resolvedOpen, initialRows, defaultHeaderId])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleAddRow = () => {
if (defaultHeaderId <= 0) return
setRows((prev) => [...prev, createFilterRow(defaultHeaderId)])
}
const handleRemoveRow = (id: string) => {
setRows((prev) => prev.filter((row) => row.id !== id))
}
const handleChangeRow = (id: string, updater: (row: FilterRow) => FilterRow) => {
setRows((prev) => prev.map((row) => (row.id === id ? updater(row) : row)))
}
const getValueOptions = (headerId: number) => {
return headerOptions.find((item) => item.id === headerId)?.values ?? []
}
const serializedRows = useMemo(
() =>
rows
.map((row) => {
if (row.operator === 'contains' || row.operator === 'notContains') {
return row.textValue.trim().length > 0 ? row : null
}
return row.multiValues.length > 0 ? row : null
})
.filter((row): row is FilterRow => row !== null),
[rows],
)
const handleConfirm = async () => {
if (serializedRows.length === 0) {
alert('필터 조건을 입력해 주세요.')
return
}
setSubmitting(true)
try {
await onConfirm(serializedRows)
handleOpenChange(false)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[940px]">
<DialogHeader>
<DialogTitle className="content-text-2xl font-bold">필터</DialogTitle>
</DialogHeader>
<div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[1fr_140px_1.4fr_64px] items-center 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 textMode = row.operator === 'contains' || row.operator === 'notContains'
return (
<div
key={row.id}
className="min-h-12 px-4 py-2 border-b last:border-b-0 grid grid-cols-[1fr_140px_1.4fr_64px] items-center gap-2"
>
<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>
{textMode ? (
<Input
placeholder="검색할 텍스트"
value={row.textValue}
onChange={(e) =>
handleChangeRow(row.id, (current) => ({
...current,
textValue: e.target.value,
}))
}
/>
) : (
<div className="space-y-1">
<select
multiple
className="w-full min-h-20 rounded-md border px-2 py-1 text-sm"
value={row.multiValues}
onChange={(e) => {
const values = Array.from(e.target.selectedOptions).map((option) => option.value)
handleChangeRow(row.id, (current) => ({
...current,
multiValues: values,
}))
}}
>
{valueOptions.map((value) => (
<option key={value} value={value}>
{value}
</option>
))}
</select>
<Label className="text-xs text-muted-foreground">Ctrl/Cmd + 클릭으로 다중 선택</Label>
</div>
)}
<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>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
적용
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default ListFilterDialog

View File

@@ -0,0 +1,167 @@
'use client'
import { useEffect, useState } from 'react'
import { GripVertical, Trash2 } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
import { cn } from '@/lib/utils'
export type ListHeaderManageRow = {
id: number
name: string
visible: boolean
locked?: boolean
}
export type ListHeaderManageDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
rows: ListHeaderManageRow[]
onConfirm: (rows: ListHeaderManageRow[]) => void | Promise<void>
}
const ListHeaderManageDialog = ({
dialogId = 'listHeaderManageDialog',
open,
onOpenChange,
rows,
onConfirm,
}: ListHeaderManageDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [localRows, setLocalRows] = useState<ListHeaderManageRow[]>([])
const [draggingId, setDraggingId] = useState<number | null>(null)
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
useEffect(() => {
if (!resolvedOpen) return
setLocalRows(rows.map((row) => ({ ...row })))
}, [resolvedOpen, rows])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleDrop = (targetId: number) => {
if (draggingId === null || draggingId === targetId) return
setLocalRows((prev) => {
const sourceIndex = prev.findIndex((row) => row.id === draggingId)
const targetIndex = prev.findIndex((row) => row.id === targetId)
if (sourceIndex < 0 || targetIndex < 0) return prev
const next = [...prev]
const [moved] = next.splice(sourceIndex, 1)
next.splice(targetIndex, 0, moved)
return next
})
}
const handleVisibleChange = (id: number, checked: boolean) => {
setLocalRows((prev) =>
prev.map((row) => {
if (row.id !== id || row.locked) return row
return { ...row, visible: checked }
}),
)
}
const handleDelete = (id: number) => {
setLocalRows((prev) => prev.filter((row) => row.id !== id || row.locked))
}
const handleConfirm = async () => {
setSubmitting(true)
try {
await onConfirm(localRows)
handleOpenChange(false)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[820px]">
<DialogHeader>
<DialogTitle className="content-text-2xl font-bold">리스트 헤더 관리</DialogTitle>
</DialogHeader>
<div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[56px_1fr_120px_88px] items-center text-sm font-semibold">
<span>순서</span>
<span>헤더명</span>
<span>노출</span>
<span className="text-center">삭제</span>
</div>
<div className="max-h-[420px] overflow-auto">
{localRows.map((row) => (
<div
key={row.id}
className={cn(
'h-11 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_120px_88px] items-center',
draggingId === row.id && 'bg-muted/40',
)}
draggable={!row.locked}
onDragStart={() => setDraggingId(row.id)}
onDragEnd={() => setDraggingId(null)}
onDragOver={(e) => e.preventDefault()}
onDrop={() => handleDrop(row.id)}
>
<div className="flex items-center">
<GripVertical className="w-4 h-4 text-muted-foreground" />
</div>
<span>{row.name}</span>
<div className="flex items-center gap-2">
<Checkbox
id={`header-visible-${row.id}`}
checked={row.visible}
onCheckedChange={(checked) => handleVisibleChange(row.id, checked === true)}
disabled={row.locked}
/>
<Label htmlFor={`header-visible-${row.id}`} className="cursor-pointer">
사용
</Label>
</div>
<div className="flex justify-center">
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => handleDelete(row.id)}
disabled={row.locked}
aria-label="헤더 삭제"
>
<Trash2 className="w-4 h-4 text-red-600" />
</Button>
</div>
</div>
))}
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
저장
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default ListHeaderManageDialog

View File

@@ -0,0 +1,107 @@
'use client'
import { useState } from 'react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
export type ListResetTarget = 'selected' | 'filtered' | 'all'
export type ListResetScope = 'result-and-history' | 'list-only'
export type ListResetDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
onConfirm: (payload: { target: ListResetTarget; scope: ListResetScope }) => void | Promise<void>
}
const ListResetDialog = ({
dialogId = 'listResetDialog',
open,
onOpenChange,
onConfirm,
}: ListResetDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [target, setTarget] = useState<ListResetTarget>('selected')
const [scope, setScope] = useState<ListResetScope>('result-and-history')
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleConfirm = async () => {
setSubmitting(true)
try {
await onConfirm({ target, scope })
handleOpenChange(false)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[700px]">
<DialogHeader>
<DialogTitle className="content-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="content-text-lg font-semibold text-red-600">초기화 대상</p>
<RadioGroup value={target} onValueChange={(v) => setTarget(v as ListResetTarget)} className="space-y-2">
<div className="flex items-center gap-2">
<RadioGroupItem value="selected" id="list-reset-target-selected" />
<Label htmlFor="list-reset-target-selected">선택 항목만</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="filtered" id="list-reset-target-filtered" />
<Label htmlFor="list-reset-target-filtered">필터 적용 항목만</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="all" id="list-reset-target-all" />
<Label htmlFor="list-reset-target-all">리스트 전체</Label>
</div>
</RadioGroup>
</div>
<div className="rounded-md border p-4 space-y-4">
<p className="content-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>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting}>
초기화
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default ListResetDialog

View File

@@ -1,5 +1,7 @@
'use client'
import { useMemo, useRef, useState } from 'react'
import { ChevronDown, ChevronUp, Download, Upload, X } from 'lucide-react'
import {
Dialog,
DialogContent,
@@ -8,100 +10,113 @@ import {
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Checkbox } from '@/components/ui/checkbox'
import { useState, useRef } from 'react'
import { Upload, X } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
import { formatKst } from '@/lib/utils'
export type UploadMode = 'add' | 'replace'
export type ValidationOption = {
checkEmailDuplicate: boolean
checkPhoneDuplicate: boolean
}
export type ListUploadDialogProps = {
/** jotai로 관리할 dialog id (기본값: 'listUploadDialog') */
dialogId?: DialogId
/** 필요하면 부모에서 직접 제어도 가능 */
open?: boolean
onOpenChange?: (open: boolean) => void
onUpload: (
file: File,
mode: UploadMode,
validation: ValidationOption,
) => void | Promise<void>
onDownloadTemplate?: () => void
export type ListUploadHistory = {
round: number
fileName: string
userId: string
uploadCount: number
uploadAt: string
}
export type ListUploadDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
onUpload: (file: File, validation: ValidationOption) => void | Promise<void>
onDownloadTemplate?: () => void | Promise<void>
uploadHistory?: ListUploadHistory[]
onDownloadHistory?: (item: ListUploadHistory) => void | Promise<void>
}
const ACCEPT_EXTENSIONS = ['.xlsx', '.xls', '.csv']
const ListUploadDialog = ({
dialogId = 'listUploadDialog',
open,
onOpenChange,
onUpload,
onDownloadTemplate,
}: ListUploadDialogProps) => {
dialogId = 'listUploadDialog',
open,
onOpenChange,
onUpload,
onDownloadTemplate,
uploadHistory = [],
onDownloadHistory,
}: ListUploadDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const fileInputRef = useRef<HTMLInputElement>(null)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [uploadMode, setUploadMode] = useState<UploadMode>('add')
const [submitting, setSubmitting] = useState(false)
const [historyExpanded, setHistoryExpanded] = useState(true)
const [validation, setValidation] = useState<ValidationOption>({
checkEmailDuplicate: false,
checkPhoneDuplicate: false,
})
const [isUploading, setIsUploading] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
// ✅ 실제 Dialog에 넘길 open 값 (props 우선, 없으면 jotai 사용)
const resolvedOpen = open ?? isDialogOpen(dialogId)
// ✅ 공통 openChange 처리 (부모 콜백 + jotai 동시 반영)
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
} else {
hideDialog(dialogId)
}
}
const normalizedHistory = useMemo(
() =>
uploadHistory.map((item) => ({
...item,
uploadAtLabel: formatKst(item.uploadAt, 'dateTime'),
})),
[uploadHistory],
)
const resetState = () => {
setSelectedFile(null)
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
setUploadMode('add')
setSubmitting(false)
setHistoryExpanded(true)
setValidation({
checkEmailDuplicate: false,
checkPhoneDuplicate: false,
})
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
}
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
const allowedTypes = [
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'text/csv',
]
if (
allowedTypes.includes(file.type) ||
file.name.endsWith('.xlsx') ||
file.name.endsWith('.xls') ||
file.name.endsWith('.csv')
) {
setSelectedFile(file)
} else {
alert('엑셀 파일만 업로드 가능합니다. (.xlsx, .xls, .csv)')
}
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleDialogOpenChange = (nextOpen: boolean) => {
if (!nextOpen && !submitting) {
resetState()
}
handleOpenChange(nextOpen)
}
const handleSelectFileClick = () => {
if (submitting) return
fileInputRef.current?.click()
}
const handleSelectFile = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (!file) return
const lower = file.name.toLowerCase()
const valid = ACCEPT_EXTENSIONS.some((ext) => lower.endsWith(ext))
if (!valid) {
alert('엑셀 또는 CSV 파일만 업로드 가능합니다. (.xlsx, .xls, .csv)')
return
}
setSelectedFile(file)
}
const handleRemoveFile = () => {
@@ -111,223 +126,174 @@ const ListUploadDialog = ({
}
}
const handleUploadClick = () => {
fileInputRef.current?.click()
}
const handleSubmit = async () => {
if (!selectedFile) {
alert('파일을 선택해주세요.')
alert('업로드할 파일을 선택해 주세요.')
return
}
setIsUploading(true)
setSubmitting(true)
try {
await onUpload(selectedFile, uploadMode, validation)
// 성공 시 초기화 + 닫기
await onUpload(selectedFile, validation)
resetState()
handleOpenChange(false)
} catch (error) {
console.error('업로드 실패:', error)
alert('업로드에 실패했습니다.')
} catch {
alert('리스트 업로드 중 오류가 발생했습니다.')
} finally {
setIsUploading(false)
setSubmitting(false)
}
}
// Dialog의 onOpenChange에 연결되는 최종 핸들러
const handleDialogOpenChange = (nextOpen: boolean) => {
if (!nextOpen && !isUploading) {
resetState()
}
handleOpenChange(nextOpen)
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle className="text-xl font-bold">엑셀 업로드</DialogTitle>
</DialogHeader>
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
<DialogContent className="sm:max-w-[860px]">
<DialogHeader>
<DialogTitle className="content-text-2xl font-bold">리스트 업로드</DialogTitle>
</DialogHeader>
<div className="space-y-6 py-4">
{/* 1. 리스트 업로드 */}
<div className="space-y-3">
<Label className="text-sm font-medium flex items-center gap-2">
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs">
1
</span>
리스트 업로드
</Label>
<div className="flex gap-2">
<Button
type="button"
variant="default"
className="flex-1 bg-green-600 hover:bg-green-700"
onClick={() => {
if (onDownloadTemplate) onDownloadTemplate()
else alert('양식 다운로드 기능이 아직 구현되지 않았습니다.')
}}
>
<Upload className="w-4 h-4 mr-2" />
양식 다운로드
</Button>
<Button
type="button"
variant="outline"
className="flex-1"
onClick={handleUploadClick}
disabled={isUploading}
>
<Upload className="w-4 h-4 mr-2" />
{selectedFile ? selectedFile.name : '선택된 파일 없음'}
</Button>
</div>
<input
ref={fileInputRef}
type="file"
accept=".xlsx,.xls,.csv"
className="hidden"
onChange={handleFileSelect}
/>
{selectedFile && (
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-md border border-blue-200">
<span className="text-sm text-blue-900 truncate">
{selectedFile.name}
</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={handleRemoveFile}
disabled={isUploading}
>
<X className="w-4 h-4" />
</Button>
</div>
)}
</div>
{/* 2. Excel 파일 업로드 */}
<div className="space-y-3">
<Label className="text-sm font-medium flex items-center gap-2">
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs">
2
</span>
Excel 파일 업로드
</Label>
</div>
{/* 3. 업로드 방식 선택 */}
<div className="space-y-3">
<Label className="text-sm font-medium flex items-center gap-2">
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs">
3
</span>
업로드 이력
</Label>
<RadioGroup
value={uploadMode}
onValueChange={value => setUploadMode(value as UploadMode)}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="add" id="add" />
<Label htmlFor="add" className="font-normal cursor-pointer">
추가
</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="replace" id="replace" />
<Label htmlFor="replace" className="font-normal cursor-pointer">
교체
</Label>
</div>
</RadioGroup>
</div>
{/* 4. 중복 검사 옵션 */}
<div className="space-y-3">
<Label className="text-sm font-medium flex items-center gap-2">
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs">
4
</span>
중복 검사
</Label>
<div className="space-y-2 pl-8">
<div className="flex items-center space-x-2">
<Checkbox
id="emailCheck"
checked={validation.checkEmailDuplicate}
onCheckedChange={checked =>
setValidation(prev => ({
...prev,
checkEmailDuplicate: checked === true,
}))
}
/>
<Label
htmlFor="emailCheck"
className="font-normal cursor-pointer"
>
이메일 중복검사
</Label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="phoneCheck"
checked={validation.checkPhoneDuplicate}
onCheckedChange={checked =>
setValidation(prev => ({
...prev,
checkPhoneDuplicate: checked === true,
}))
}
/>
<Label
htmlFor="phoneCheck"
className="font-normal cursor-pointer"
>
전화번호 중복검사
</Label>
</div>
</div>
</div>
{/* 5. 업로드 이력 (드롭다운) */}
<div className="space-y-3">
<select
className="w-full px-3 py-2 border border-input rounded-md text-sm"
defaultValue=""
>
<option value="" disabled>
업로드 이력
</option>
<option>2024-01-15 14:30 - 파일1.xlsx (추가)</option>
<option>2024-01-14 10:20 - 파일2.xlsx (교체)</option>
</select>
<Button type="button" variant="outline" className="w-full">
다운로드
<div className="space-y-6 py-2">
<div className="space-y-3">
<Label className="content-text-lg font-semibold">업로드 파일</Label>
<div className="flex items-center gap-2">
<Button type="button" className="bg-excel content-text-lg" onClick={onDownloadTemplate}>
<Download className="w-4 h-4" />
양식 다운로드
</Button>
<Button
type="button"
variant="outline"
className="flex-1 justify-start content-text-lg"
onClick={handleSelectFileClick}
disabled={submitting}
>
<Upload className="w-4 h-4" />
{selectedFile ? selectedFile.name : '업로드 파일을 선택해 주세요'}
</Button>
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={handleRemoveFile}
disabled={!selectedFile || submitting}
aria-label="선택 파일 제거"
>
<X className="w-4 h-4" />
</Button>
<input
ref={fileInputRef}
type="file"
accept={ACCEPT_EXTENSIONS.join(',')}
className="hidden"
onChange={handleSelectFile}
/>
</div>
</div>
<DialogFooter>
<div className="flex items-center justify-end w-full gap-2">
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs mr-2">
6
</span>
<Button
type="button"
onClick={handleSubmit}
disabled={!selectedFile || isUploading}
>
{isUploading ? '업로드중...' : '확인'}
</Button>
<div className="space-y-3">
<Label className="content-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>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
<div className="rounded-md border">
<button
type="button"
className="w-full px-4 h-11 flex items-center justify-between border-b text-left"
onClick={() => setHistoryExpanded((prev) => !prev)}
>
<span className="content-text-lg font-semibold">업로드 이력</span>
{historyExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
</button>
{historyExpanded && (
<div className="max-h-56 overflow-auto">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-white border-b">
<tr>
<th className="px-3 h-9 text-left">회차</th>
<th className="px-3 h-9 text-left">파일명</th>
<th className="px-3 h-9 text-left">사용자 ID</th>
<th className="px-3 h-9 text-right">업로드 건수</th>
<th className="px-3 h-9 text-left">업로드 일시</th>
<th className="px-3 h-9 text-center">다운로드</th>
</tr>
</thead>
<tbody>
{normalizedHistory.length === 0 && (
<tr>
<td className="px-3 h-12 text-center text-muted-foreground" colSpan={6}>
업로드 이력이 없습니다.
</td>
</tr>
)}
{normalizedHistory.map((item) => (
<tr key={`${item.round}-${item.fileName}`} className="border-b last:border-b-0">
<td className="px-3 h-10">{item.round}</td>
<td className="px-3 h-10">{item.fileName}</td>
<td className="px-3 h-10">{item.userId}</td>
<td className="px-3 h-10 text-right">{item.uploadCount.toLocaleString()}</td>
<td className="px-3 h-10">{item.uploadAtLabel}</td>
<td className="px-3 h-10 text-center">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onDownloadHistory?.(item)}
disabled={!onDownloadHistory}
>
다운로드
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => handleDialogOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting}>
{submitting ? '업로드 중...' : '업로드'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default ListUploadDialog
export default ListUploadDialog

View File

@@ -0,0 +1,211 @@
'use client'
import { useMemo, useState } from 'react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
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> = {
sms: '문자',
email: '이메일',
}
const MessageHistoryDialog = ({
dialogId = 'messageHistoryDialog',
open,
onOpenChange,
rows,
onDownload,
}: MessageHistoryDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [tab, setTab] = useState<MessageHistoryType>('sms')
const [selectedId, setSelectedId] = useState<number | null>(null)
const [detailType, setDetailType] = useState<MessageHistoryDetailType>(null)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const visibleRows = useMemo(() => rows.filter((row) => row.type === tab), [rows, tab])
const selectedRow = useMemo(
() => visibleRows.find((row) => row.id === selectedId) ?? null,
[visibleRows, selectedId],
)
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
setSelectedId(null)
setDetailType(null)
}
const handlePickDetail = (rowId: number, nextType: Exclude<MessageHistoryDetailType, null>) => {
setSelectedId(rowId)
setDetailType(nextType)
}
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])
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[1200px]">
<DialogHeader>
<DialogTitle className="content-text-2xl font-bold">발송 이력</DialogTitle>
</DialogHeader>
<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="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="content-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>
</>
)}
</div>
</div>
<DialogFooter>
<Button type="button" onClick={() => handleOpenChange(false)}>
닫기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default MessageHistoryDialog

View File

@@ -0,0 +1,291 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
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 { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
export type MessageSendMode = 'email' | 'sms'
export type ScheduleType = 'instant' | 'reserve'
export type MessageTemplateOption = {
id: string
name: string
title: string
body: string
}
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
}
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>
}
const titleMap: Record<MessageSendMode, string> = {
email: '메일 발송',
sms: '문자 발송',
}
const MessageSendDialog = ({
dialogId = 'messageSendDialog',
open,
onOpenChange,
mode,
templateOptions,
targetHeaderOptions,
defaultSenderEmail = '',
defaultSenderName = '',
defaultSenderNumber = '',
onConfirm,
}: 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 [reserveAt, setReserveAt] = useState('')
const [targetHeaderId, setTargetHeaderId] = useState<number>(targetHeaderOptions[0]?.id ?? 0)
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const selectedTemplate = useMemo(
() => templateOptions.find((template) => template.id === templateId),
[templateId, templateOptions],
)
useEffect(() => {
if (!resolvedOpen) return
const firstTemplate = templateOptions[0]
setTemplateId(firstTemplate?.id ?? '')
setTitle(firstTemplate?.title ?? '')
setBody(firstTemplate?.body ?? '')
setScheduleType('instant')
setReserveAt('')
setTargetHeaderId(targetHeaderOptions[0]?.id ?? 0)
setSenderEmail(defaultSenderEmail)
setSenderName(defaultSenderName)
setSenderNumber(defaultSenderNumber)
}, [resolvedOpen, templateOptions, targetHeaderOptions, defaultSenderEmail, defaultSenderName, defaultSenderNumber])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
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 handleConfirm = async () => {
if (!templateId) {
alert('템플릿을 선택해 주세요.')
return
}
if (!title.trim() || !body.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
}
setSubmitting(true)
try {
await onConfirm({
mode,
templateId,
senderEmail,
senderName,
senderNumber,
title,
body,
scheduleType,
reserveAt: scheduleType === 'reserve' ? reserveAt : undefined,
targetHeaderId,
})
handleOpenChange(false)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[980px]">
<DialogHeader>
<DialogTitle className="content-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="content-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="content-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>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
발송
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default MessageSendDialog

View File

@@ -129,7 +129,7 @@ const UserUploadDialog = ({
<Button
type="button"
variant="default"
className="content-text-lg bg-green-600 hover:bg-green-700"
className="content-text-lg bg-excel"
onClick={onDownloadTemplate}
>
<Download className="w-4 h-4 mr-2" />

View File

@@ -238,7 +238,13 @@ const UserUpsertDialog = ({
<KriSingleSelect
items={userRoleArray}
value={String(formData.userRole)}
onChange={(e) => handleInputChange('userRole', Number(e))}
onChange={(e) => {
if(mode !== 'create'){
alert("권한이 변경되면 해당 계정에 배정된 리스트 정보가 초기화 됩니다.");
}
handleInputChange('userRole', Number(e));
}}
getLabel={(item) => item.label}
getValue={(item) => String(item.value)}
placeholder="사용자 권한"

View File

@@ -1,57 +1,11 @@
import { CheckCircle, XCircle, Users } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import ExternalLayout from "./ExternalLayout";
import {RedirectSlug} from "@/types/common";
interface StatusConfig {
label: string;
sublabel: string;
title: string;
description: string;
Icon: React.ElementType;
badgeVariant: "default" | "secondary" | "destructive" | "outline";
iconClassName: string;
savedVisible: boolean;
}
import {STATUS_MAP} from "@/config/redirect.data";
// ─── Status Configs ───────────────────────────────────────────────────────────
const STATUS_MAP: Record<RedirectSlug, StatusConfig> = {
complete: {
label: "설문 완료",
sublabel: "Survey Complete",
title: "설문에 참여해 주셔서\n감사합니다",
description:
"귀하의 소중한 의견이 성공적으로 접수되었습니다. 응답 결과는 연구 목적으로만 활용되며, 개인 정보는 철저히 보호됩니다.",
Icon: CheckCircle,
badgeVariant: "default",
iconClassName: "text-primary",
savedVisible: true,
},
screen: {
label: "참여 불가",
sublabel: "Screen Out",
title: "이번 설문에는\n참여하실 수 없습니다",
description:
"현재 진행 중인 설문은 특정 조건에 맞는 응답자를 대상으로 합니다. 귀하의 프로필이 이번 조사의 대상과 맞지 않아 참여가 제한되었습니다.",
Icon: XCircle,
badgeVariant: "outline",
iconClassName: "text-muted-foreground",
savedVisible: false,
},
quota: {
label: "할당 초과",
sublabel: "Quota Full",
title: "모집 인원이\n마감되었습니다",
description:
"해당 설문의 목표 응답 수가 충족되어 더 이상 참여가 불가합니다. 참여 의사를 가져주신 데 감사드리며, 다른 설문 기회를 기대해 주세요.",
Icon: Users,
badgeVariant: "outline",
iconClassName: "text-muted-foreground",
savedVisible: false,
},
};
const InfoRow = ({
label,

View File

@@ -2,7 +2,6 @@
import {useSelectedProject} from "@/hooks/useSelectedProject";
import {useCallback, useEffect, useRef, useState} from "react";
import {listHder} from "@/types/list";
import {
ChannelType,
MessageType,
@@ -30,6 +29,7 @@ import {
useUpdateMainTemplateMutation,
useUploadTemplateBodyImageMutation,
} from "@/query/message";
import {listHeader} from "@/types/list";
interface MessageTemplateProps {
pageTitle: string;
@@ -42,7 +42,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
const editorCmdRef = useRef<KriEditorCommand | null>(null);
const sessionTempUrlsRef = useRef<Set<string>>(new Set());
const [listHderList, setListHderList] = useState<listHder[]>([]);
const [listHderList, setListHderList] = useState<listHeader[]>([]);
const [selectedTemplate, setSelectedTemplate] = useState<Template>(defaultTemplate);
const [selectedTemplateIdx, setSelectedTemplateIdx] = useState<number | null>(null);

View File

@@ -0,0 +1,179 @@
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 { formatKst } from "@/lib/utils";
import { ResultCode, ResultCodeType } from "@/types/project";
export type ListTableRow = Record<string, unknown>;
const getAssignColumns = (userRole: number): DataTableColumn<ListTableRow>[] => {
const targets: Array<{ id: string; header: string; key: number }> = [];
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;
};
const getResultColumns = (resultCodeArray: ResultCode[]): DataTableColumn<ListTableRow>[] => {
const labelByTypeCode = new Map<string, string>();
resultCodeArray.forEach((item) => {
labelByTypeCode.set(`${item.resultCdTy}:${item.resultCd}`, item.resultCdLbl);
});
const getResultLabel = (resultType: ResultCodeType, result?: ListResultBase) => {
const lastResultCd = result?.lastResultCd;
if (lastResultCd === undefined) return "";
return labelByTypeCode.get(`${resultType}:${lastResultCd}`) ?? "";
}
const formatResult = (resultType: ResultCodeType, result?: ListContactResult) => {
const lastResultCd = result?.lastResultCd;
if (lastResultCd === undefined) return "";
const label = getResultLabel(resultType, result);
const count = result?.attemptCount ?? 0;
const dt = `(${formatKst(result?.lastResultDt ?? "", "dateHourMin")})`;
const resultText = `${lastResultCd}. ${label} (${count}회)`;
return (
<div className="leading-tight">
<div>{resultText}</div>
<div>{dt}</div>
</div>
);
};
const formatSendResult = (result?: ListSendResult) => {
const label = result?.lastResultLabel ?? "";
const dt = `(${formatKst(result?.lastResultDt ?? "", "dateHourMin")})`;
return (
<div className="leading-tight">
<div>{label}</div>
<div>{dt}</div>
</div>
);
};
const columns: DataTableColumn<ListTableRow>[] = [
{
id: "contactResult",
header: "컨택 결과",
cell: ({ row }) =>
formatResult(ResultCodeType.CONTACT, row.original.contactResult as ListContactResult | undefined),
enableSorting: false,
},
{
id: "mailSendResult",
header: "email 발송 결과",
cell: ({ row }) =>
formatSendResult(row.original.emailSendResult as ListSendResult | undefined),
enableSorting: false,
},
{
id: "smsSendResult",
header: "문자 발송 결과",
cell: ({ row }) =>
formatSendResult(row.original.smsSendResult as ListSendResult | undefined),
enableSorting: false,
},
{
id: "interviewResult",
header: "면접 결과",
cell: ({ row }) =>
formatResult(ResultCodeType.INTERVIEW, row.original.interviewResult as ListContactResult | undefined),
enableSorting: false,
},
{
id: "surveyStatus",
header: "설문 진행 상태",
accessorFn: (row) => getResultLabel(ResultCodeType.SURVEY, row.surveyResult as ListResultBase | undefined),
enableSorting: false,
},
];
return columns;
};
export const getListColumns = (
listHeaders: listHeader[],
resultCodeArray: ResultCode[],
userRole: number
): DataTableColumn<ListTableRow>[] => {
const visibleHeaders = listHeaders.filter((header) => {
if (!header.useColView) return false;
if (header.listHderTy === ListHeaderConst.SID) return true;
if (
header.listHderTy === ListHeaderAssignConst.OUTSOURCE ||
header.listHderTy === ListHeaderAssignConst.CONTACT_INTERVIEWER ||
header.listHderTy === ListHeaderAssignConst.FIELD_INTERVIEWER
) {
return false;
}
if (userRole >= 9000) return header.useIntrvwerView;
return 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];
};

View File

@@ -69,7 +69,7 @@ function DialogContent({
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 cursor-pointer"
>
<XIcon />
<span className="sr-only">Close</span>

View File

@@ -36,8 +36,8 @@ export const projectSideMenus: SideMenuItem[] = [
label: "면접원 배정",
icon: Users,
children: [
{ id: "assign-project", label: "프로젝트 배정", path: "/project/assign" },
{ id: "assign-list", label: "리스트 배정", path: "/list/assign" },
{ id: "assign-project", label: "프로젝트 배정", path: "/assign/project" },
{ id: "assign-list", label: "리스트 배정", path: "/assign/list" },
],
},
{

View File

@@ -0,0 +1,39 @@
import {RedirectSlug} from "@/types/common";
import {CheckCircle, Users, XCircle} from "lucide-react";
import {StatusConfig} from "@/config/redirect.types";
export const STATUS_MAP: Record<RedirectSlug, StatusConfig> = {
complete: {
label: "설문 완료",
sublabel: "Survey Complete",
title: "설문에 참여해 주셔서\n감사합니다",
description:
"귀하의 소중한 의견이 성공적으로 접수되었습니다. 응답 결과는 연구 목적으로만 활용되며, 개인 정보는 철저히 보호됩니다.",
Icon: CheckCircle,
badgeVariant: "default",
iconClassName: "text-primary",
savedVisible: true,
},
screen: {
label: "참여 불가",
sublabel: "Screen Out",
title: "이번 설문에는\n참여하실 수 없습니다",
description:
"현재 진행 중인 설문은 특정 조건에 맞는 응답자를 대상으로 합니다. 귀하의 프로필이 이번 조사의 대상과 맞지 않아 참여가 제한되었습니다.",
Icon: XCircle,
badgeVariant: "outline",
iconClassName: "text-muted-foreground",
savedVisible: false,
},
quota: {
label: "할당 초과",
sublabel: "Quota Full",
title: "모집 인원이\n마감되었습니다",
description:
"해당 설문의 목표 응답 수가 충족되어 더 이상 참여가 불가합니다. 참여 의사를 가져주신 데 감사드리며, 다른 설문 기회를 기대해 주세요.",
Icon: Users,
badgeVariant: "outline",
iconClassName: "text-muted-foreground",
savedVisible: false,
},
};

View File

@@ -0,0 +1,10 @@
export interface StatusConfig {
label: string;
sublabel: string;
title: string;
description: string;
Icon: React.ElementType;
badgeVariant: "default" | "secondary" | "destructive" | "outline";
iconClassName: string;
savedVisible: boolean;
}

View File

@@ -1,28 +1,54 @@
import {ListHeaderGrade, ListHeaderType} from "@/types/list";
export const LIST_HEADER_GRADE_ORDER = [
ListHeaderGrade.IMMUTABLE,
ListHeaderGrade.DEFAULT,
ListHeaderGrade.NORMAL,
0, // IMMUTABLE
1, // RESERVED
10, // COMMON
] as const;
export const ListHeaderAssignConst = {
OUTSOURCE: 13,
CONTACT_INTERVIEWER: 14,
FIELD_INTERVIEWER: 15,
} as const;
export const ListHeaderDefaultConst = {
SID: 11,
IS_USE: 12,
...ListHeaderAssignConst,
MEMO: 19,
} as const;
export const ListHeaderSpecificConst = {
TEL_NUM: 21,
EMAIL: 31,
FILE: 81,
} as const;
export const ListHeaderConst = {
TEXT: 91,
...ListHeaderDefaultConst,
...ListHeaderSpecificConst,
} as const;
type ListHeaderType = (typeof ListHeaderConst)[keyof typeof ListHeaderConst];
export const LIST_HEADER_TYPE_ORDER = [
ListHeaderType.TEXT,
ListHeaderType.TEL,
ListHeaderType.EMAIL,
ListHeaderType.FILE_UPLOAD,
ListHeaderConst.TEXT,
ListHeaderConst.TEL_NUM,
ListHeaderConst.EMAIL,
ListHeaderConst.FILE,
] as const;
export const LIST_HEADER_TYPE_LABEL = {
[ListHeaderType.TEXT]: "일반",
[ListHeaderType.TEL]: "전화번호",
[ListHeaderType.EMAIL]: "이메일",
[ListHeaderType.FILE_UPLOAD]: "파일 업로드",
} as const satisfies Record<ListHeaderType, string>;
type ListHeaderOptionType = (typeof LIST_HEADER_TYPE_ORDER)[number];
export const LIST_HEADER_TYPE_OPTIONS = [
{ value: ListHeaderType.TEXT, label: LIST_HEADER_TYPE_LABEL[ListHeaderType.TEXT] },
{ value: ListHeaderType.TEL, label: LIST_HEADER_TYPE_LABEL[ListHeaderType.TEL] },
{ value: ListHeaderType.EMAIL, label: LIST_HEADER_TYPE_LABEL[ListHeaderType.EMAIL] },
{ value: ListHeaderType.FILE_UPLOAD, label: LIST_HEADER_TYPE_LABEL[ListHeaderType.FILE_UPLOAD] },
] as const;
export const LIST_HEADER_TYPE_LABEL = {
[ListHeaderConst.TEXT]: "일반",
[ListHeaderConst.TEL_NUM]: "전화번호",
[ListHeaderConst.EMAIL]: "이메일",
[ListHeaderConst.FILE]: "파일 업로드",
} as const satisfies Partial<Record<ListHeaderType, string>> &
Record<ListHeaderOptionType, string>;
export const LIST_HEADER_TYPE_OPTIONS = LIST_HEADER_TYPE_ORDER.map((value) => ({
value,
label: LIST_HEADER_TYPE_LABEL[value],
})) satisfies ReadonlyArray<{ value: ListHeaderOptionType; label: string }>;

View File

@@ -6,7 +6,7 @@ import { useStorage } from "@/hooks/useStorage";
import {ItrntUserInfo} from "@/types/user";
import {useIntranetUsersQuery} from "@/query/intranet";
import {useQueryClient} from "@tanstack/react-query";
import {qk} from "@/query/keys";
import {qk} from "@/query/key/keys";
export const useItrntUserList = () => {
const storage = useStorage(StorageKeys.ItrntUserList);

View File

@@ -64,6 +64,28 @@ export type HttpClientOptions = {
setErrorMessage?: (status: number, serverMsg?: string) => string;
};
let logoutRedirectStarted = false;
const canRedirectToLogout = (): boolean => {
if (typeof window === "undefined") return false;
if (logoutRedirectStarted) return false;
const { pathname } = window.location;
if (pathname === "/logout" || pathname === "/login") return false;
return true;
};
const redirectToLogout = (): void => {
if (!canRedirectToLogout()) return;
logoutRedirectStarted = true;
try {
window.location.replace("/logout");
} catch {}
};
const replacePathParams = (path: string, params?: PathParams): string => {
if (!params) return path;
let out = path;
@@ -186,9 +208,7 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
if (res.status === 401) options.onAuthError?.();
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
try {
window.location.replace("/logout");
} catch {}
redirectToLogout();
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
}
@@ -230,9 +250,7 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
if (res.status === 401) options.onAuthError?.();
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
try {
window.location.replace("/logout");
} catch {}
redirectToLogout();
throw new HttpError(res.status, parsed, url.toString(), res.headers);
}

View File

@@ -2,6 +2,11 @@ import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import type {NextRequest} from "next/server";
export type ValueOf<T> = T[keyof T];
export type EnumLikeKey<T extends Record<string, unknown>> = keyof T;
export type EnumLikeValue<T extends Record<string, unknown>> = ValueOf<T>;
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@@ -54,10 +54,7 @@ export const catchRedirectPageLanding = async (req: NextRequest, event: NextFetc
}
// 실패 처리 1) 에러 페이지로 redirect (추천)
const errUrl = new URL("/redirect/error", req.url);
errUrl.searchParams.set("code", String(res.status));
errUrl.searchParams.set("sid", req.nextUrl.searchParams.get("sid") ?? "");
return NextResponse.redirect(errUrl, 307);
return goToError(req);
// 실패 처리 2) 그냥 에러 응답으로 차단하고 싶으면 아래로 대체
// const text = await res.text().catch(() => "");
@@ -65,11 +62,15 @@ export const catchRedirectPageLanding = async (req: NextRequest, event: NextFetc
} catch (e) {
// 타임아웃/네트워크 오류 등
const errUrl = new URL("/redirect/error", req.url);
errUrl.searchParams.set("code", "fetch_error");
errUrl.searchParams.set("sid", req.nextUrl.searchParams.get("sid") ?? "");
return NextResponse.redirect(errUrl, 307);
return goToError(req);
} finally {
clearTimeout(t);
}
};
};
const goToError = (req: NextRequest) => {
const errUrl = new URL("/redirect/error", req.url);
errUrl.searchParams.set("code", "fetch_error");
errUrl.searchParams.set("sid", req.nextUrl.searchParams.get("sid") ?? "");
return NextResponse.redirect(errUrl, 307);
}

View File

@@ -1,7 +1,7 @@
"use client";
import {keepPreviousData, useQuery} from "@tanstack/react-query";
import {qk} from "@/query/keys";
import {qk} from "@/query/key/keys";
import {nextApi} from "@/lib/http-client";
import {ItrntUserInfo} from "@/types/user";
import {IntranetProjectSearchResponse, KonKiwiProjectInfo} from "@/types/project";

View File

@@ -1,6 +1,7 @@
import type { ChannelType } from "@/types/messageTemplate";
export const qk = {
/********** 사용자 관리 관련 **********/
roleList: () => ["role", "list"] as const,
userCompanies: () => ["user", "companies"] as const,
users: () => ["user", "list"] as const,
@@ -8,7 +9,9 @@ export const qk = {
fieldworkUsers: () => ["user", "fieldwork"] as const,
outsourceUsers: () => ["user", "outsource"] as const,
/********** 사용자 관리 관련 **********/
/********** 프로젝트 관련 **********/
projectTop: (count: number, keyword: string) => ["project", "top", count, keyword] as const,
projectOwnerList: () => ["project", "owner-list"] as const,
projectList: (
@@ -18,21 +21,36 @@ export const qk = {
sortBy: string,
sortDir: "asc" | "desc"
) => ["project", "list", query, pageIndex, pageSize, sortBy, sortDir] as const,
assignFieldwork: (prjctIdx: number) => ["assign", "prjct-fieldwork", prjctIdx] as const,
assignOutsource: (prjctIdx: number) => ["assign", "prjct-outsource", prjctIdx] as const,
projectInfo: (prjctIdx: number) => ["project", "info", prjctIdx] as const,
resultCodes: (prjctIdx: number) => ["result-code", prjctIdx] as const,
/********** 프로젝트 관련 **********/
/********** 배정 관련 **********/
projectAssignFieldwork: (prjctIdx: number) => ["assign", "prjct-fieldwork", prjctIdx] as const,
projectAssignOutsource: (prjctIdx: number) => ["assign", "prjct-outsource", prjctIdx] as const,
/********** 배정 관련 **********/
/********** KON, KIWI 프로젝트 관련 KART에서 받아옴 **********/
kartProjectList: (itrntPrjctCd: string, userTeam: string, isKiwi: number, keyword: string) =>
["kart", "project-list", itrntPrjctCd, userTeam, isKiwi, keyword] as const,
/********** KON, KIWI 프로젝트 관련 KART에서 받아옴 **********/
/********** 인트라넷 관련 **********/
intranetProjectList: (keyword: string) => ["intranet", "project-list", keyword] as const,
intranetUsers: () => ["intranet", "user-list"] as const,
/********** 인트라넷 관련 **********/
/********** 리스트 관련 **********/
listHeader: (prjctIdx: number) => ["list", "header", prjctIdx] as const,
listSearch: (prjctIdx: number, body: unknown) => ["list", "search-filter", prjctIdx, body] as const,
/********** 리스트 관련 **********/
/********** 템플릿 및 발송 관련 **********/
mainTemplate: (prjctIdx: number, chnnlTy: ChannelType) =>
["project", "main-template", prjctIdx, chnnlTy] as const,
templateList: (chnnlTy: ChannelType, itrntPrjctCd: string) =>
["message-template", "list", chnnlTy, itrntPrjctCd] as const,
template: (tmplatIdx: number) => ["message-template", "detail", tmplatIdx] as const,
} as const;
/********** 템플릿 및 발송 관련 **********/
} as const;

55
src/query/list.ts Normal file
View File

@@ -0,0 +1,55 @@
import {keepPreviousData, useQuery} from "@tanstack/react-query";
import {qk} from "@/query/key/keys";
import {nextApi} from "@/lib/http-client";
import {listHeader, ListSearchRequest, ListSearchWithFullResult} from "@/types/list";
import {PageResponse} from "@/types/common";
import {ListHeaderAssignConst} from "@/const/listConst";
export function useListHeaderQuery(prjctIdx: number, enabled: boolean) {
return useQuery({
queryKey: qk.listHeader(prjctIdx),
queryFn: () =>
nextApi.get<listHeader[]>(
`/list/header/${prjctIdx}`
),
enabled,
staleTime: 0, // 항상 오래된 데이터 취급
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
placeholderData: keepPreviousData,
meta: { ignoreGlobalLoading: true },
});
}
const serializeListSearchRequest = (request: ListSearchRequest) => ({
listFilter: {
sidSet: request.listFilter.sidSet ?? [],
listUseSet: request.listFilter.listUseSet ?? [],
assignUserMap: request.listFilter.assignUserMap ?? {
[ListHeaderAssignConst.OUTSOURCE]: [],
[ListHeaderAssignConst.CONTACT_INTERVIEWER]: [],
[ListHeaderAssignConst.FIELD_INTERVIEWER]: [],
},
memo: request.listFilter.memo ?? "",
otherItems: request.listFilter.otherItems ?? {},
},
pageRequest: request.pageRequest,
});
export function useListSearchQuery(prjctIdx: number, request: ListSearchRequest, enabled: boolean) {
const serializedBody = serializeListSearchRequest(request);
return useQuery({
queryKey: qk.listSearch(prjctIdx, serializedBody),
queryFn: () =>
nextApi.post<PageResponse<ListSearchWithFullResult>>(
`/list/search-filter/${prjctIdx}`,
serializedBody
),
enabled,
staleTime: 0,
refetchOnMount: "always",
placeholderData: keepPreviousData,
meta: { ignoreGlobalLoading: true },
});
}

View File

@@ -2,7 +2,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { qk } from "@/query/keys";
import { qk } from "@/query/key/keys";
import type { ChannelType, Template, TemplateSummary } from "@/types/messageTemplate";
import type { ProjectMainTemplateUpdateRequest } from "@/types/project";

View File

@@ -2,7 +2,7 @@
import {useQuery, keepPreviousData, useQueryClient, useMutation} from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { qk } from "@/query/keys";
import { qk } from "@/query/key/keys";
import type {
KonKiwiProjectInfo,
ProjectCreateRequest,
@@ -135,7 +135,7 @@ export function useKartProjectListQuery(args: {
*/
export function useAssignedOutsourceIdsQuery(prjctIdx: number, enabled: boolean) {
return useQuery({
queryKey: qk.assignOutsource(prjctIdx),
queryKey: qk.projectAssignOutsource(prjctIdx),
queryFn: () => nextApi.get<string[]>(`/assign/prjct-outsource/${prjctIdx}`),
enabled,
staleTime: 0,
@@ -145,7 +145,7 @@ export function useAssignedOutsourceIdsQuery(prjctIdx: number, enabled: boolean)
export function useAssignedFieldworkIdsQuery(prjctIdx: number, enabled: boolean) {
return useQuery({
queryKey: qk.assignFieldwork(prjctIdx),
queryKey: qk.projectAssignFieldwork(prjctIdx),
queryFn: () => nextApi.get<string[]>(`/assign/prjct-fieldwork/${prjctIdx}`),
enabled,
staleTime: 0,
@@ -189,7 +189,7 @@ export function useSaveAssignedFieldworkMutation(prjctIdx: number) {
mutationFn: (userIds: string[]) =>
nextApi.put<void>(`/assign/prjct-fieldwork/${prjctIdx}`, userIds),
onSuccess: () => {
qc.invalidateQueries({ queryKey: qk.assignFieldwork(prjctIdx) });
qc.invalidateQueries({ queryKey: qk.projectAssignFieldwork(prjctIdx) });
},
});
}

View File

@@ -2,11 +2,15 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { qk } from "@/query/keys";
import { qk } from "@/query/key/keys";
// 프로젝트에 존재하는 타입 기준(경로/이름 다르면 import만 수정)
import type { RoleInfo } from "@/types/role";
import type { UserInfo, UserInfoSaveRequest, UserUploadResponse } from "@/types/user";
import type {
ExcelUploadResult,
UserInfo,
UserInfoSaveRequest,
} from "@/types/user";
import type { DataVerification } from "@/types/common";
export function useRoleListQuery() {
@@ -108,10 +112,10 @@ export function useUploadUsersExcelMutation() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (file: File) => {
mutationFn: async (file: File): Promise<ExcelUploadResult> => {
const formData = new FormData();
formData.append("file", file);
return nextApi.postForm<UserUploadResponse>("/user/excel", formData);
return nextApi.postForm<ExcelUploadResult>("/user/excel-upload", formData);
},
onSuccess: (res) => {
if (!res.hasErrorFile) {
@@ -126,4 +130,4 @@ export function useDownloadUserExcelTemplateMutation() {
mutationFn: () =>
nextApi.post<ArrayBuffer>("/user/excel-template", undefined, { expectBinary: true }),
});
}
}

View File

@@ -6,9 +6,17 @@ export type DialogId =
| 'userUpsertDialog'
| 'userUploadDialog'
| 'listUploadDialog'
| 'listBatchEditDialog'
| 'listFilterDialog'
| 'projectCreateDialog'
| 'resultCodeDialog'
| 'resultCodeCopyDialog'
| 'listResetDialog'
| 'listExcelUploadDialog'
| 'listHeaderManageDialog'
| 'listDownloadDialog'
| 'messageSendDialog'
| 'messageHistoryDialog'
// 현재 열려 있는 다이얼로그 ID 리스트
export const openDialogIdsAtom = atom<DialogId[]>([])
export const openDialogIdsAtom = atom<DialogId[]>([])

View File

@@ -2,6 +2,7 @@
import { StorageKeys } from "@/store/storage/storage-keys";
import {createSessionStorageAtom} from "@/store/jotai/utils";
import {SurveyType} from "@/types/project";
export type SelectedProject = {
prjctIdx: number;
@@ -10,6 +11,8 @@ export type SelectedProject = {
itrntPrjctCd: string;
ownerDept: string;
ownerFw: string;
surveyTy: SurveyType;
ff: boolean;
};
/**

View File

@@ -1,27 +1,82 @@
import {PageRequest} from "@/types/common";
import {EnumLikeKey, EnumLikeValue} from "@/lib/utils";
import {ListHeaderAssignConst, ListHeaderConst} from "@/const/listConst";
export enum ListHeaderGrade {
IMMUTABLE = 0,
DEFAULT = 1,
NORMAL = 2,
RESERVED = 1,
COMMON = 10,
}
export enum ListHeaderType {
TEL = 21,
EMAIL = 31,
FILE_UPLOAD = 81,
TEXT = 91,
export type ListHeaderTypeKey = EnumLikeKey<typeof ListHeaderConst>;
export type ListHeaderType = EnumLikeValue<typeof ListHeaderConst>;
export type ListHeaderAssignTypeKey = EnumLikeKey<typeof ListHeaderAssignConst>;
export type ListHeaderAssignType = EnumLikeValue<typeof ListHeaderAssignConst>;
export enum ListIsUse {
UNUSABLE = 0, //0 : 사용 안함
USABLE = 1, //1 : 사용
TEST = 9, //9 : TEST
}
export type listHder = {
export type listHeader = {
listHderId: number;
listHderOrder: number;
listHderGrad: ListHeaderGrade;
listHderNm: string;
listHderTy: ListHeaderType
useFilter: boolean;
useView: boolean;
useColView: boolean;
useIntrvwerView: boolean;
useIntrvwerEdit: boolean;
regUser: string;
regDt: string;
modUser?: string;
modDt?: string;
}
}
export type ListFilter = {
sidSet: string[];
listUseSet: ListIsUse[];
assignUserMap: Record<ListHeaderAssignType, string[]>;
memo: string; // 또는 memo?: string | null
otherItems: Record<number, string[]>;
};
export type ListSearchRequest = {
listFilter: ListFilter;
pageRequest: PageRequest;
}
export type ListResultBase = {
lastResultCd: number;
lastResultDt: string;
attemptCount: number;
};
export type ListSendResult = ListResultBase & {
lastResultLabel: string;
}
export type ListContactResult = ListResultBase & {
lastUser: string;
assignUser: string;
};
export type ListSearchBase = {
prjctIdx: number;
sid: number;
use: ListIsUse;
assignList: Record<ListHeaderAssignType, string>;
memo: string;
itemList: Record<number, string>;
};
export type ListSearchWithResult = ListSearchBase & {
contactResult: ListContactResult;
interviewResult: ListContactResult;
surveyResult: ListResultBase;
};
export type ListSearchWithFullResult = ListSearchWithResult & {
mailSendResult: ListSendResult;
smsSendResult?: ListSendResult;
};

View File

@@ -41,11 +41,11 @@ export type UserInfoSaveRequest = {
memo?: string
}
export type UserUploadResponse = {
export type ExcelUploadResult = {
totalCount: number;
successCount: number;
failCount: number;
hasErrorFile: boolean;
errorFileName: string | null;
errorFileBase64: string | null;
};
errorFileName: string;
errorFileBase64: string;
}