From 694406437757a76b5d46e4829321f005d9b9ee65 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 27 Apr 2026 09:55:51 +0900 Subject: [PATCH 1/3] =?UTF-8?q?260427=5F01=5FENH:=20=EB=A6=AC=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EB=8B=A4=EC=9D=B4=EC=96=BC=EB=A1=9C=EA=B7=B8=20?= =?UTF-8?q?=EB=B0=8F=20=EB=A6=AC=EC=8A=A4=ED=8A=B8=20=EC=9E=91=EC=97=85=20?= =?UTF-8?q?=EC=8B=9C=EC=9E=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{list/assign => assign/list}/page.tsx | 0 .../assign => assign/project}/page.tsx | 0 src/app/(pages)/(main)/list/manage/page.tsx | 399 +++++++++++++- src/app/(pages)/(main)/manage/user/page.tsx | 8 +- .../(main)/message/template/email/page.tsx | 1 - .../(main)/message/template/sms/page.tsx | 1 - src/app/(pages)/(main)/page.tsx | 4 + src/app/(pages)/login/page.tsx | 10 +- src/app/api/external/[[...slug]]/route.ts | 1 - src/app/api/list/[[...slug]]/route.ts | 52 ++ src/app/api/project/[[...slug]]/route.ts | 4 +- src/app/api/user/[[...slug]]/route.ts | 8 +- src/app/globals.css | 16 +- src/components/dialog/ListBatchEditDialog.tsx | 208 ++++++++ src/components/dialog/ListDownloadDialog.tsx | 96 ++++ src/components/dialog/ListFilterDialog.tsx | 280 ++++++++++ .../dialog/ListHeaderManageDialog.tsx | 167 ++++++ src/components/dialog/ListResetDialog.tsx | 107 ++++ src/components/dialog/ListUploadDialog.tsx | 486 ++++++++---------- .../dialog/MessageHistoryDialog.tsx | 211 ++++++++ src/components/dialog/MessageSendDialog.tsx | 291 +++++++++++ src/components/dialog/UserUploadDialog.tsx | 2 +- src/components/dialog/UserUpsertDialog.tsx | 8 +- src/components/external/RedirectLanding.tsx | 48 +- .../message-template/MessageTemplate.tsx | 4 +- .../table-column/ListTableColumn.tsx | 179 +++++++ src/components/ui/dialog.tsx | 2 +- src/config/menu.data.ts | 4 +- src/config/redirect.data.ts | 39 ++ src/config/redirect.types.ts | 10 + src/const/listConst.ts | 68 ++- src/hooks/useItrntUserList.ts | 2 +- src/lib/http-client.ts | 30 +- src/lib/utils.ts | 5 + src/middleware/catchRedirectPageLanding.ts | 19 +- src/query/intranet.ts | 2 +- src/query/{ => key}/keys.ts | 24 +- src/query/list.ts | 55 ++ src/query/message.ts | 2 +- src/query/project.ts | 8 +- src/query/user.ts | 14 +- src/store/jotai/dialog.ts | 10 +- src/store/jotai/project.ts | 3 + src/types/list.ts | 83 ++- src/types/user.ts | 8 +- 45 files changed, 2560 insertions(+), 419 deletions(-) rename src/app/(pages)/(main)/{list/assign => assign/list}/page.tsx (100%) rename src/app/(pages)/(main)/{project/assign => assign/project}/page.tsx (100%) create mode 100644 src/app/api/list/[[...slug]]/route.ts create mode 100644 src/components/dialog/ListBatchEditDialog.tsx create mode 100644 src/components/dialog/ListDownloadDialog.tsx create mode 100644 src/components/dialog/ListFilterDialog.tsx create mode 100644 src/components/dialog/ListHeaderManageDialog.tsx create mode 100644 src/components/dialog/ListResetDialog.tsx create mode 100644 src/components/dialog/MessageHistoryDialog.tsx create mode 100644 src/components/dialog/MessageSendDialog.tsx create mode 100644 src/components/table-column/ListTableColumn.tsx create mode 100644 src/config/redirect.data.ts create mode 100644 src/config/redirect.types.ts rename src/query/{ => key}/keys.ts (59%) create mode 100644 src/query/list.ts diff --git a/src/app/(pages)/(main)/list/assign/page.tsx b/src/app/(pages)/(main)/assign/list/page.tsx similarity index 100% rename from src/app/(pages)/(main)/list/assign/page.tsx rename to src/app/(pages)/(main)/assign/list/page.tsx diff --git a/src/app/(pages)/(main)/project/assign/page.tsx b/src/app/(pages)/(main)/assign/project/page.tsx similarity index 100% rename from src/app/(pages)/(main)/project/assign/page.tsx rename to src/app/(pages)/(main)/assign/project/page.tsx diff --git a/src/app/(pages)/(main)/list/manage/page.tsx b/src/app/(pages)/(main)/list/manage/page.tsx index d60be54..9446b2e 100644 --- a/src/app/(pages)/(main)/list/manage/page.tsx +++ b/src/app/(pages)/(main)/list/manage/page.tsx @@ -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 ; + const [searchText, setSearchText] = useState('') + const [searchContactResult, setSearchContactResult] = useState([]) + const [searchInterviewResult, setSearchInterviewResult] = useState([]) + const [searchSurveyResult, setSearchSurveyResult] = useState([]) + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 10 }) + const [sorting, setSorting] = useState([]) + + const [downloadMode, setDownloadMode] = useState('list') + const [messageSendMode, setMessageSendMode] = useState('email') + const [filterRows, setFilterRows] = useState([]) + const [batchRows, setBatchRows] = useState([]) + + 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(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]) + + const listSearchRequest = useMemo(() => { + 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[]>(() => { + if (!listHeaderQuery.data) return [] + return getListColumns(listHeaderQuery.data, resultCodeArray, userRole) + }, [listHeaderQuery.data, resultCodeArray, userRole]) + + const viewList = useMemo( + () => (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( + () => + (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 return (
-
- This is Manage List Page {fontSize} +
+
+ + + + + + + +
+ + +
-
- ); -}; -export default ListManagePage; \ No newline at end of file +
+
+ setSearchText(e.target.value)} + /> + item.resultCdTy === ResultCodeType.CONTACT)} + value={searchContactResult} + onChange={setSearchContactResult} + getValue={(item) => String(item.resultCd)} + getLabel={(item) => item.resultCdLbl} + placeholder="컨택 결과" + widthClassName="w-70" + heightClassName="h-9" + /> + item.resultCdTy === ResultCodeType.INTERVIEW)} + value={searchInterviewResult} + onChange={setSearchInterviewResult} + getValue={(item) => String(item.resultCd)} + getLabel={(item) => item.resultCdLbl} + placeholder="면접 결과" + widthClassName="w-70" + heightClassName="h-9" + /> + item.resultCdTy === ResultCodeType.SURVEY)} + value={searchSurveyResult} + onChange={setSearchSurveyResult} + getValue={(item) => String(item.resultCd)} + getLabel={(item) => item.resultCdLbl} + placeholder="설문 결과" + widthClassName="w-70" + heightClassName="h-9" + /> + + + +
+
+ +
+ + columns={columns} + data={viewList} + isClient={false} + pageCount={pageCount} + totalCount={totalCount} + onPaginationChange={setPagination} + onSortingChange={setSorting} + selectMode="click-event" + pageSizeOptions={[10, 20, 30, 50]} + /> +
+ + + + + + [row.headerId, row.multiValues]))} + initialRows={batchRows} + onConfirm={handleBatchConfirm} + /> + + + +
+ ) +} + +export default ListManagePage diff --git a/src/app/(pages)/(main)/manage/user/page.tsx b/src/app/(pages)/(main)/manage/user/page.tsx index 4be0f3c..fdaeb91 100644 --- a/src/app/(pages)/(main)/manage/user/page.tsx +++ b/src/app/(pages)/(main)/manage/user/page.tsx @@ -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 = () => { @@ -240,4 +242,4 @@ const UserManagePage = () => { ); } -export default UserManagePage; \ No newline at end of file +export default UserManagePage; diff --git a/src/app/(pages)/(main)/message/template/email/page.tsx b/src/app/(pages)/(main)/message/template/email/page.tsx index 84b2100..03f86b7 100644 --- a/src/app/(pages)/(main)/message/template/email/page.tsx +++ b/src/app/(pages)/(main)/message/template/email/page.tsx @@ -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 = () => { diff --git a/src/app/(pages)/(main)/message/template/sms/page.tsx b/src/app/(pages)/(main)/message/template/sms/page.tsx index d1aea99..5f19e7d 100644 --- a/src/app/(pages)/(main)/message/template/sms/page.tsx +++ b/src/app/(pages)/(main)/message/template/sms/page.tsx @@ -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 = () => { diff --git a/src/app/(pages)/(main)/page.tsx b/src/app/(pages)/(main)/page.tsx index ede3317..cef4c0f 100644 --- a/src/app/(pages)/(main)/page.tsx +++ b/src/app/(pages)/(main)/page.tsx @@ -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`); diff --git a/src/app/(pages)/login/page.tsx b/src/app/(pages)/login/page.tsx index 6305a90..a2a47b4 100644 --- a/src/app/(pages)/login/page.tsx +++ b/src/app/(pages)/login/page.tsx @@ -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(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; \ No newline at end of file +export default LoginPage; diff --git a/src/app/api/external/[[...slug]]/route.ts b/src/app/api/external/[[...slug]]/route.ts index 3f64d11..ad1782d 100644 --- a/src/app/api/external/[[...slug]]/route.ts +++ b/src/app/api/external/[[...slug]]/route.ts @@ -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){ diff --git a/src/app/api/list/[[...slug]]/route.ts b/src/app/api/list/[[...slug]]/route.ts new file mode 100644 index 0000000..5343c76 --- /dev/null +++ b/src/app/api/list/[[...slug]]/route.ts @@ -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( + `/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>( + `/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); + } +}; diff --git a/src/app/api/project/[[...slug]]/route.ts b/src/app/api/project/[[...slug]]/route.ts index 1181de4..49e1b1d 100644 --- a/src/app/api/project/[[...slug]]/route.ts +++ b/src/app/api/project/[[...slug]]/route.ts @@ -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: "요청 바디가 없습니다." }, diff --git a/src/app/api/user/[[...slug]]/route.ts b/src/app/api/user/[[...slug]]/route.ts index 8def304..9cffa10 100644 --- a/src/app/api/user/[[...slug]]/route.ts +++ b/src/app/api/user/[[...slug]]/route.ts @@ -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( - "/user/excel", + const result = await contactApi.postForm( + "/user/excel/upload", backendForm ); diff --git a/src/app/globals.css b/src/app/globals.css index 7f9f63a..36f0dd0 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -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; -} \ No newline at end of file +} diff --git a/src/components/dialog/ListBatchEditDialog.tsx b/src/components/dialog/ListBatchEditDialog.tsx new file mode 100644 index 0000000..aef3df8 --- /dev/null +++ b/src/components/dialog/ListBatchEditDialog.tsx @@ -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 + headerOptions: BatchEditOption[] + initialRows?: BatchEditRow[] + onConfirm: (rows: BatchEditRow[]) => void | Promise +} + +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([]) + 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 ( + + + + 일괄 수정 + + +
+
+

적용된 필터

+

+ {filterSummary.length > 0 ? filterSummary : '적용된 필터가 없습니다.'} +

+
+ +
+
+ 헤더 + 수정 값 + +
+ +
+ {rows.map((row) => ( +
+ + + handleChangeValue(row.id, e.target.value)} + placeholder="수정할 값을 입력해 주세요" + /> + +
+ +
+
+ ))} +
+
+ + +
+ + + + + +
+
+ ) +} + +export default ListBatchEditDialog diff --git a/src/components/dialog/ListDownloadDialog.tsx b/src/components/dialog/ListDownloadDialog.tsx new file mode 100644 index 0000000..fd33084 --- /dev/null +++ b/src/components/dialog/ListDownloadDialog.tsx @@ -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 +} + +const titleMap: Record = { + 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 ( + + + + {titleMap[mode]} + + +
+

다운로드 범위

+ setScope(v as 'filtered' | 'all')} className="space-y-2"> +
+ + +
+
+ + +
+
+
+ + + + + +
+
+ ) +} + +export default ListDownloadDialog diff --git a/src/components/dialog/ListFilterDialog.tsx b/src/components/dialog/ListFilterDialog.tsx new file mode 100644 index 0000000..1e2b744 --- /dev/null +++ b/src/components/dialog/ListFilterDialog.tsx @@ -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 +} + +const operatorLabel: Record = { + 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([]) + 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 ( + + + + 필터 + + +
+
+ 헤더 + 비교 연산자 + 값 + +
+ +
+ {rows.map((row) => { + const valueOptions = getValueOptions(row.headerId) + const textMode = row.operator === 'contains' || row.operator === 'notContains' + + return ( +
+ + + + + {textMode ? ( + + handleChangeRow(row.id, (current) => ({ + ...current, + textValue: e.target.value, + })) + } + /> + ) : ( +
+ + +
+ )} + +
+ +
+
+ ) + })} +
+
+ + + + + + + +
+
+ ) +} + +export default ListFilterDialog diff --git a/src/components/dialog/ListHeaderManageDialog.tsx b/src/components/dialog/ListHeaderManageDialog.tsx new file mode 100644 index 0000000..369d29b --- /dev/null +++ b/src/components/dialog/ListHeaderManageDialog.tsx @@ -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 +} + +const ListHeaderManageDialog = ({ + dialogId = 'listHeaderManageDialog', + open, + onOpenChange, + rows, + onConfirm, +}: ListHeaderManageDialogProps) => { + const { isDialogOpen, showDialog, hideDialog } = useDialog() + const [localRows, setLocalRows] = useState([]) + const [draggingId, setDraggingId] = useState(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 ( + + + + 리스트 헤더 관리 + + +
+
+ 순서 + 헤더명 + 노출 + 삭제 +
+ +
+ {localRows.map((row) => ( +
setDraggingId(row.id)} + onDragEnd={() => setDraggingId(null)} + onDragOver={(e) => e.preventDefault()} + onDrop={() => handleDrop(row.id)} + > +
+ +
+ {row.name} +
+ handleVisibleChange(row.id, checked === true)} + disabled={row.locked} + /> + +
+
+ +
+
+ ))} +
+
+ + + + + +
+
+ ) +} + +export default ListHeaderManageDialog diff --git a/src/components/dialog/ListResetDialog.tsx b/src/components/dialog/ListResetDialog.tsx new file mode 100644 index 0000000..8b201b8 --- /dev/null +++ b/src/components/dialog/ListResetDialog.tsx @@ -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 +} + +const ListResetDialog = ({ + dialogId = 'listResetDialog', + open, + onOpenChange, + onConfirm, +}: ListResetDialogProps) => { + const { isDialogOpen, showDialog, hideDialog } = useDialog() + const [target, setTarget] = useState('selected') + const [scope, setScope] = useState('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 ( + + + + 리스트 초기화 + + +
+
+

초기화 대상

+ setTarget(v as ListResetTarget)} className="space-y-2"> +
+ + +
+
+ + +
+
+ + +
+
+
+ +
+

초기화 범위

+ setScope(v as ListResetScope)} className="space-y-2"> +
+ + +
+
+ + +
+
+
+
+ + + + + +
+
+ ) +} + +export default ListResetDialog diff --git a/src/components/dialog/ListUploadDialog.tsx b/src/components/dialog/ListUploadDialog.tsx index 613e9e7..95a984c 100644 --- a/src/components/dialog/ListUploadDialog.tsx +++ b/src/components/dialog/ListUploadDialog.tsx @@ -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 - 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 + onDownloadTemplate?: () => void | Promise + uploadHistory?: ListUploadHistory[] + onDownloadHistory?: (item: ListUploadHistory) => void | Promise +} + +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(null) const [selectedFile, setSelectedFile] = useState(null) - const [uploadMode, setUploadMode] = useState('add') + const [submitting, setSubmitting] = useState(false) + const [historyExpanded, setHistoryExpanded] = useState(true) const [validation, setValidation] = useState({ checkEmailDuplicate: false, checkPhoneDuplicate: false, }) - const [isUploading, setIsUploading] = useState(false) - const fileInputRef = useRef(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) => { - 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) => { + 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 ( - - - - 엑셀 업로드 - + + + + 리스트 업로드 + -
- {/* 1. 리스트 업로드 */} -
- -
- - -
- - {selectedFile && ( -
- - {selectedFile.name} - - -
- )} -
- - {/* 2. Excel 파일 업로드 */} -
- -
- - {/* 3. 업로드 방식 선택 */} -
- - setUploadMode(value as UploadMode)} - > -
- - -
-
- - -
-
-
- - {/* 4. 중복 검사 옵션 */} -
- -
-
- - setValidation(prev => ({ - ...prev, - checkEmailDuplicate: checked === true, - })) - } - /> - -
-
- - setValidation(prev => ({ - ...prev, - checkPhoneDuplicate: checked === true, - })) - } - /> - -
-
-
- - {/* 5. 업로드 이력 (드롭다운) */} -
- - + + +
- -
- - 6 - - +
+ +
+
+ + setValidation((prev) => ({ + ...prev, + checkEmailDuplicate: checked === true, + })) + } + /> + +
+
+ + setValidation((prev) => ({ + ...prev, + checkPhoneDuplicate: checked === true, + })) + } + /> + +
- - -
+ + +
+ + + {historyExpanded && ( +
+ + + + + + + + + + + + + {normalizedHistory.length === 0 && ( + + + + )} + {normalizedHistory.map((item) => ( + + + + + + + + + ))} + +
회차파일명사용자 ID업로드 건수업로드 일시다운로드
+ 업로드 이력이 없습니다. +
{item.round}{item.fileName}{item.userId}{item.uploadCount.toLocaleString()}{item.uploadAtLabel} + +
+
+ )} +
+ + + + + + +
+
) } -export default ListUploadDialog \ No newline at end of file +export default ListUploadDialog diff --git a/src/components/dialog/MessageHistoryDialog.tsx b/src/components/dialog/MessageHistoryDialog.tsx new file mode 100644 index 0000000..7b31647 --- /dev/null +++ b/src/components/dialog/MessageHistoryDialog.tsx @@ -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) => void | Promise +} + +const tabLabelMap: Record = { + sms: '문자', + email: '이메일', +} + +const MessageHistoryDialog = ({ + dialogId = 'messageHistoryDialog', + open, + onOpenChange, + rows, + onDownload, +}: MessageHistoryDialogProps) => { + const { isDialogOpen, showDialog, hideDialog } = useDialog() + const [tab, setTab] = useState('sms') + const [selectedId, setSelectedId] = useState(null) + const [detailType, setDetailType] = useState(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) => { + 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 ( + + + + 발송 이력 + + +
+ + +
+ +
+
+ + + + + + + + + + + + + + + + + + {visibleRows.length === 0 && ( + + + + )} + {visibleRows.map((row) => ( + + + + + + + + + + + + + + ))} + +
회차제목템플릿발송 정보타겟 헤더대상수성공실패등록 일시발송 일시상태
+ 발송 이력이 없습니다. +
{row.id}{row.title} + + {row.sendInfo} + + {row.targetCount} + + + + {row.createdAt}{row.sendAt}{row.status}
+
+ +
+

+ {detailType === null && '상세 이력'} + {detailType === 'template' && '미리보기'} + {detailType === 'target' && '수신 대상'} + {detailType === 'success' && '성공 이력'} + {detailType === 'fail' && '실패 이력'} +

+ + {detailType === null && ( +

+ 템플릿, 대상수, 성공, 실패 항목을 선택하면 상세 영역이 열립니다. +

+ )} + + {detailType !== null && ( + <> +
{detailContent}
+ + + )} +
+
+ + + + +
+
+ ) +} + +export default MessageHistoryDialog diff --git a/src/components/dialog/MessageSendDialog.tsx b/src/components/dialog/MessageSendDialog.tsx new file mode 100644 index 0000000..6c7a4c0 --- /dev/null +++ b/src/components/dialog/MessageSendDialog.tsx @@ -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 +} + +const titleMap: Record = { + 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('instant') + const [reserveAt, setReserveAt] = useState('') + const [targetHeaderId, setTargetHeaderId] = useState(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 ( + + + + {titleMap[mode]} + + +
+
+
+ + +
+ + {mode === 'email' ? ( +
+
+ + setSenderEmail(e.target.value)} /> +
+
+ + setSenderName(e.target.value)} /> +
+
+ ) : ( +
+ + setSenderNumber(e.target.value)} /> +
+ )} + +
+ + setTitle(e.target.value)} /> +
+ +
+ +