260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋

This commit is contained in:
2026-07-14 10:59:07 +09:00
parent a8ce35f5bf
commit 192d47bdb1
180 changed files with 11942 additions and 6007 deletions

View File

@@ -0,0 +1,233 @@
'use client'
import { useEffect, useState } from 'react'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
import type { CmpnInfoSaveRequest } from '@/types/cmpn'
import type { DataVerification } from "@kri/common";
import { apiError, NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR } from "@kri/common/http";
export type CmpnUpsertDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
mode?: 'create' | 'edit'
initialData?: Partial<CmpnInfoSaveRequest>
onSubmit: (data: CmpnInfoSaveRequest) => void | Promise<void>
onCheckDuplicate?: (cmpnId: string) => DataVerification | Promise<DataVerification>
}
const createDefaultCmpnInfo = (): CmpnInfoSaveRequest => ({
cmpnId: '',
cmpnAlias: '',
cmpnTel: '',
ownCmpn: false,
memo: '',
})
const CmpnUpsertDialog = ({
dialogId = 'cmpnUpsertDialog',
open,
onOpenChange,
mode = 'create',
initialData,
onSubmit,
onCheckDuplicate,
}: CmpnUpsertDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog();
const [formData, setFormData] = useState<CmpnInfoSaveRequest>(createDefaultCmpnInfo);
const [isCheckedDuplicate, setIsCheckedDuplicate] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const resolvedOpen = open ?? isDialogOpen(dialogId);
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen);
if (nextOpen) {
showDialog(dialogId);
} else {
hideDialog(dialogId);
}
}
useEffect(() => {
if (initialData) {
setFormData({
...createDefaultCmpnInfo(),
...initialData,
});
if (mode === 'edit') {
setIsCheckedDuplicate(true);
}
} else {
setFormData(createDefaultCmpnInfo());
setIsCheckedDuplicate(false);
}
}, [initialData, mode, resolvedOpen]);
const handleInputChange = (field: keyof CmpnInfoSaveRequest, value: string) => {
setFormData((prev) => ({
...prev,
[field]: value,
}));
if (field === 'cmpnId' && mode === 'create') {
setIsCheckedDuplicate(false);
}
}
const handleCheckDuplicate = async () => {
const cmpnId = formData.cmpnId.trim();
if (!cmpnId) {
alert("회사 ID를 입력해주세요.");
return;
}
if (onCheckDuplicate) {
const result = await onCheckDuplicate(cmpnId);
if (!result.success) {
alert(result.errMessage);
setIsCheckedDuplicate(false);
} else {
alert("사용 가능한 회사 ID입니다.");
setIsCheckedDuplicate(true);
}
} else {
setIsCheckedDuplicate(true);
}
}
const handleSubmit = async () => {
if (!formData.cmpnId.trim()) {
alert("회사 ID를 입력해주세요.");
return;
}
if (mode === 'create' && !isCheckedDuplicate) {
alert("회사 ID 중복체크를 해주세요.");
return;
}
if (!formData.cmpnAlias.trim()) {
alert("별칭을 입력해주세요.");
return;
}
setIsSubmitting(true);
try {
await onSubmit({
...formData,
cmpnId: formData.cmpnId.trim(),
cmpnAlias: formData.cmpnAlias.trim(),
cmpnTel: formData.cmpnTel?.trim(),
ownCmpn: mode === 'create' ? false : formData.ownCmpn,
memo: formData.memo?.trim(),
});
handleOpenChange(false);
} catch (e) {
const err = apiError(e, {
fallbackMessage: "Save failed.",
});
console.error(err.status, err.code, err.message);
if (err.code !== NONE_HTTP_ERROR && err.code !== UNKNOWN_HTTP_ERROR) {
alert(err.message);
} else {
alert("저장에 실패했습니다.");
}
} finally {
setIsSubmitting(false);
}
}
return (
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-xl">{mode === 'create' ? '회사 등록' : '회사 수정'}</span>}
description="회사 정보를 입력해주세요."
contentClassName="sm:max-w-[500px] text-sm"
bodyClassName="grid gap-4 py-4"
footer={
<>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
취소
</Button>
<Button
type="submit"
onClick={handleSubmit}
disabled={isSubmitting}
>
{mode === 'create' ? "등록" : "수정"}
</Button>
</>
}
>
<div className="grid gap-2">
<Label htmlFor="cmpnId">
회사 ID<span className="text-red-500 ml-1">*</span>
</Label>
<div className="flex gap-2">
<Input
id="cmpnId"
placeholder="Enter company ID"
value={formData.cmpnId}
onChange={(e) => handleInputChange('cmpnId', e.target.value)}
disabled={mode === 'edit'}
/>
{mode === 'create' && (
<Button
variant="outline"
onClick={handleCheckDuplicate}
disabled={!formData.cmpnId.trim() || isCheckedDuplicate}
>
{isCheckedDuplicate ? "확인완료" : "중복체크"}
</Button>
)}
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="cmpnAlias">별칭</Label>
<Input
id="cmpnAlias"
placeholder="Enter alias"
value={formData.cmpnAlias ?? ''}
onChange={(e) => handleInputChange('cmpnAlias', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="cmpnTel">전화번호</Label>
<Input
id="cmpnTel"
placeholder="Enter tel"
value={formData.cmpnTel ?? ''}
onChange={(e) => handleInputChange('cmpnTel', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="memo">메모</Label>
<textarea
id="memo"
className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
rows={3}
placeholder="Enter memo"
value={formData.memo ?? ''}
onChange={(e) => handleInputChange('memo', e.target.value)}
/>
</div>
</KriDialog>
)
}
export default CmpnUpsertDialog

View File

@@ -2,7 +2,7 @@
import { useEffect, useMemo, useState } from 'react'
import { Plus, X } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
@@ -107,7 +107,7 @@ const ListBatchEditDialog = ({
const handleConfirm = async () => {
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
if (normalized.length === 0) {
alert('일괄 수정할 항목을 입력해 주세요.')
alert('일괄 수정할 항목을 입력해주세요.')
return
}
@@ -121,87 +121,86 @@ const ListBatchEditDialog = ({
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[900px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">일괄 수정</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="rounded-md border px-4 py-3 text-sm">
<p className="font-semibold mb-1">적용된 필터</p>
<p className="text-muted-foreground">
{filterSummary.length > 0 ? filterSummary : '적용된 필터가 없습니다.'}
</p>
</div>
<div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
<span>헤더</span>
<span>수정 값</span>
<span />
</div>
<div className="max-h-72 overflow-auto">
{rows.map((row) => (
<div
key={row.id}
className="h-12 px-4 border-b last:border-b-0 grid grid-cols-[1fr_2fr_64px] items-center gap-2"
>
<Select
value={String(row.headerId)}
onValueChange={(v) => handleChangeHeader(row.id, Number(v))}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="헤더 선택" />
</SelectTrigger>
<SelectContent>
{headerOptions.map((option) => (
<SelectItem key={option.id} value={String(option.id)}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Input
value={row.value}
onChange={(e) => handleChangeValue(row.id, e.target.value)}
placeholder="수정할 값을 입력해 주세요"
/>
<div className="flex justify-center">
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => handleRemoveRow(row.id)}
aria-label="행 제거"
>
<X className="w-4 h-4" />
</Button>
</div>
</div>
))}
</div>
</div>
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
<Plus className="w-4 h-4" />
행 추가
</Button>
</div>
<DialogFooter>
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">일괄 수정</span>}
contentClassName="sm:max-w-[900px]"
bodyClassName="space-y-4"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
적용
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
}
>
<div className="rounded-md border px-4 py-3 text-sm">
<p className="font-semibold mb-1">적용된 필터</p>
<p className="text-muted-foreground">
{filterSummary.length > 0 ? filterSummary : '적용된 필터가 없습니다.'}
</p>
</div>
<div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
<span>헤더</span>
<span>수정 값</span>
<span />
</div>
<div className="max-h-72 overflow-auto">
{rows.map((row) => (
<div
key={row.id}
className="h-12 px-4 border-b last:border-b-0 grid grid-cols-[1fr_2fr_64px] items-center gap-2"
>
<Select
value={String(row.headerId)}
onValueChange={(v) => handleChangeHeader(row.id, Number(v))}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="헤더 선택" />
</SelectTrigger>
<SelectContent>
{headerOptions.map((option) => (
<SelectItem key={option.id} value={String(option.id)}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Input
value={row.value}
onChange={(e) => handleChangeValue(row.id, e.target.value)}
placeholder="수정할 값을 입력해주세요"
/>
<div className="flex justify-center">
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => handleRemoveRow(row.id)}
aria-label="행 제거"
>
<X className="w-4 h-4" />
</Button>
</div>
</div>
))}
</div>
</div>
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
<Plus className="w-4 h-4" />
행 추가
</Button>
</KriDialog>
)
}

View File

@@ -22,15 +22,15 @@ const ApplyFilterOption = ({ value, onValueChange, idPrefix }: ApplyFilterGroupP
>
<div className="flex items-center gap-2">
<RadioGroupItem value="selected" id={`${idPrefix}-selected`} />
<Label htmlFor={`${idPrefix}-selected`}>선택 항목만</Label>
<Label className="text-base" htmlFor={`${idPrefix}-selected`}>선택 항목만</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="filtered" id={`${idPrefix}-filtered`} />
<Label htmlFor={`${idPrefix}-filtered`}>필터 적용 대상만</Label>
<Label className="text-base" htmlFor={`${idPrefix}-filtered`}>필터 적용 대상만</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="all" id={`${idPrefix}-all`} />
<Label htmlFor={`${idPrefix}-all`}>전체 대상</Label>
<Label className="text-base" htmlFor={`${idPrefix}-all`}>전체 대상</Label>
</div>
</RadioGroup>
)

View File

@@ -2,7 +2,7 @@
import { useState } from 'react'
import { Download } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
@@ -57,7 +57,7 @@ const ListDownloadDialog = ({
const hasFrom = contactHistoryDateFrom.length > 0
const hasTo = contactHistoryDateTo.length > 0
if (hasFrom !== hasTo) {
alert('조회 기간은 시작일과 종료일을 모두 입력해 주세요.')
alert('조회 기간은 시작일과 종료일을 모두 입력해주세요.')
return
}
if (hasFrom && hasTo && contactHistoryDateFrom > contactHistoryDateTo) {
@@ -83,51 +83,14 @@ const ListDownloadDialog = ({
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[560px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">{titleMap[mode]}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
{mode === 'contact-history' ? (
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">조회 기간</p>
<KriDateRangePicker
value={{ from: contactHistoryDateFrom, to: contactHistoryDateTo }}
onChange={(range) => {
setContactHistoryDateFrom(range.from)
setContactHistoryDateTo(range.to)
}}
/>
<p className="text-xs text-muted-foreground">비워두면 전체 기간으로 다운로드됩니다.</p>
</div>
) : null}
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">다운로드 범위</p>
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="download-scope-target" />
</div>
{mode === 'contact-history' ? (
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">이력 기준</p>
<RadioGroup
value={contactHistoryType}
onValueChange={(v) => setContactHistoryType(v as ContactHistoryDownloadType)}
className="flex items-center gap-6 flex-wrap"
>
<div className="flex items-center gap-2">
<RadioGroupItem value="all" id="download-contact-history-all" />
<Label htmlFor="download-contact-history-all">전체 이력</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="latest" id="download-contact-history-latest" />
<Label htmlFor="download-contact-history-latest">마지막 이력만</Label>
</div>
</RadioGroup>
</div>
) : null}
</div>
<DialogFooter>
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
contentClassName="sm:max-w-[560px]"
bodyClassName="space-y-4"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
@@ -135,9 +98,46 @@ const ListDownloadDialog = ({
<Download className="w-4 h-4" />
다운로드
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
}
>
{mode === 'contact-history' ? (
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">조회 기간</p>
<KriDateRangePicker
value={{ from: contactHistoryDateFrom, to: contactHistoryDateTo }}
onChange={(range) => {
setContactHistoryDateFrom(range.from)
setContactHistoryDateTo(range.to)
}}
/>
<p className="text-xs text-muted-foreground">비워두면 전체 기간으로 다운로드합니다.</p>
</div>
) : null}
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">다운로드 범위</p>
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="download-scope-target" />
</div>
{mode === 'contact-history' ? (
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">이력 기준</p>
<RadioGroup
value={contactHistoryType}
onValueChange={(v) => setContactHistoryType(v as ContactHistoryDownloadType)}
className="flex items-center gap-6 flex-wrap"
>
<div className="flex items-center gap-2">
<RadioGroupItem value="all" id="download-contact-history-all" />
<Label className="text-base" htmlFor="download-contact-history-all">전체 이력</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="latest" id="download-contact-history-latest" />
<Label className="text-base" htmlFor="download-contact-history-latest">마지막 이력만</Label>
</div>
</RadioGroup>
</div>
) : null}
</KriDialog>
)
}

View File

@@ -2,7 +2,7 @@
import { useEffect, useMemo, useState } from 'react'
import { Plus, X } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
@@ -15,7 +15,7 @@ import {
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
import type { FilterHeaderOption, FilterOperator, FilterRow } from '@/types/list'
import type { FilterHeaderOption, FilterOperator, FilterRow, FilterValueOption } from '@/types/list'
export type ListFilterDialogProps = {
dialogId?: DialogId
@@ -31,12 +31,14 @@ const operatorLabel: Record<FilterOperator, string> = {
neq: '다름',
contains: '포함',
notContains: '포함하지 않음',
empty: '값 없음',
notEmpty: '값 있음',
}
const createFilterRow = (headerId: number): FilterRow => ({
const createFilterRow = (headerId: number, headerOptions: FilterHeaderOption[]): FilterRow => ({
id: crypto.randomUUID(),
headerId,
operator: 'eq',
operator: headerOptions.find((option) => option.id === headerId)?.allowedOperators[0] ?? 'eq',
textValue: '',
multiValues: [],
})
@@ -54,7 +56,7 @@ const ListFilterDialog = ({
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const defaultHeaderId = headerOptions[0]?.id ?? 0
const defaultHeaderId = headerOptions.find((option) => !option.disabled)?.id ?? 0
useEffect(() => {
if (!resolvedOpen) return
@@ -63,9 +65,9 @@ const ListFilterDialog = ({
return
}
if (defaultHeaderId > 0) {
setRows([createFilterRow(defaultHeaderId)])
setRows([createFilterRow(defaultHeaderId, headerOptions)])
}
}, [resolvedOpen, initialRows, defaultHeaderId])
}, [resolvedOpen, initialRows, defaultHeaderId, headerOptions])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
@@ -78,7 +80,7 @@ const ListFilterDialog = ({
const handleAddRow = () => {
if (defaultHeaderId <= 0) return
setRows((prev) => [...prev, createFilterRow(defaultHeaderId)])
setRows((prev) => [...prev, createFilterRow(defaultHeaderId, headerOptions)])
}
const handleRemoveRow = (id: string) => {
@@ -89,16 +91,25 @@ const ListFilterDialog = ({
setRows((prev) => prev.map((row) => (row.id === id ? updater(row) : row)))
}
const getValueOptions = (headerId: number) => {
return headerOptions.find((item) => item.id === headerId)?.values ?? []
}
const getHeaderOption = (headerId: number) => headerOptions.find((item) => item.id === headerId)
const getValueOptions = (headerId: number): FilterValueOption[] => getHeaderOption(headerId)?.valueOptions ?? []
// valueOptions가 undefined면 텍스트 입력 헤더, 빈 배열이면 "목록형인데 현재 선택 가능한 값이 없음"이므로 둘을 구분한다.
const isListValueHeader = (headerId: number) => getHeaderOption(headerId)?.valueOptions !== undefined
const getAllowedOperators = (headerId: number): FilterOperator[] =>
getHeaderOption(headerId)?.allowedOperators ?? ['eq', 'neq', 'contains', 'notContains', 'empty', 'notEmpty']
const isDisabledHeader = (headerId: number) => getHeaderOption(headerId)?.disabled === true
const serializedRows = useMemo(
() =>
rows
.map((row) => {
const hasValueOptions = getValueOptions(row.headerId).length > 0
if (hasValueOptions) return row.multiValues.length > 0 ? row : null
if (isDisabledHeader(row.headerId)) return null
if (row.operator === 'empty' || row.operator === 'notEmpty') return row
if (isListValueHeader(row.headerId)) return row.multiValues.length > 0 ? row : null
return row.textValue.trim().length > 0 ? row : null
})
.filter((row): row is FilterRow => row !== null),
@@ -107,7 +118,7 @@ const ListFilterDialog = ({
const handleConfirm = async () => {
if (serializedRows.length === 0) {
alert('필터 조건을 입력해 주세요.')
alert('필터 조건을 입력해주세요.')
return
}
@@ -121,141 +132,155 @@ const ListFilterDialog = ({
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[940px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">필터</DialogTitle>
</DialogHeader>
<div className="overflow-hidden rounded-md border">
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr_64px] items-center border-b bg-muted/40 px-4 text-sm font-semibold">
<span>헤더</span>
<span>비교 연산자</span>
<span>값</span>
<span />
</div>
<div className="max-h-80 overflow-auto">
{rows.map((row) => {
const valueOptions = getValueOptions(row.headerId)
const listMode = valueOptions.length > 0
return (
<div
key={row.id}
className="grid min-h-12 grid-cols-[1fr_140px_1.4fr_64px] items-center gap-2 border-b px-4 py-2 last:border-b-0"
>
<Select
value={String(row.headerId)}
onValueChange={(value) =>
handleChangeRow(row.id, (current) => ({
...current,
headerId: Number(value),
textValue: '',
multiValues: [],
}))
}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="헤더 선택" />
</SelectTrigger>
<SelectContent>
{headerOptions.map((option) => (
<SelectItem key={option.id} value={String(option.id)}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={row.operator}
onValueChange={(value) =>
handleChangeRow(row.id, (current) => ({
...current,
operator: value as FilterOperator,
textValue: '',
multiValues: [],
}))
}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{(Object.keys(operatorLabel) as FilterOperator[]).map((operator) => (
<SelectItem key={operator} value={operator}>
{operatorLabel[operator]}
</SelectItem>
))}
</SelectContent>
</Select>
{listMode ? (
<KriMultiSelect
items={valueOptions}
value={row.multiValues}
onChange={(values) =>
handleChangeRow(row.id, (current) => ({
...current,
multiValues: values,
}))
}
getValue={(item) => item}
getLabel={(item) => item}
placeholder="값 선택"
widthClassName="w-full"
heightClassName="h-9"
className="w-full"
spanClassName="text-sm"
badgeClassName="text-xs"
maxCount={2}
/>
) : (
<Input
placeholder="검색할 텍스트"
value={row.textValue}
onChange={(event) =>
handleChangeRow(row.id, (current) => ({
...current,
textValue: event.target.value,
}))
}
/>
)}
<div className="flex justify-center">
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => handleRemoveRow(row.id)}
aria-label="조건 제거"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
)
})}
</div>
</div>
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
<Plus className="h-4 w-4" />
조건 추가
</Button>
<DialogFooter>
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">필터</span>}
contentClassName="sm:max-w-[940px]"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
적용
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
}
>
<div className="overflow-hidden rounded-md border">
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr_64px] items-center border-b bg-muted px-4 text-sm font-semibold">
<span>헤더</span>
<span>비교 연산자</span>
<span>값</span>
<span />
</div>
<div className="max-h-80 overflow-auto">
{rows.map((row) => {
const valueOptions = getValueOptions(row.headerId)
const listMode = isListValueHeader(row.headerId)
const disabled = isDisabledHeader(row.headerId)
const rowAllowedOperators = getAllowedOperators(row.headerId)
const isEmptyOperator = row.operator === 'empty' || row.operator === 'notEmpty'
return (
<div
key={row.id}
className="grid min-h-12 grid-cols-[1fr_140px_1.4fr_64px] items-center gap-2 border-b px-4 py-2 last:border-b-0"
>
<Select
value={String(row.headerId)}
disabled={disabled}
onValueChange={(value) => {
const nextHeaderId = Number(value)
const nextAllowedOperators = getAllowedOperators(nextHeaderId)
handleChangeRow(row.id, (current) => ({
...current,
headerId: nextHeaderId,
operator: nextAllowedOperators.includes(current.operator)
? current.operator
: nextAllowedOperators[0] ?? 'eq',
textValue: '',
multiValues: [],
}))
}}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="헤더 선택" />
</SelectTrigger>
<SelectContent>
{headerOptions.map((option) => (
<SelectItem key={option.id} value={String(option.id)} disabled={option.disabled}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={row.operator}
disabled={disabled}
onValueChange={(value) =>
handleChangeRow(row.id, (current) => ({
...current,
operator: value as FilterOperator,
}))
}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{rowAllowedOperators.map((operator) => (
<SelectItem key={operator} value={operator}>
{operatorLabel[operator]}
</SelectItem>
))}
</SelectContent>
</Select>
{isEmptyOperator ? (
<Input placeholder="값을 입력할 필요 없음" value="" disabled />
) : listMode ? (
<KriMultiSelect
items={valueOptions}
value={row.multiValues}
disabled={disabled}
onChange={(values) =>
handleChangeRow(row.id, (current) => ({
...current,
multiValues: values,
}))
}
getValue={(item) => item.value}
getLabel={(item) => item.label}
placeholder="값 선택"
widthClassName="w-full"
heightClassName="h-9"
className="w-full"
spanClassName="text-sm"
badgeClassName="text-xs"
maxCount={2}
/>
) : (
<Input
placeholder="검색할 텍스트"
value={row.textValue}
disabled={disabled}
onChange={(event) =>
handleChangeRow(row.id, (current) => ({
...current,
textValue: event.target.value,
}))
}
/>
)}
<div className="flex justify-center">
<Button
type="button"
variant="ghost"
size="icon-sm"
disabled={disabled}
onClick={() => handleRemoveRow(row.id)}
aria-label="조건 제거"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
)
})}
</div>
</div>
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2" disabled={defaultHeaderId <= 0}>
<Plus className="h-4 w-4" />
조건 추가
</Button>
</KriDialog>
)
}

View File

@@ -20,7 +20,7 @@ import {
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { GripVertical, Plus, Trash2 } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
@@ -35,6 +35,7 @@ export type ListHeaderManageDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
prjctIdx: number
rows: listHeader[]
onConfirm: (rows: listHeader[]) => void | Promise<void>
}
@@ -76,7 +77,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
style={style}
className={cn(
'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2',
(activeId === row.listHderId || isDragging) && 'bg-muted/40',
(activeId === row.listHderId || isDragging) && 'bg-muted',
)}
>
<div className="flex items-center">
@@ -173,6 +174,7 @@ const ListHeaderManageDialog = ({
dialogId = 'listHeaderManageDialog',
open,
onOpenChange,
prjctIdx,
rows,
onConfirm,
}: ListHeaderManageDialogProps) => {
@@ -275,6 +277,7 @@ const ListHeaderManageDialog = ({
const newIndex = prev.filter((row) => row.listHderNm.startsWith('신규 헤더')).length + 1
const nextRow: listHeader = {
prjctIdx,
listHderId: nextId,
listHderOrder: prev.length + 1,
listHderGrad: ListHeaderGrade.COMMON,
@@ -295,6 +298,7 @@ const ListHeaderManageDialog = ({
try {
const orderedRows = localRows.map((row, index) => ({
...row,
prjctIdx: row.prjctIdx ?? prjctIdx,
listHderOrder: index + 1,
}))
await onConfirm(orderedRows)
@@ -305,13 +309,24 @@ const ListHeaderManageDialog = ({
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[1200px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">리스트 헤더 관리</DialogTitle>
</DialogHeader>
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">리스트 헤더 관리</span>}
contentClassName="sm:max-w-[1200px]"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
저장
</Button>
</>
}
>
<div className="flex justify-end">
<div className="flex justify-end mb-2">
<Button type="button" className="gap-2 bg-blue" onClick={handleAddHeader} disabled={submitting}>
<Plus className="w-4 h-4" />
헤더 추가
@@ -319,7 +334,7 @@ const ListHeaderManageDialog = ({
</div>
<div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
<span>순서</span>
<span>헤더명</span>
<span>헤더 타입</span>
@@ -355,16 +370,7 @@ const ListHeaderManageDialog = ({
</DndContext>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
저장
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</KriDialog>
)
}

View File

@@ -1,7 +1,7 @@
'use client'
import { useState } from 'react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
@@ -50,47 +50,46 @@ const ListResetDialog = ({
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[700px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">리스트 초기화</DialogTitle>
</DialogHeader>
<div className="space-y-6 py-2">
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
<ApplyFilterOption
value={target}
onValueChange={(v) => setTarget(v)}
idPrefix="list-reset-target"
/>
</div>
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold text-red-600">초기화 범위</p>
<RadioGroup value={scope} onValueChange={(v) => setScope(v as ListResetScope)} className="space-y-2">
<div className="flex items-center gap-2">
<RadioGroupItem value="result-and-history" id="list-reset-scope-result-history" />
<Label htmlFor="list-reset-scope-result-history">결과 + 이력 삭제</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="list-only" id="list-reset-scope-list-only" />
<Label htmlFor="list-reset-scope-list-only">결과 + 이력 + 리스트 삭제</Label>
</div>
</RadioGroup>
</div>
</div>
<DialogFooter>
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">리스트 초기화</span>}
contentClassName="sm:max-w-[700px]"
bodyClassName="space-y-6 py-2"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting}>
초기화
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
}
>
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
<ApplyFilterOption
value={target}
onValueChange={(v) => setTarget(v)}
idPrefix="list-reset-target"
/>
</div>
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold text-red-600">초기화 범위</p>
<RadioGroup value={scope} onValueChange={(v) => setScope(v as ListResetScope)} className="space-y-2">
<div className="flex items-center gap-2">
<RadioGroupItem value="result-and-history" id="list-reset-scope-result-history" />
<Label className="text-base" htmlFor="list-reset-scope-result-history">결과 + 이력 삭제</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="list-only" id="list-reset-scope-list-only" />
<Label className="text-base" htmlFor="list-reset-scope-list-only">결과 + 이력 + 리스트 삭제</Label>
</div>
</RadioGroup>
</div>
</KriDialog>
)
}

View File

@@ -2,10 +2,11 @@
import { useMemo, useRef, useState } from 'react'
import { ChevronDown, ChevronUp, Download, Upload, X } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { KriSelect, KriSelectItem } from '@/components/common/KriSelect'
import { useDialog } from '@/hooks/useDialog'
@@ -32,6 +33,7 @@ export type ListUploadDialogProps = {
}
const ACCEPT_EXTENSIONS = ['.xlsx', '.xls', '.csv']
const FIXED_UPLOAD_MODE = ListUploadMode.ADD_AND_CHANGE
const ListUploadDialog = ({
dialogId = 'listUploadDialog',
@@ -50,7 +52,8 @@ const ListUploadDialog = ({
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [excelHeaders, setExcelHeaders] = useState<string[]>([])
const [otherHeaderTypeMap, setOtherHeaderTypeMap] = useState<Record<number, ListHeaderType>>({})
const [uploadMode, setUploadMode] = useState<ListUploadMode>(ListUploadMode.CHANGE)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [uploadMode, setUploadMode] = useState<ListUploadMode>(ListUploadMode.ADD_AND_CHANGE)
const [submitting, setSubmitting] = useState(false)
const [historyExpanded, setHistoryExpanded] = useState(false)
const [validation, setValidation] = useState<ValidationOption>({
@@ -91,7 +94,7 @@ const ListUploadDialog = ({
setSelectedFile(null)
setExcelHeaders([])
setOtherHeaderTypeMap({})
setUploadMode(ListUploadMode.ADD)
setUploadMode(ListUploadMode.ADD_AND_CHANGE)
setSubmitting(false)
setHistoryExpanded(false)
setValidation({
@@ -115,10 +118,19 @@ const ListUploadDialog = ({
handleOpenChange(nextOpen)
}
const decodeCsvText = (buffer: ArrayBuffer) => {
// 한국 Windows 엑셀에서 저장한 CSV는 UTF-8이 아니라 EUC-KR(CP949)인 경우가 많다.
try {
return new TextDecoder('utf-8', { fatal: true }).decode(buffer)
} catch {
return new TextDecoder('euc-kr').decode(buffer)
}
}
const extractHeaders = async (file: File) => {
const lower = file.name.toLowerCase()
if (lower.endsWith('.csv')) {
const text = await file.text()
const text = decodeCsvText(await file.arrayBuffer())
const firstLine = text.split(/\r?\n/)[0] ?? ''
return firstLine.split(',').map((s) => s.trim()).filter((s) => s.length > 0)
}
@@ -170,7 +182,7 @@ const ListUploadDialog = ({
)
await onUpload(selectedFile, {
uploadMode,
uploadMode: FIXED_UPLOAD_MODE,
checkDuplicateEmail: validation.checkEmailDuplicate,
checkDuplicatePhone: validation.checkPhoneDuplicate,
...(Object.keys(specificHeader).length > 0 ? { specificHeader } : {}),
@@ -235,168 +247,167 @@ const ListUploadDialog = ({
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
<DialogContent className="overflow-hidden" style={{ width: 'min(960px, 95vw)', maxWidth: '95vw' }}>
<DialogHeader>
<DialogTitle className="text-2xl font-bold">리스트 업로드</DialogTitle>
</DialogHeader>
<div className="min-w-0 space-y-6 py-2">
{
/*
<div className="space-y-3">
<Label className="text-lg font-semibold">업로드 방식</Label>
<RadioGroup
value={String(uploadMode)}
onValueChange={(value) => setUploadMode(Number(value) as ListUploadMode)}
className="flex flex-wrap items-center gap-6"
>
<div className="flex items-center gap-2">
<RadioGroupItem value={String(ListUploadMode.CHANGE)} id="list-upload-mode-change" />
<Label htmlFor="list-upload-mode-change" className="cursor-pointer">
전체 교체
</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value={String(ListUploadMode.ADD)} id="list-upload-mode-add" />
<Label htmlFor="list-upload-mode-add" className="cursor-pointer">
추가
</Label>
</div>
</RadioGroup>
</div>
*/
}
<div className="space-y-3">
<Label className="text-lg font-semibold">업로드 파일</Label>
<div className="min-w-0 flex items-center gap-2">
<Button type="button" className="shrink-0 bg-excel text-base" onClick={onDownloadTemplate}>
<Download className="w-4 h-4" />
양식 다운로드
</Button>
<Button
type="button"
variant="outline"
className="min-w-0 flex-1 justify-start text-lg"
disabled={submitting}
onClick={() => fileInputRef.current?.click()}
>
<Upload className="w-4 h-4 shrink-0" />
<span className="min-w-0 truncate">{selectedFile ? selectedFile.name : '업로드 파일을 선택해 주세요.'}</span>
</Button>
<Button type="button" variant="ghost" size="icon-sm" disabled={!selectedFile || submitting} onClick={resetState} aria-label="선택 파일 제거">
<X className="w-4 h-4" />
</Button>
<input ref={fileInputRef} type="file" accept={ACCEPT_EXTENSIONS.join(',')} className="hidden" onChange={handleSelectFile} />
</div>
</div>
{selectedFile && excelHeaders.length > 0 && compareRows.length > 0 && (
<div className="min-w-0 space-y-3">
<Label className="text-lg font-semibold">헤더 비교</Label>
<div className="block w-full max-w-full overflow-x-scroll rounded-md border pb-1">
<div className="w-max whitespace-nowrap">
{headerCompareList.map(({ header, index, isMatched, isSettingRequired, serverHeader }) => {
return (
<div key={`${header}-${index}`} className="inline-block w-[125px] align-top border-r last:border-r-0">
<div className="flex h-8 items-center truncate bg-slate-700 px-2.5 text-sm font-medium text-slate-50">
{header || `컬럼${index + 1}`}
</div>
<div className="flex h-9 items-center border-t px-2">
{renderHeaderTypeCell(serverHeader, isMatched, isSettingRequired, index)}
</div>
</div>
)
})}
</div>
</div>
</div>
)}
<div className="space-y-3">
<Label className="text-lg font-semibold">중복 검증</Label>
<div className="flex items-center gap-6">
<div className="flex items-center gap-2">
<Checkbox
id="list-upload-email-dup"
checked={validation.checkEmailDuplicate}
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkEmailDuplicate: checked === true }))}
/>
<Label htmlFor="list-upload-email-dup" className="cursor-pointer">
이메일 중복검증
</Label>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="list-upload-phone-dup"
checked={validation.checkPhoneDuplicate}
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkPhoneDuplicate: checked === true }))}
/>
<Label htmlFor="list-upload-phone-dup" className="cursor-pointer">
전화번호 중복검증
</Label>
</div>
</div>
</div>
<div className="rounded-md border">
<button type="button" className="flex h-11 w-full items-center justify-between border-b px-4 text-left" onClick={() => setHistoryExpanded((prev) => !prev)}>
<span className="text-lg font-semibold">업로드 이력({normalizedHistory.length} 회)</span>
{historyExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
</button>
{historyExpanded && (
<div className="h-[160px] overflow-y-auto">
<table className="w-full text-base">
<thead className="sticky top-0 border-b bg-white">
<tr>
<th className="h-9 px-3 text-center">회차</th>
<th className="h-9 px-3 text-center">파일명</th>
<th className="h-9 px-3 text-center">사용자 ID</th>
<th className="h-9 px-3 text-center">업로드 건수</th>
<th className="h-9 px-3 text-center">업로드 일시</th>
<th className="h-9 px-3 text-center">다운로드</th>
</tr>
</thead>
<tbody>
{normalizedHistory.length === 0 && (
<tr>
<td className="h-12 px-3 text-center text-muted-foreground" colSpan={6}>
업로드 이력이 없습니다.
</td>
</tr>
)}
{normalizedHistory.map((item) => (
<tr key={item.listUploadLogId} className="border-b last:border-b-0">
<td className="h-10 px-3 text-center">{item.wave}</td>
<td className="h-10 px-3 text-center">{item.fileName}</td>
<td className="h-10 px-3 text-center">{item.regUser}</td>
<td className="h-10 px-3 text-center">{item.listCount.toLocaleString()}</td>
<td className="h-10 px-3 text-center">{item.uploadAtLabel}</td>
<td className="h-10 px-3 text-center">
<Button type="button" size="sm" className="bg-excel" onClick={() => onDownloadHistory?.(item)}>
<Download className="h-4 w-4" />
다운로드
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
<DialogFooter>
<KriDialog
open={resolvedOpen}
onOpenChange={handleDialogOpenChange}
title={<span className="text-2xl font-bold">리스트 업로드</span>}
contentClassName="w-[min(960px,95vw)] max-w-[95vw] sm:max-w-[min(960px,95vw)] overflow-hidden"
bodyClassName="min-w-0 space-y-6 py-2"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleDialogOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch}>
{submitting ? '업로드 중...' : '업로드'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
}
>
{
/*
<div className="space-y-3">
<Label className="text-lg font-semibold">업로드 방식</Label>
<RadioGroup
value={String(uploadMode)}
onValueChange={(value) => setUploadMode(Number(value) as ListUploadMode)}
className="flex flex-wrap items-center gap-6"
>
<div className="flex items-center gap-2">
<RadioGroupItem value={String(ListUploadMode.CHANGE)} id="list-upload-mode-change" />
<Label htmlFor="list-upload-mode-change" className="cursor-pointer">
전체 교체
</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value={String(ListUploadMode.ADD)} id="list-upload-mode-add" />
<Label htmlFor="list-upload-mode-add" className="cursor-pointer">
추가
</Label>
</div>
</RadioGroup>
</div>
*/
}
<div className="space-y-3">
<Label className="text-lg font-semibold">업로드 파일</Label>
<div className="min-w-0 flex items-center gap-2">
<Button type="button" className="shrink-0 bg-excel text-base" onClick={onDownloadTemplate}>
<Download className="w-4 h-4" />
양식 다운로드
</Button>
<Button
type="button"
variant="outline"
className="min-w-0 flex-1 justify-start text-lg"
disabled={submitting}
onClick={() => fileInputRef.current?.click()}
>
<Upload className="w-4 h-4 shrink-0" />
<span className="min-w-0 truncate text-sm">{selectedFile ? selectedFile.name : '업로드 파일을 선택해 주세요.'}</span>
</Button>
<Button type="button" variant="ghost" size="icon-sm" disabled={!selectedFile || submitting} onClick={resetState} aria-label="선택 파일 제거">
<X className="w-4 h-4" />
</Button>
<input ref={fileInputRef} type="file" accept={ACCEPT_EXTENSIONS.join(',')} className="hidden" onChange={handleSelectFile} />
</div>
</div>
{selectedFile && excelHeaders.length > 0 && compareRows.length > 0 && (
<div className="min-w-0 space-y-3">
<Label className="text-lg font-semibold">헤더 비교</Label>
<div className="block w-full max-w-full overflow-x-scroll rounded-md border pb-1">
<div className="w-max whitespace-nowrap">
{headerCompareList.map(({ header, index, isMatched, isSettingRequired, serverHeader }) => {
return (
<div key={`${header}-${index}`} className="inline-block w-[125px] align-top border-r last:border-r-0">
<div className="flex h-8 items-center truncate bg-slate-700 px-2.5 text-sm font-medium text-slate-50">
{header || `컬럼${index + 1}`}
</div>
<div className="flex h-9 items-center border-t px-2">
{renderHeaderTypeCell(serverHeader, isMatched, isSettingRequired, index)}
</div>
</div>
)
})}
</div>
</div>
</div>
)}
<div className="space-y-3">
<Label className="text-lg font-semibold">중복 검증</Label>
<div className="flex items-center gap-6">
<div className="flex items-center gap-2">
<Checkbox
id="list-upload-email-dup"
checked={validation.checkEmailDuplicate}
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkEmailDuplicate: checked === true }))}
/>
<Label htmlFor="list-upload-email-dup" className="cursor-pointer text-base">
이메일 중복검증
</Label>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="list-upload-phone-dup"
checked={validation.checkPhoneDuplicate}
onCheckedChange={(checked) => setValidation((prev) => ({ ...prev, checkPhoneDuplicate: checked === true }))}
/>
<Label htmlFor="list-upload-phone-dup" className="cursor-pointer text-base">
전화번호 중복검증
</Label>
</div>
</div>
</div>
<div className="rounded-md border">
<button type="button" className="flex h-11 w-full items-center justify-between border-b px-4 text-left" onClick={() => setHistoryExpanded((prev) => !prev)}>
<span className="text-lg font-semibold">업로드 이력({normalizedHistory.length} 회)</span>
{historyExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
</button>
{historyExpanded && (
<div className="h-[160px] overflow-y-auto">
<table className="w-full text-base">
<thead className="sticky top-0 border-b bg-white">
<tr>
<th className="h-9 px-3 text-center">회차</th>
<th className="h-9 px-3 text-center">파일명</th>
<th className="h-9 px-3 text-center">사용자 ID</th>
<th className="h-9 px-3 text-center">업로드 건수</th>
<th className="h-9 px-3 text-center">업로드 일시</th>
<th className="h-9 px-3 text-center">다운로드</th>
</tr>
</thead>
<tbody>
{normalizedHistory.length === 0 && (
<tr>
<td className="h-12 px-3 text-center text-muted-foreground" colSpan={6}>
업로드 이력이 없습니다.
</td>
</tr>
)}
{normalizedHistory.map((item) => (
<tr key={item.listUploadLogId} className="border-b last:border-b-0">
<td className="h-10 px-3 text-center">{item.wave}</td>
<td className="h-10 px-3 text-center">{item.fileName}</td>
<td className="h-10 px-3 text-center">{item.regUser}</td>
<td className="h-10 px-3 text-center">{item.listCount.toLocaleString()}</td>
<td className="h-10 px-3 text-center">{item.uploadAtLabel}</td>
<td className="h-10 px-3 text-center">
<Button type="button" size="sm" className="bg-excel" onClick={() => onDownloadHistory?.(item)}>
<Download className="h-4 w-4" />
다운로드
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</KriDialog>
)
}

View File

@@ -1,39 +1,28 @@
'use client'
import { useMemo, useState } from 'react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { DataTable } from '@/components/data-table/DataTable'
import type { DataTableColumn } from '@/components/data-table/DataTable.type'
import { useDialog } from '@/hooks/useDialog'
import { useSelectedProject } from '@/hooks/useSelectedProject'
import { useBulkSendDetailExcelMutation, useBulkSendDetailQuery, useBulkSendListQuery } from '@/query/message'
import { MessageType } from '@kri/common/noti-hub'
import { downloadBase64File, XLSX_MIME_TYPE } from '@kri/common/browser'
import { formatKst } from '@kri/common'
import type { PaginationState } from '@tanstack/react-table'
import type { DialogId } from '@/store/jotai/dialog'
import type { BulkSendInfo } from '@kri/common/noti-hub'
import type { SendResultInfo } from '@/types/message'
import {clientEnv} from "@/lib/env.client";
export type MessageHistoryType = 'sms' | 'email'
export type MessageHistoryDetailType = 'template' | 'target' | 'success' | 'fail' | null
export type MessageHistoryRow = {
id: number
type: MessageHistoryType
title: string
templateName: string
sendInfo: string
targetHeader: string
targetCount: number
successCount: number
failCount: number
createdAt: string
sendAt: string
status: string
templatePreview?: string
targetPreview?: string[]
successPreview?: string[]
failPreview?: string[]
}
export type MessageHistoryDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
rows: MessageHistoryRow[]
onDownload?: (row: MessageHistoryRow, detailType: Exclude<MessageHistoryDetailType, null>) => void | Promise<void>
}
const tabLabelMap: Record<MessageHistoryType, string> = {
@@ -41,26 +30,64 @@ const tabLabelMap: Record<MessageHistoryType, string> = {
email: '이메일',
}
const historyColumns: DataTableColumn<BulkSendInfo>[] = [
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
{ id: 'resve', header: '구분', accessorFn: (row) => (row.resve ? '예약' : '즉시') },
{ id: 'trgtCnt', header: '대상수', accessorFn: (row) => row.trgtCnt.toLocaleString() },
{ id: 'sendCnt', header: '발송수', accessorFn: (row) => row.sendCnt.toLocaleString() },
{ id: 'succesCnt', header: '성공', accessorFn: (row) => row.succesCnt.toLocaleString() },
{ id: 'failCnt', header: '실패', accessorFn: (row) => row.failCnt.toLocaleString() },
{ id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') },
{ id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' },
]
const detailColumns: DataTableColumn<SendResultInfo>[] = [
{ id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || row.destTel || '-' },
{ id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' },
{ id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || row.sendTel || '-' },
{ id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) },
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
]
const MessageHistoryDialog = ({
dialogId = 'messageHistoryDialog',
open,
onOpenChange,
rows,
onDownload,
}: MessageHistoryDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const { selectedProject } = useSelectedProject()
const [tab, setTab] = useState<MessageHistoryType>('sms')
const [selectedId, setSelectedId] = useState<number | null>(null)
const [detailType, setDetailType] = useState<MessageHistoryDetailType>(null)
const [selectedKey, setSelectedKey] = useState<string | null>(null)
const [detailPagination, setDetailPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 })
const resolvedOpen = open ?? isDialogOpen(dialogId)
const prjctCd = selectedProject?.prjctCd ?? ''
const enabled = resolvedOpen && !!prjctCd
const visibleRows = useMemo(() => rows.filter((row) => row.type === tab), [rows, tab])
const emailListQuery = useBulkSendListQuery(MessageType.EMAIL, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'email')
const smsListQuery = useBulkSendListQuery(MessageType.SMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
const lmsListQuery = useBulkSendListQuery(MessageType.LMS_MMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
const selectedRow = useMemo(
() => visibleRows.find((row) => row.id === selectedId) ?? null,
[visibleRows, selectedId],
const visibleRows = useMemo(() => {
if (tab === 'email') return emailListQuery.data ?? []
return [...(smsListQuery.data ?? []), ...(lmsListQuery.data ?? [])].sort((a, b) =>
(b.regDt ?? '').localeCompare(a.regDt ?? ''),
)
}, [tab, emailListQuery.data, smsListQuery.data, lmsListQuery.data])
const detailQuery = useBulkSendDetailQuery(
selectedKey ?? '',
{
pageIndex: detailPagination.pageIndex,
pageSize: detailPagination.pageSize,
sortBy: 'regDt',
sortDir: 'desc',
},
enabled && !!selectedKey,
)
const detailExcelMutation = useBulkSendDetailExcelMutation()
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
@@ -69,142 +96,85 @@ const MessageHistoryDialog = ({
return
}
hideDialog(dialogId)
setSelectedId(null)
setDetailType(null)
setSelectedKey(null)
}
const handlePickDetail = (rowId: number, nextType: Exclude<MessageHistoryDetailType, null>) => {
setSelectedId(rowId)
setDetailType(nextType)
const handleSelectTab = (nextTab: MessageHistoryType) => {
setTab(nextTab)
setSelectedKey(null)
}
const detailContent = useMemo(() => {
if (!selectedRow || !detailType) return null
if (detailType === 'template') return selectedRow.templatePreview ?? '(미리보기 데이터 없음)'
if (detailType === 'target') return (selectedRow.targetPreview ?? []).join('\n')
if (detailType === 'success') return (selectedRow.successPreview ?? []).join('\n')
if (detailType === 'fail') return (selectedRow.failPreview ?? []).join('\n')
return null
}, [selectedRow, detailType])
const handleSelectRow = (row: BulkSendInfo) => {
setSelectedKey(row.bulkSendKey)
setDetailPagination({ pageIndex: 0, pageSize: 10 })
}
const handleDownloadDetail = async () => {
if (!selectedKey) return
const result = await detailExcelMutation.mutateAsync(selectedKey)
if (!result.fileBase64) {
alert('다운로드할 데이터가 없습니다.')
return
}
downloadBase64File(result.fileBase64, result.fileName, XLSX_MIME_TYPE)
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[1200px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">발송 이력</DialogTitle>
</DialogHeader>
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">발송 이력</span>}
contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto"
closeLabel="닫기"
bodyClassName="space-y-4"
>
<div className="flex gap-2">
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => handleSelectTab('sms')}>
{tabLabelMap.sms}
</Button>
<Button type="button" variant={tab === 'email' ? 'default' : 'outline'} onClick={() => handleSelectTab('email')}>
{tabLabelMap.email}
</Button>
</div>
<div className="flex gap-2">
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => setTab('sms')}>
{tabLabelMap.sms}
</Button>
<Button type="button" variant={tab === 'email' ? 'default' : 'outline'} onClick={() => setTab('email')}>
{tabLabelMap.email}
</Button>
</div>
<div className="rounded-md border overflow-hidden">
<DataTable<BulkSendInfo>
columns={historyColumns}
data={visibleRows}
getRowId={(row) => row.bulkSendKey}
isClient
selectMode="click-event"
onRowClick={handleSelectRow}
highlightRowIds={selectedKey ? [selectedKey] : []}
emptyText="발송 이력이 없습니다."
pageSizeOptions={[5, 10, 20]}
defaultPageSize={5}
/>
</div>
<div className="grid grid-cols-1 xl:grid-cols-[1.7fr_1fr] gap-4">
<div className="rounded-md border overflow-auto">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-white border-b">
<tr>
<th className="px-2 h-9 text-left">회차</th>
<th className="px-2 h-9 text-left">제목</th>
<th className="px-2 h-9 text-left">템플릿</th>
<th className="px-2 h-9 text-left">발송 정보</th>
<th className="px-2 h-9 text-left">타겟 헤더</th>
<th className="px-2 h-9 text-right">대상수</th>
<th className="px-2 h-9 text-right">성공</th>
<th className="px-2 h-9 text-right">실패</th>
<th className="px-2 h-9 text-left">등록 일시</th>
<th className="px-2 h-9 text-left">발송 일시</th>
<th className="px-2 h-9 text-left">상태</th>
</tr>
</thead>
<tbody>
{visibleRows.length === 0 && (
<tr>
<td colSpan={11} className="h-12 text-center text-muted-foreground">
발송 이력이 없습니다.
</td>
</tr>
)}
{visibleRows.map((row) => (
<tr key={`${row.type}-${row.id}`} className="border-b last:border-b-0">
<td className="px-2 h-10">{row.id}</td>
<td className="px-2 h-10">{row.title}</td>
<td className="px-2 h-10">
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'template')}>
{row.templateName}
</button>
</td>
<td className="px-2 h-10">{row.sendInfo}</td>
<td className="px-2 h-10">
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'target')}>
{row.targetHeader}
</button>
</td>
<td className="px-2 h-10 text-right">{row.targetCount}</td>
<td className="px-2 h-10 text-right">
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'success')}>
{row.successCount}
</button>
</td>
<td className="px-2 h-10 text-right">
<button type="button" className="underline" onClick={() => handlePickDetail(row.id, 'fail')}>
{row.failCount}
</button>
</td>
<td className="px-2 h-10">{row.createdAt}</td>
<td className="px-2 h-10">{row.sendAt}</td>
<td className="px-2 h-10">{row.status}</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="rounded-md border p-4 space-y-3 min-h-80">
<p className="text-lg font-semibold">
{detailType === null && '상세 이력'}
{detailType === 'template' && '미리보기'}
{detailType === 'target' && '수신 대상'}
{detailType === 'success' && '성공 이력'}
{detailType === 'fail' && '실패 이력'}
</p>
{detailType === null && (
<p className="text-sm text-muted-foreground">
템플릿, 대상수, 성공, 실패 항목을 선택하면 상세 영역이 열립니다.
</p>
)}
{detailType !== null && (
<>
<pre className="rounded border p-3 text-sm whitespace-pre-wrap min-h-56">{detailContent}</pre>
<Button
type="button"
variant="outline"
onClick={() => {
if (!selectedRow || !detailType) return
onDownload?.(selectedRow, detailType)
}}
disabled={!selectedRow || !detailType || !onDownload}
>
다운로드
</Button>
</>
)}
{selectedKey && (
<div className="rounded-md border p-4 space-y-3">
<div className="flex items-center justify-between">
<p className="text-lg font-semibold">상세 이력</p>
<Button type="button" variant="outline" onClick={handleDownloadDetail} disabled={detailExcelMutation.isPending}>
다운로드
</Button>
</div>
<DataTable<SendResultInfo>
columns={detailColumns}
data={detailQuery.data?.content ?? []}
getRowId={(row) => row.cmid}
isClient={false}
pageCount={detailQuery.data?.totalPages ?? 0}
totalCount={detailQuery.data?.totalElements ?? 0}
pagination={detailPagination}
onPaginationChange={setDetailPagination}
emptyText="상세 이력이 없습니다."
pageSizeOptions={[10, 20, 30]}
/>
</div>
<DialogFooter>
<Button type="button" onClick={() => handleOpenChange(false)}>
닫기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
</KriDialog>
)
}

View File

@@ -1,60 +1,54 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useEffect, useMemo, useRef, useState } from 'react'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import { useDialog } from '@/hooks/useDialog'
import { useAuth } from '@/hooks/useAuth'
import { useSelectedProject } from '@/hooks/useSelectedProject'
import { useListSearchQuery } from '@/query/list'
import {
useCreateBulkSendKeyMutation,
useMainTemplateIdxQuery,
useSendBulkMutation,
useTemplateListQuery,
useTemplateQuery,
} from '@/query/message'
import {ChannelType, type DestInfo, TemplateSms, type TemplateSummary} from '@kri/common/noti-hub'
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
import { cn } from '@/lib/utils'
import { getNearestFutureDateTime } from '@/lib/datetime'
import type { DialogId } from '@/store/jotai/dialog'
import { createEmptyListFilter, type ListFilter, type ListFilterTarget, type listHeader } from '@/types/list'
import { ListHeaderConst } from '@/const/listConst'
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
import ApplyFilterOption from './ListDialogOption/ApplyFilterOption'
import {KriEditor} from "@/components/kri-editor";
import {clientEnv} from "@/lib/env.client";
export type MessageSendMode = 'email' | 'sms'
export type ScheduleType = 'instant' | 'reserve'
export type MessageTemplateOption = {
id: string
name: string
title: string
body: string
}
const MAX_TARGET_COUNT = 5000
export type MessageSendHeaderOption = {
id: number
label: string
}
export type MessageSendPayload = {
mode: MessageSendMode
templateId: string
senderEmail: string
senderName: string
senderNumber: string
title: string
body: string
scheduleType: ScheduleType
reserveAt?: string
targetHeaderId: number
}
const toTargetRow = (row: ListTableRow): { sid: string; itemList: Record<number, string> } => ({
sid: String(row.sid ?? ''),
itemList: (row.itemList as Record<number, string> | undefined) ?? {},
})
export type MessageSendDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
mode: MessageSendMode
templateOptions: MessageTemplateOption[]
targetHeaderOptions: MessageSendHeaderOption[]
defaultSenderEmail?: string
defaultSenderName?: string
defaultSenderNumber?: string
onConfirm: (payload: MessageSendPayload) => void | Promise<void>
listHeaders: listHeader[]
currentFilter: ListFilter
selectedRows: ListTableRow[]
onSent?: () => void
}
const titleMap: Record<MessageSendMode, string> = {
@@ -67,45 +61,105 @@ const MessageSendDialog = ({
open,
onOpenChange,
mode,
templateOptions,
targetHeaderOptions,
defaultSenderEmail = '',
defaultSenderName = '',
defaultSenderNumber = '',
onConfirm,
listHeaders,
currentFilter,
selectedRows,
onSent,
}: MessageSendDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [templateId, setTemplateId] = useState('')
const [title, setTitle] = useState('')
const [body, setBody] = useState('')
const [senderEmail, setSenderEmail] = useState(defaultSenderEmail)
const [senderName, setSenderName] = useState(defaultSenderName)
const [senderNumber, setSenderNumber] = useState(defaultSenderNumber)
const [scheduleType, setScheduleType] = useState<ScheduleType>('instant')
const { auth } = useAuth()
const { selectedProject } = useSelectedProject()
const chnnlTy = mode === 'email' ? ChannelType.EMAIL : ChannelType.SMS
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
const [senderEmail, setSenderEmail] = useState('')
const [senderName, setSenderName] = useState('')
const [senderNumber, setSenderNumber] = useState('')
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
const [reserveAt, setReserveAt] = useState('')
const [targetHeaderId, setTargetHeaderId] = useState<number>(targetHeaderOptions[0]?.id ?? 0)
const [targetHeaderId, setTargetHeaderId] = useState<number | null>(null)
const [target, setTarget] = useState<ListFilterTarget>('selected')
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const selectedTemplate = useMemo(
() => templateOptions.find((template) => template.id === templateId),
[templateId, templateOptions],
const prjctIdx = selectedProject?.prjctIdx ?? 0
const prjctCd = selectedProject?.prjctCd ?? ''
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? ''
const enabled = resolvedOpen && !!selectedProject && prjctIdx > 0
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled)
const templateList: TemplateSummary[] = templateListQuery.data ?? []
const templateDetailQuery = useTemplateQuery(templateIdx ?? 0, enabled && !!templateIdx)
const selectedTemplate = templateDetailQuery.data ?? null
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
const mainTemplateIdx = mainTemplateQuery.data ?? null
const headerType = mode === 'email' ? ListHeaderConst.EMAIL : ListHeaderConst.TEL_NUM
const targetHeaderOptions = useMemo(
() => listHeaders.filter((header) => header.listHderTy === headerType),
[listHeaders, headerType],
)
// '전체'/'필터 적용 대상'은 현재 페이지에 보이는 행을 넘어설 수 있어 별도로 넓게 조회한다
const bulkTargetFilter = target === 'all' ? createEmptyListFilter() : currentFilter
const bulkTargetEnabled = enabled && target !== 'selected'
const bulkTargetQuery = useListSearchQuery(
prjctIdx,
{
listFilter: bulkTargetFilter,
pageRequest: { pageIndex: 0, pageSize: MAX_TARGET_COUNT, sortBy: 'sid', sortDir: 'asc' },
},
bulkTargetEnabled,
)
const targetRows = useMemo(() => {
const rows = target === 'selected' ? selectedRows : (bulkTargetQuery.data?.content ?? [])
return rows.map(toTargetRow)
}, [target, selectedRows, bulkTargetQuery.data])
const targetTotalCount = target === 'selected' ? selectedRows.length : (bulkTargetQuery.data?.totalElements ?? 0)
const isTargetTruncated = target !== 'selected' && targetTotalCount > MAX_TARGET_COUNT
const createBulkKeyMutation = useCreateBulkSendKeyMutation(mode)
const sendBulkMutation = useSendBulkMutation(mode)
const mainTemplateAppliedRef = useRef(false)
useEffect(() => {
if (!resolvedOpen) return
const firstTemplate = templateOptions[0]
setTemplateId(firstTemplate?.id ?? '')
setTitle(firstTemplate?.title ?? '')
setBody(firstTemplate?.body ?? '')
setTemplateIdx(null)
setSenderEmail('')
setSenderName('')
setSenderNumber('')
setScheduleType('instant')
setReserveAt('')
setTargetHeaderId(targetHeaderOptions[0]?.id ?? 0)
setSenderEmail(defaultSenderEmail)
setSenderName(defaultSenderName)
setSenderNumber(defaultSenderNumber)
}, [resolvedOpen, templateOptions, targetHeaderOptions, defaultSenderEmail, defaultSenderName, defaultSenderNumber])
setTarget('selected')
setTargetHeaderId(null)
mainTemplateAppliedRef.current = false
}, [resolvedOpen])
// 대표 템플릿이 있으면 최초 1회 자동 선택
useEffect(() => {
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return
mainTemplateAppliedRef.current = true
if (mainTemplateIdx) setTemplateIdx(mainTemplateIdx)
}, [enabled, mainTemplateQuery.isSuccess, mainTemplateIdx])
// 템플릿 상세가 도착하면 발신 정보를 세팅한다 (발송 전 수정 가능)
useEffect(() => {
if (!selectedTemplate) return
setSenderName(selectedTemplate.sendNm)
if ('sendEml' in selectedTemplate) setSenderEmail(selectedTemplate.sendEml)
if ('sendTel' in selectedTemplate) setSenderNumber(selectedTemplate.sendTel)
}, [selectedTemplate])
useEffect(() => {
if (targetHeaderId !== null) return
const first = targetHeaderOptions[0]
if (first) setTargetHeaderId(first.listHderId)
}, [targetHeaderOptions, targetHeaderId])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
@@ -116,175 +170,235 @@ const MessageSendDialog = ({
hideDialog(dialogId)
}
const handleTemplateChange = (nextTemplateId: string) => {
const template = templateOptions.find((item) => item.id === nextTemplateId)
setTemplateId(nextTemplateId)
if (!template) return
setTitle(template.title)
setBody(template.body)
const handleScheduleTypeChange = (next: 'instant' | 'reserve') => {
setScheduleType(next)
if (next === 'reserve' && !reserveAt) {
setReserveAt(getNearestFutureDateTime())
}
}
const handleSelectTemplate = (value: string) => {
const idx = Number(value)
setTemplateIdx(Number.isFinite(idx) && idx > 0 ? idx : null)
}
const buildMsgParam = (itemList: Record<number, string>): Record<string, string> => {
const param: Record<string, string> = {}
listHeaders.forEach((header) => {
const value = itemList[header.listHderId]
if (value !== undefined) param[header.listHderNm] = value
})
return param
}
const buildDestInfoList = (): DestInfo[] => {
if (!targetHeaderId) return []
return targetRows.map(({ sid, itemList }) => {
const destValue = itemList[targetHeaderId] ?? ''
return {
sid,
destEml: mode === 'email' ? destValue : undefined,
destTel: mode === 'sms' ? destValue : undefined,
msgParam: buildMsgParam(itemList),
}
})
}
const handleConfirm = async () => {
if (!templateId) {
if (!selectedTemplate || !templateIdx) {
alert('템플릿을 선택해 주세요.')
return
}
if (!title.trim() || !body.trim()) {
alert('제목과 내용을 입력해 주세요.')
if (!targetHeaderId) {
alert(`수신 ${mode === 'email' ? '이메일' : '번호'} 헤더를 선택해 주세요.`)
return
}
if (mode === 'email' && !senderEmail.trim()) {
alert('발송자 메일을 입력해 주세요.')
return
}
if (mode === 'sms' && !senderNumber.trim()) {
alert('발송 번호를 입력해 주세요.')
return
}
if (mode === 'email' && (!senderEmail.trim() || !senderName.trim())) {
alert('발송자 정보를 입력해 주세요.')
return
}
if (scheduleType === 'reserve' && !reserveAt) {
alert('예약 발송 일시를 선택해 주세요.')
return
}
if (isTargetTruncated) {
alert(`수신 대상이 ${MAX_TARGET_COUNT}건을 초과합니다. 대상 범위를 좁혀 주세요.`)
return
}
const destInfoList = buildDestInfoList()
if (destInfoList.length === 0) {
alert('수신 대상이 없습니다.')
return
}
setSubmitting(true)
try {
await onConfirm({
mode,
templateId,
senderEmail,
senderName,
senderNumber,
title,
body,
scheduleType,
reserveAt: scheduleType === 'reserve' ? reserveAt : undefined,
targetHeaderId,
const bulkSendKey = await createBulkKeyMutation.mutateAsync({
reqstCmpn: auth.user?.userCmpn ?? '',
reqstUser: auth.user?.userId ?? '',
reqstSvc: clientEnv.REQUEST_SVC,
prjctCd,
tmplatIdx: templateIdx,
resve: scheduleType === 'reserve',
sendDt: scheduleType === 'reserve' ? new Date(reserveAt).toISOString() : undefined,
trgtCnt: destInfoList.length,
})
await sendBulkMutation.mutateAsync({
sendEml: mode === 'email' ? senderEmail : undefined,
sendTel: mode === 'sms' ? senderNumber : undefined,
sendNm: senderName || undefined,
bulkSendKey,
destInfoList,
})
alert('발송 요청이 완료되었습니다.')
onSent?.()
handleOpenChange(false)
} catch (e) {
console.error(e)
alert('발송 중 오류가 발생했습니다.')
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[980px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">{titleMap[mode]}</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div className="space-y-4">
<div className="space-y-2">
<Label className="text-lg font-semibold">템플릿</Label>
<Select value={templateId} onValueChange={handleTemplateChange}>
<SelectTrigger className="w-full">
<SelectValue placeholder="템플릿을 선택해 주세요" />
</SelectTrigger>
<SelectContent>
{templateOptions.map((template) => (
<SelectItem key={template.id} value={template.id}>
{template.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{mode === 'email' ? (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
<div className="space-y-2">
<Label>발송자 메일</Label>
<Input value={senderEmail} onChange={(e) => setSenderEmail(e.target.value)} />
</div>
<div className="space-y-2">
<Label>발송자 이름</Label>
<Input value={senderName} onChange={(e) => setSenderName(e.target.value)} />
</div>
</div>
) : (
<div className="space-y-2">
<Label>발송 번호</Label>
<Input value={senderNumber} onChange={(e) => setSenderNumber(e.target.value)} />
</div>
)}
<div className="space-y-2">
<Label>{mode === 'email' ? '메일 제목' : '문자 제목'}</Label>
<Input value={title} onChange={(e) => setTitle(e.target.value)} />
</div>
<div className="space-y-2">
<Label>{mode === 'email' ? '메일 내용' : '문자 내용'}</Label>
<textarea
className="w-full min-h-36 rounded-md border px-3 py-2 text-sm resize-y"
value={body}
onChange={(e) => setBody(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>수신 대상 헤더</Label>
<Select value={String(targetHeaderId)} onValueChange={(v) => setTargetHeaderId(Number(v))}>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{targetHeaderOptions.map((header) => (
<SelectItem key={header.id} value={String(header.id)}>
{header.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>발송 일시</Label>
<RadioGroup
value={scheduleType}
onValueChange={(v) => setScheduleType(v as ScheduleType)}
className="flex items-center gap-4"
>
<div className="flex items-center gap-2">
<RadioGroupItem value="instant" id="message-send-instant" />
<Label htmlFor="message-send-instant">즉시</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="reserve" id="message-send-reserve" />
<Label htmlFor="message-send-reserve">예약</Label>
</div>
</RadioGroup>
{scheduleType === 'reserve' && (
<Input type="datetime-local" value={reserveAt} onChange={(e) => setReserveAt(e.target.value)} />
)}
</div>
</div>
<div className="rounded-md border p-4 space-y-2">
<p className="text-lg font-semibold">미리보기</p>
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
{selectedTemplate && (
<>
<div className="rounded border p-2 text-sm font-semibold">{title || '(제목 없음)'}</div>
<div className="rounded border p-3 text-sm whitespace-pre-wrap min-h-72">
{body || '(내용 없음)'}
</div>
</>
)}
</div>
</div>
<DialogFooter>
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
contentClassName="sm:max-w-[1100px] max-h-[90vh] overflow-y-auto"
bodyClassName="grid grid-cols-1 lg:grid-cols-2 gap-6"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
발송
{submitting ? '발송 중...' : '발송'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
}
>
<div className="space-y-4">
<div className="space-y-2">
<Label className="text-base">템플릿을 선택해 주세요</Label>
<KriSingleSelect
items={templateList}
value={String(templateIdx ?? '')}
onChange={handleSelectTemplate}
placeholder="템플릿을 선택해 주세요"
heightClassName="h-9"
widthClassName="w-full"
getLabel={(item) => item.tmplatNm}
getValue={(item) => String(item.tmplatIdx)}
/>
</div>
{mode === 'email' ? (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
<div className="space-y-2">
<Label className="text-base">발송자 메일</Label>
<Input value={senderEmail} onChange={(e) => setSenderEmail(e.target.value)} />
</div>
<div className="space-y-2">
<Label className="text-base">발송자 이름</Label>
<Input value={senderName} onChange={(e) => setSenderName(e.target.value)} />
</div>
</div>
) : (
<div className="space-y-2">
<Label className="text-base">발송 번호</Label>
<Input value={senderNumber} onChange={(e) => setSenderNumber(e.target.value)} />
</div>
)}
<div className="space-y-2">
<Label className="text-base">발송 일시</Label>
<RadioGroup
value={scheduleType}
onValueChange={(v) => handleScheduleTypeChange(v as 'instant' | 'reserve')}
className="flex items-center gap-4"
>
<div className="flex items-center gap-2 cursor-pointer">
<RadioGroupItem value="instant" id="message-send-instant" />
<Label htmlFor="message-send-instant">즉시</Label>
</div>
<div className="flex items-center gap-2 cursor-pointer">
<RadioGroupItem value="reserve" id="message-send-reserve" />
<Label htmlFor="message-send-reserve">예약</Label>
</div>
</RadioGroup>
{scheduleType === 'reserve' && (
<KriDateTimePicker value={reserveAt} onChange={setReserveAt} placeholder="예약 일시 선택" />
)}
</div>
<div className="space-y-2">
<Label className="text-base">수신 {mode === 'email' ? '이메일' : '번호'} 헤더</Label>
<KriSingleSelect
items={targetHeaderOptions}
value={String(targetHeaderId ?? '')}
onChange={(value) => setTargetHeaderId(Number(value) || null)}
placeholder={`수신 ${mode === 'email' ? '이메일' : '번호'}로 사용할 헤더를 선택해 주세요`}
heightClassName="h-9"
widthClassName="w-full"
getLabel={(item) => item.listHderNm}
getValue={(item) => String(item.listHderId)}
/>
{targetHeaderOptions.length === 0 && (
<p className="text-sm text-red-600">
{mode === 'email' ? '이메일' : '전화번호'} 타입의 리스트 헤더가 없습니다. 헤더 관리에서 먼저 설정해 주세요.
</p>
)}
</div>
<div className="space-y-2 rounded-md border p-4">
<Label className="text-base">수신 대상</Label>
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="message-send-target" />
<p className="text-sm text-muted-foreground">
대상 {targetTotalCount.toLocaleString()}건
{isTargetTruncated ? ` (최대 ${MAX_TARGET_COUNT.toLocaleString()}건까지만 발송 가능합니다)` : ''}
</p>
</div>
</div>
<div className="rounded-md border p-4 space-y-2">
<p className="text-lg font-semibold">미리보기</p>
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
{selectedTemplate && (
<>
{chnnlTy !== ChannelType.SMS && (
<div className="rounded border p-2 text-lg font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
)}
{chnnlTy === ChannelType.SMS ? (
<div className="flex flex-col items-center">
<KriEditor
mode="sms"
value={(selectedTemplate as TemplateSms).tmplatBody ?? ""}
onChange={() => {}}
isSmsReadOnly
placeholder="문자 내용을 입력해 주세요"
className="max-w-80 mx-0"
debounceMs={600}
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
/>
</div>
) : (
<div
className={cn('rounded-md border bg-muted/30 p-3')}
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
/>
)}
</>
)}
</div>
</KriDialog>
)
}

View File

@@ -1,14 +1,7 @@
'use client'
import {useState, useEffect, useMemo} from 'react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from "@/components/ui/dialog";
import { KriDialog } from "@/components/common/KriDialog";
import {Label} from "@/components/ui/label";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
@@ -21,7 +14,7 @@ import {ProjectCreateRequest} from "@/types/project";
import { useDebouncedValue } from "@kri/common/hooks";
import {PROJECT_NAME_REGEX} from "@/const/projectConst";
import {FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
import {MultiSelectOption} from "@/components/ui/multi-select";
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
import {ItrntUserInfo} from "@/types/user";
import {useIntranetProjectListQuery} from "@/query/intranet";
@@ -165,15 +158,32 @@ const ProjectCreateDialog = ({
}, [users]);
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[500px] text-sm">
<DialogHeader>
<DialogTitle className="text-xl">
프로젝트 생성
</DialogTitle>
<DialogDescription>프로젝트 생성에 필요한 기본 정보를 입력해주세요.</DialogDescription>
</DialogHeader>
<div className="grid gap-6 py-4">
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-xl">프로젝트 생성</span>}
description="프로젝트 생성에 필요한 기본 정보를 입력해주세요."
contentClassName="sm:max-w-[500px] text-sm"
bodyClassName="grid gap-6 py-4"
footer={
<>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
취소
</Button>
<Button
type="submit"
onClick={handleSubmit}
disabled={isSubmitting}
>
생성
</Button>
</>
}
>
<div className="grid gap-2">
<Label>
인트라넷 프로젝트<span className="text-red-500 ml-1">*</span>
@@ -230,25 +240,7 @@ const ProjectCreateDialog = ({
widthClassName="w-full"
/>
</div>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
취소
</Button>
<Button
type="submit"
onClick={handleSubmit}
disabled={isSubmitting}
>
생성
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</KriDialog>
);
}

View File

@@ -0,0 +1,91 @@
'use client'
import { KriDialog } from '@/components/common/KriDialog'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
import type { ListReserve } from '@/types/list'
import { formatKst } from '@kri/common'
export type ReservationListDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
reservations: ListReserve[]
onSelectReservation: (sid: string) => void
}
// 오늘과 가장 가까운(과거/미래 무관) 예약의 sid를 찾는다.
export const findClosestReservationSid = (reservations: ListReserve[], now: Date = new Date()): number | null => {
if (reservations.length === 0) return null
return reservations.reduce((closest, current) => {
const closestDiff = Math.abs(new Date(closest.resveDt).getTime() - now.getTime())
const currentDiff = Math.abs(new Date(current.resveDt).getTime() - now.getTime())
return currentDiff < closestDiff ? current : closest
}, reservations[0]).sid
}
const ReservationListDialog = ({
dialogId = 'reservationListDialog',
open,
onOpenChange,
reservations,
onSelectReservation,
}: ReservationListDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const resolvedOpen = open ?? isDialogOpen(dialogId)
const closestSid = findClosestReservationSid(reservations)
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleSelect = (sid: number) => {
onSelectReservation(String(sid))
handleOpenChange(false)
}
return (
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-xl">예약리스트 조회</span>}
contentClassName="sm:max-w-[480px]"
showDefaultFooter
>
<div className="max-h-80 overflow-auto rounded-md border">
{reservations.length === 0 ? (
<div className="p-6 text-center text-sm text-muted-foreground">예약된 리스트가 없습니다.</div>
) : (
<table className="w-full text-sm">
<thead className="sticky top-0 bg-muted">
<tr>
<th className="p-2 text-left">SID</th>
<th className="p-2 text-left">예약 일시</th>
</tr>
</thead>
<tbody>
{reservations.map((item) => (
<tr
key={item.listResveIdx}
className={`cursor-pointer border-t hover:bg-muted/50 ${item.sid === closestSid ? 'bg-accent' : ''}`}
onClick={() => handleSelect(item.sid)}
>
<td className="p-2">{item.sid}</td>
<td className="p-2">{formatKst(item.resveDt, 'dateHourMin')}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</KriDialog>
)
}
export default ReservationListDialog

View File

@@ -1,13 +1,7 @@
'use client'
import {useEffect, useMemo, useState} from 'react'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {Trash2, Plus, Download} from 'lucide-react'
@@ -77,6 +71,7 @@ const ResultCodeDialog = ({
resultCdTy: resultCodeType,
resultCd: lastCode + 1,
resultCdLbl: '',
isDefault: false,
}
])
}
@@ -220,23 +215,46 @@ const ResultCodeDialog = ({
}, [open]);
return (
<Dialog open={open} onOpenChange={handleClose}>
<KriDialog
open={open ?? false}
onOpenChange={(nextOpen) => {
if (!nextOpen) handleClose()
}}
title={<div className="text-2xl font-bold">결과 코드 설정</div>}
contentClassName={[
'overflow-hidden',
'transition-all duration-200',
importMode ? 'sm:max-w-6xl' : 'sm:max-w-3xl',
'w-[calc(100vw-2rem)]',
'max-h-[85vh]',
'gap-2',
].join(' ')}
bodyClassName="min-h-0 p-0"
footerClassName="px-6 py-4 border-t bg-white"
footer={
importMode ? (
<>
<Button variant="outline" onClick={handleImportCancel}>
취소
</Button>
<Button onClick={handleImportApply} disabled={!importProject} className="gap-2">
<Download className="w-4 h-4" />
가져오기 적용
</Button>
</>
) : (
<>
<Button variant="outline" onClick={handleClose}>
취소
</Button>
<Button onClick={handleSave}>
저장
</Button>
</>
)
}
>
{/* importMode일 때 더 넓게(그리고 애니메이션으로 부드럽게) */}
<DialogContent
className={[
'p-0 overflow-hidden',
'transition-all duration-200',
importMode ? 'sm:max-w-6xl' : 'sm:max-w-3xl',
'w-[calc(100vw-2rem)]',
'max-h-[85vh]',
'gap-2',
].join(' ')}
>
<DialogHeader className="px-6 pt-6 pb-4 border-b">
<DialogTitle className="flex items-center justify-between gap-3">
<span>결과 코드 설정</span>
</DialogTitle>
</DialogHeader>
{/* 상단 버튼 영역 */}
<div className="px-6 pt-1 pb-3 border-b bg-white flex justify-end">
@@ -272,7 +290,7 @@ const ResultCodeDialog = ({
</div>
)}
</div>
<div className="px-6 pt-4 flex flex-wrap items-center gap-2">
<div className="px-6 py-2 flex flex-wrap items-center gap-1">
{RESULT_CODE_TYPE_OPTIONS
.filter((opt) => opt.value !== ResultCodeType.SURVEY)
.map((opt) => (
@@ -315,7 +333,9 @@ const ResultCodeDialog = ({
<tbody className="divide-y">
{resultCodeArray
.filter((rc) => rc.resultCdTy === resultCodeType)
.map((code, index) => (
.map((code, index) => {
const isLocked = code.isDefault;
return (
<tr key={index} className="hover:bg-gray-50">
<td className="px-4 py-2 align-middle">
<Input
@@ -323,7 +343,7 @@ const ResultCodeDialog = ({
onChange={(e) => handleCodeChange(code.resultCdUUID, 'resultCd', e.target.value)}
onBlur={(e) => checkDuplicate(code.resultCdUUID, Number(e.target.value), e.target)}
className="h-9"
disabled={importMode}
disabled={importMode || isLocked}
/>
</td>
<td className="px-4 py-2 align-middle">
@@ -331,15 +351,15 @@ const ResultCodeDialog = ({
value={code.resultCdLbl}
onChange={(e) => handleCodeChange(code.resultCdUUID, 'resultCdLbl', e.target.value)}
className="h-9"
disabled={importMode}
disabled={importMode || isLocked}
/>
</td>
<td className="px-2 py-2 align-middle">
{!importMode && (
{!importMode && !isLocked && (
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteCode(index)}
onClick={() => handleDeleteCode(code.resultCd)}
aria-label="delete"
>
<Trash2 className="w-4 h-4 text-red-600" />
@@ -347,7 +367,8 @@ const ResultCodeDialog = ({
)}
</td>
</tr>
))}
);
})}
</tbody>
</table>
</div>
@@ -398,30 +419,7 @@ const ResultCodeDialog = ({
)}
</div>
<DialogFooter className="px-6 py-4 border-t bg-white">
{importMode ? (
<>
<Button variant="outline" onClick={handleImportCancel}>
취소
</Button>
<Button onClick={handleImportApply} disabled={!importProject} className="gap-2">
<Download className="w-4 h-4" />
가져오기 적용
</Button>
</>
) : (
<>
<Button variant="outline" onClick={handleClose}>
취소
</Button>
<Button onClick={handleSave}>
저장
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</KriDialog>
)
}

View File

@@ -0,0 +1,230 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Label } from '@/components/ui/label'
import { KriDateTimePicker } from '@/components/common/KriDateTimePicker'
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import { useDialog } from '@/hooks/useDialog'
import {
useMainTemplateIdxQuery,
useSendSingleMessageMutation,
useTemplateListQuery,
useTemplateQuery,
} from '@/query/message'
import { ChannelType, type TemplateSms, type TemplateSummary } from '@kri/common/noti-hub'
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
import { KriEditor } from '@/components/kri-editor'
import { getNearestFutureDateTime } from '@/lib/datetime'
import type { DialogId } from '@/store/jotai/dialog'
import type { MessageSendChannel } from '@/types/message'
const titleMap: Record<MessageSendChannel, string> = {
email: '메일 발송',
sms: '문자 발송',
}
export type SingleMessageSendDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
channel: MessageSendChannel
prjctIdx: number
itrntPrjctCd: string
sid: string
destHeaderId: number
onSent?: () => void
}
const SingleMessageSendDialog = ({
dialogId = 'singleMessageSendDialog',
open,
onOpenChange,
channel,
prjctIdx,
itrntPrjctCd,
sid,
destHeaderId,
onSent,
}: SingleMessageSendDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const resolvedOpen = open ?? isDialogOpen(dialogId)
const chnnlTy = channel === 'email' ? ChannelType.EMAIL : ChannelType.SMS
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
const [reserveAt, setReserveAt] = useState('')
const [submitting, setSubmitting] = useState(false)
const enabled = resolvedOpen && !!itrntPrjctCd
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled)
const templateList: TemplateSummary[] = templateListQuery.data ?? []
const templateDetailQuery = useTemplateQuery(templateIdx ?? 0, enabled && !!templateIdx)
const selectedTemplate = templateDetailQuery.data ?? null
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
const mainTemplateIdx = mainTemplateQuery.data ?? null
const sendSingleMutation = useSendSingleMessageMutation(channel, prjctIdx)
const mainTemplateAppliedRef = useRef(false)
useEffect(() => {
if (!resolvedOpen) return
setTemplateIdx(null)
setScheduleType('instant')
setReserveAt('')
mainTemplateAppliedRef.current = false
}, [resolvedOpen])
// 대표 템플릿이 있으면 최초 1회 자동 선택
useEffect(() => {
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return
mainTemplateAppliedRef.current = true
if (mainTemplateIdx) setTemplateIdx(mainTemplateIdx)
}, [enabled, mainTemplateQuery.isSuccess, mainTemplateIdx])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleScheduleTypeChange = (next: 'instant' | 'reserve') => {
setScheduleType(next)
if (next === 'reserve' && !reserveAt) {
setReserveAt(getNearestFutureDateTime())
}
}
const handleSelectTemplate = (value: string) => {
const idx = Number(value)
setTemplateIdx(Number.isFinite(idx) && idx > 0 ? idx : null)
}
const handleConfirm = async () => {
if (!templateIdx) {
alert('템플릿을 선택해 주세요.')
return
}
if (scheduleType === 'reserve' && !reserveAt) {
alert('예약 발송 일시를 선택해 주세요.')
return
}
setSubmitting(true)
try {
await sendSingleMutation.mutateAsync({
tmplatIdx: templateIdx,
resve: scheduleType === 'reserve',
sendDt: scheduleType === 'reserve' ? new Date(reserveAt).toISOString() : undefined,
sid: Number(sid),
destHeaderIds: [destHeaderId],
})
alert('발송 요청이 완료되었습니다.')
onSent?.()
handleOpenChange(false)
} catch (e) {
console.error(e)
alert('발송 중 오류가 발생했습니다.')
} finally {
setSubmitting(false)
}
}
return (
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-xl font-bold">{titleMap[channel]}</span>}
contentClassName="sm:max-w-[900px] max-h-[90vh] overflow-y-auto"
bodyClassName="grid grid-cols-1 lg:grid-cols-2 gap-6"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
{submitting ? '발송 중...' : '발송'}
</Button>
</>
}
>
<div className="space-y-4">
<div className="space-y-2">
<Label className="text-sm">템플릿을 선택해 주세요</Label>
<KriSingleSelect
items={templateList}
value={String(templateIdx ?? '')}
onChange={handleSelectTemplate}
placeholder="템플릿을 선택해 주세요"
heightClassName="h-9"
widthClassName="w-full"
getLabel={(item) => item.tmplatNm}
getValue={(item) => String(item.tmplatIdx)}
/>
</div>
<div className="space-y-2">
<Label className="text-sm">발송 일시</Label>
<RadioGroup
value={scheduleType}
onValueChange={(v) => handleScheduleTypeChange(v as 'instant' | 'reserve')}
className="flex items-center gap-4"
>
<div className="flex items-center gap-2 cursor-pointer">
<RadioGroupItem value="instant" id="single-send-instant" />
<Label htmlFor="single-send-instant">즉시</Label>
</div>
<div className="flex items-center gap-2 cursor-pointer">
<RadioGroupItem value="reserve" id="single-send-reserve" />
<Label htmlFor="single-send-reserve">예약</Label>
</div>
</RadioGroup>
{scheduleType === 'reserve' && (
<KriDateTimePicker value={reserveAt} onChange={setReserveAt} placeholder="예약 일시 선택" />
)}
</div>
</div>
<div className="space-y-2 rounded-md border p-4">
<p className="text-sm font-semibold">미리보기</p>
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
{selectedTemplate && (
<>
{chnnlTy !== ChannelType.SMS && (
<div className="rounded border p-2 text-sm font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
)}
{chnnlTy === ChannelType.SMS ? (
<div className="flex flex-col items-center">
<KriEditor
mode="sms"
value={(selectedTemplate as TemplateSms).tmplatBody ?? ''}
onChange={() => {}}
isSmsReadOnly
placeholder="문자 내용을 입력해 주세요"
className="max-w-80 mx-0"
debounceMs={600}
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
/>
</div>
) : (
<div
className="rounded-md border bg-muted/30 p-3 text-sm"
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
/>
)}
</>
)}
</div>
</KriDialog>
)
}
export default SingleMessageSendDialog

View File

@@ -0,0 +1,69 @@
'use client'
import { useEffect, useState } from 'react'
import { toDataURL } from 'qrcode'
import { KriDialog } from '@/components/common/KriDialog'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
export type SurveyQrDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
url: string
}
const SurveyQrDialog = ({ dialogId = 'surveyQrDialog', open, onOpenChange, url }: SurveyQrDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
useEffect(() => {
if (!resolvedOpen || !url) {
setQrDataUrl(null)
return
}
let cancelled = false
toDataURL(url, { width: 240 }).then((dataUrl) => {
if (!cancelled) setQrDataUrl(dataUrl)
})
return () => {
cancelled = true
}
}, [resolvedOpen, url])
return (
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-xl">설문 QR코드</span>}
contentClassName="sm:max-w-[360px]"
>
<div className="flex flex-col items-center gap-3 py-4">
{qrDataUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={qrDataUrl} alt="설문 QR코드" width={240} height={240} />
) : (
<div className="flex h-[240px] w-[240px] items-center justify-center text-sm text-muted-foreground">
QR코드 생성 중...
</div>
)}
<p className="break-all text-center text-xs text-muted-foreground">{url}</p>
</div>
</KriDialog>
)
}
export default SurveyQrDialog

View File

@@ -1,12 +1,6 @@
'use client'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { useState, useRef } from 'react'
import {Download, Upload, X} from 'lucide-react'
@@ -117,13 +111,20 @@ const UserUploadDialog = ({
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle className=" text-2xl font-bold">User upload</DialogTitle>
</DialogHeader>
<div className="space-y-6 py-4">
<KriDialog
open={resolvedOpen}
onOpenChange={handleDialogOpenChange}
title={<span className="text-2xl font-bold">User upload</span>}
contentClassName="sm:max-w-[600px]"
bodyClassName="space-y-6 py-4"
footer={
<div className="flex items-center justify-end w-full gap-2">
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting}>
확인
</Button>
</div>
}
>
<div>
<div className="flex gap-2">
<Button
@@ -165,17 +166,7 @@ const UserUploadDialog = ({
onChange={handleFileSelect}
/>
</div>
</div>
<DialogFooter>
<div className="flex items-center justify-end w-full gap-2">
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting}>
확인
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
</KriDialog>
)
}

View File

@@ -1,27 +1,20 @@
'use client'
import { useState, useEffect } from 'react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
import { UserInfoSaveRequest } from '@/types/user'
import KriPassword from "@/components/common/KriPassword";
import KriPassword, { KRI_PW_REGEX } from "@/components/common/KriPassword";
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
import {DataVerification} from "@/types/common";
import type { DataVerification } from "@kri/common";
import {apiError} from "@kri/common/http";
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
import {FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
import {CONTACT_INTERVIEWER_ROLE, FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@kri/common/http";
import type { CmpnInfo } from "@/types/cmpn";
export type UserUpsertDialogProps = {
/** Jotai로 관리할 다이얼로그 ID */
@@ -35,7 +28,7 @@ export type UserUpsertDialogProps = {
initialData?: Partial<UserInfoSaveRequest>
isInternal: boolean
userCmpn: string
userCmpnArray: string[]
userCmpnArray: CmpnInfo[]
userRoleArray: KriSelectItem[]
onSubmit: (data: UserInfoSaveRequest) => void | Promise<void>
onCheckDuplicate?: (userId: string) => DataVerification | Promise<DataVerification>
@@ -47,7 +40,6 @@ const UserUpsertDialog = ({
onOpenChange,
mode = 'create',
initialData,
isInternal,
userCmpn,
userCmpnArray,
userRoleArray,
@@ -60,7 +52,7 @@ const UserUpsertDialog = ({
userName: '',
userCmpn: userCmpn,
userTeam: '',
userRole: 9002,
userRole: CONTACT_INTERVIEWER_ROLE,
memo: '',
}
@@ -102,7 +94,7 @@ const UserUpsertDialog = ({
}
}, [initialData, mode, resolvedOpen])
const handleInputChange = (field: keyof UserInfoSaveRequest, value: any) => {
const handleInputChange = <K extends keyof UserInfoSaveRequest>(field: K, value: UserInfoSaveRequest[K]) => {
setFormData(prev => ({
...prev,
[field]: value,
@@ -146,6 +138,10 @@ const UserUpsertDialog = ({
alert("비밀번호를 입력해주세요.");
return;
}
if (!KRI_PW_REGEX.test(formData.userPw)) {
alert("비밀번호는 영문과 숫자를 포함한 8~20자로 입력해주세요.");
return;
}
if (!formData.userName.trim()) {
alert("이름을 입력해주세요.");
return;
@@ -179,15 +175,32 @@ const UserUpsertDialog = ({
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[500px] text-sm">
<DialogHeader>
<DialogTitle className="text-xl">
{mode === 'create' ? '계정 등록' : '계정 수정'}
</DialogTitle>
<DialogDescription>면접원 계정 정보를 입력해주세요.</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<KriDialog
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-xl">{mode === 'create' ? '계정 등록' : '계정 수정'}</span>}
description="면접원 계정 정보를 입력해주세요."
contentClassName="sm:max-w-[500px] text-sm"
bodyClassName="grid gap-4 py-4"
footer={
<>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
취소
</Button>
<Button
type="submit"
onClick={handleSubmit}
disabled={isSubmitting}
>
{mode === 'create' ? "등록" : "수정"}
</Button>
</>
}
>
<div className="grid gap-2">
<Label htmlFor="userId">
ID<span className="text-red-500 ml-1">*</span>
@@ -217,6 +230,7 @@ const UserUpsertDialog = ({
</Label>
<KriPassword
id="password"
label=""
value={formData.userPw}
onChange={(v) => handleInputChange('userPw', v)}
placeholder="Enter password"
@@ -235,45 +249,35 @@ const UserUpsertDialog = ({
</div>
<div className="grid gap-2">
<Label>계정 권한</Label>
<KriSingleSelect
<KriSelect
items={userRoleArray}
value={String(formData.userRole)}
getLabel={(item) => item.label}
getValue={(item) => String(item.value)}
onChange={(e) => {
if(mode !== 'create'){
alert("권한이 변경되면 해당 계정에 배정된 리스트 정보가 초기화됩니다.");
}
handleInputChange('userRole', Number(e));
}}
getLabel={(item) => item.label}
getValue={(item) => String(item.value)}
placeholder="사용자 권한"
widthClassName="w-full"
heightClassName="h-9"
useAll={false}
className="w-full min-w-0 overflow-hidden [&>span]:truncate"
heightClassName="h-8"
/>
</div>
<div className="grid gap-2">
<Label>소속 회사</Label>
{
isInternal && formData.userRole > 9000 ?
<KriSingleSelect
items={userCmpnArray}
value={formData.userCmpn}
onChange={(e) => handleInputChange('userCmpn', e)}
placeholder="소속 회사"
widthClassName="w-full"
heightClassName="h-9"
/>
:
<Input
id="userCmpn"
placeholder="Enter company"
value={formData.userCmpn}
disabled={!isInternal}
onChange={(e) => handleInputChange('userCmpn', e.target.value)}
/>
}
<KriSelect
items={userCmpnArray}
value={formData.userCmpn}
getValue={(item) => item.cmpnId}
getLabel={(item) => item.cmpnAlias || item.cmpnId}
onChange={(e) => handleInputChange('userCmpn', e)}
useAll={false}
disabled={mode !== 'create'}
className="w-full min-w-0 overflow-hidden [&>span]:truncate"
heightClassName="h-9"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="memo">메모</Label>
@@ -284,25 +288,7 @@ const UserUpsertDialog = ({
onChange={(e) => handleInputChange('memo', e.target.value)}
/>
</div>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
취소
</Button>
<Button
type="submit"
onClick={handleSubmit}
disabled={isSubmitting}
>
{mode === 'create' ? "등록" : "수정"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</KriDialog>
)
}