261019_01_ENH: 리스트 비동기 작업 동시 실행 제한 및 진행 상태 UI 개선, 미사용 참조 정리

This commit is contained in:
2026-10-19 14:22:07 +09:00
parent 4e51530922
commit d2e826702e
46 changed files with 1398 additions and 406 deletions

View File

@@ -17,6 +17,7 @@ import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data"
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
import { cn } from "@/lib/utils";
import { FONT_SIZE } from "@/const/commonConst";
import { ListJobWatcher } from "@/components/list/ListJobWatcher";
type AppMainLayoutProps = {
children: ReactNode;
@@ -235,6 +236,7 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
}
>
{children}
{mounted && auth.user && <ListJobWatcher userId={auth.user.userId} prjctIdx={selectedProject?.prjctIdx ?? 0} />}
<ReserveSearchDialog />
</KriMainLayout>
);

View File

@@ -121,7 +121,7 @@ export function DataTable<TData, TValue = unknown>({
[topPinnedRows, data, bottomPinnedRows],
)
const internalGetRowId = useCallback((row: TData, index: number) => {
const internalGetRowId = useCallback((_row: TData, index: number) => {
if (index < topPinnedRows.length) return `__top-pinned-${index}`
if (index >= topPinnedRows.length + data.length) {
return `__bottom-pinned-${index - topPinnedRows.length - data.length}`

View File

@@ -15,6 +15,7 @@ import {
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import { useDialog } from '@/hooks/useDialog'
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
import type { DialogId } from '@/store/jotai/dialog'
import type { FilterValueOption, ListFilterTarget } from '@/types/list'
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
@@ -47,6 +48,7 @@ export type BatchEditPayload = {
}
export type ListBatchEditDialogProps = {
prjctIdx: number
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
@@ -75,6 +77,7 @@ const resultCodeGroups: { type: Exclude<ResultCodeType, ResultCodeType.SURVEY>;
]
const ListBatchEditDialog = ({
prjctIdx,
dialogId = 'listBatchEditDialog',
open,
onOpenChange,
@@ -98,6 +101,7 @@ const ListBatchEditDialog = ({
const rowInputRefs = useRef<Map<string, HTMLInputElement>>(new Map())
const resolvedOpen = open ?? isDialogOpen(dialogId)
const gate = useListJobGate({ prjctIdx, jobType: 'LIST_UPDATE', active: resolvedOpen })
const defaultHeaderId = headerOptions[0]?.id ?? 0
const isFileHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.FILE
@@ -168,6 +172,7 @@ const ListBatchEditDialog = ({
}
const handleConfirm = async () => {
if (gate.submitBlocked || submitting) return
setInvalidRowId(null)
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
@@ -203,7 +208,6 @@ const ListBatchEditDialog = ({
setSubmitting(true)
try {
await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, surveyResultCodes, target })
handleOpenChange(false)
} finally {
setSubmitting(false)
}
@@ -214,19 +218,23 @@ const ListBatchEditDialog = ({
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">일괄 수정</span>}
contentClassName="sm:max-w-[900px]"
contentClassName="sm:max-w-[900px] max-h-[90vh] overflow-y-auto"
bodyClassName="space-y-4"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
적용
{gate.hasCurrentJob ? '닫기' : '취소'}
</Button>
{!gate.hasCurrentJob && (
<Button type="button" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
적용
</Button>
)}
</>
}
>
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
{!gate.hasCurrentJob && <>
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">적용 대상</p>
<ApplyFilterOption
@@ -399,6 +407,7 @@ const ListBatchEditDialog = ({
<Plus className="w-4 h-4" />
행 추가
</Button>
</>}
</KriDialog>
)
}

View File

@@ -8,6 +8,8 @@ import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { useDialog } from '@/hooks/useDialog'
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
import { LIST_DOWNLOAD_JOB_TYPE } from '@/const/listJobConst'
import type { DialogId } from '@/store/jotai/dialog'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import KriDateRangePicker from '@/components/common/KriDateRangePicker'
@@ -20,6 +22,7 @@ import {
} from '@/types/list'
export type ListDownloadDialogProps = {
prjctIdx: number
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
@@ -37,6 +40,7 @@ const titleMap: Record<ListDownloadMode, string> = {
}
const ListDownloadDialog = ({
prjctIdx,
dialogId = 'listDownloadDialog',
open,
onOpenChange,
@@ -55,6 +59,7 @@ const ListDownloadDialog = ({
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const gate = useListJobGate({ prjctIdx, jobType: LIST_DOWNLOAD_JOB_TYPE[mode], active: resolvedOpen })
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
@@ -66,6 +71,7 @@ const ListDownloadDialog = ({
}
const handleDownload = async () => {
if (gate.submitBlocked || submitting) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
if (mode === 'contact-history') {
@@ -93,7 +99,6 @@ const ListDownloadDialog = ({
contactHistoryType: mode === 'contact-history' ? contactHistoryType : undefined,
historyOrder: mode === 'contact-history' ? historyOrder : undefined,
})
handleOpenChange(false)
} finally {
setSubmitting(false)
}
@@ -104,20 +109,24 @@ const ListDownloadDialog = ({
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
contentClassName="sm:max-w-[560px]"
contentClassName="sm:max-w-[560px] max-h-[90vh] overflow-y-auto"
bodyClassName="space-y-4"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleDownload} disabled={submitting} className="gap-2">
<Download className="w-4 h-4" />
다운로드
{gate.hasCurrentJob ? '닫기' : '취소'}
</Button>
{!gate.hasCurrentJob && (
<Button type="button" onClick={handleDownload} disabled={submitting || gate.submitBlocked} className="gap-2">
<Download className="w-4 h-4" />
다운로드
</Button>
)}
</>
}
>
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
{!gate.hasCurrentJob && <>
{mode === 'contact-history' ? (
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">조회 기간</p>
@@ -189,6 +198,7 @@ const ListDownloadDialog = ({
</RadioGroup>
</div>
) : null}
</>}
</KriDialog>
)
}

View File

@@ -38,6 +38,7 @@ export type ListHeaderManageDialogProps = {
prjctIdx: number
rows: listHeader[]
onConfirm: (rows: listHeader[]) => void | Promise<void>
saveDisabled?: boolean
}
type ListHeaderRowProps = {
@@ -179,6 +180,7 @@ const ListHeaderManageDialog = ({
prjctIdx,
rows,
onConfirm,
saveDisabled = false,
}: ListHeaderManageDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [localRows, setLocalRows] = useState<listHeader[]>([])
@@ -299,6 +301,7 @@ const ListHeaderManageDialog = ({
}
const handleConfirm = async () => {
if (saveDisabled || submitting) return
const names = localRows.map((row) => row.listHderNm.trim())
const duplicateNames = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))]
if (duplicateNames.length > 0) {
@@ -354,12 +357,13 @@ const ListHeaderManageDialog = ({
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
<Button type="button" onClick={handleConfirm} disabled={submitting || saveDisabled}>
저장
</Button>
</>
}
>
{saveDisabled && <p role="alert" className="mb-2 text-sm text-amber-800">리스트 작업이 진행 중이거나 작업 상태를 확인할 수 없어 헤더를 저장할 수 없습니다.</p>}
<div className="flex justify-between mb-2">
<span className="text-base text-red-600 font-semibold">⚠️ 헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩에 영향이 있을 수 있습니다.</span>

View File

@@ -6,11 +6,13 @@ import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { useDialog } from '@/hooks/useDialog'
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
import type { DialogId } from '@/store/jotai/dialog'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import type { ListFilterTarget, ListResetScope } from '@/types/list'
export type ListResetDialogProps = {
prjctIdx: number
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
@@ -20,6 +22,7 @@ export type ListResetDialogProps = {
}
const ListResetDialog = ({
prjctIdx,
dialogId = 'listResetDialog',
open,
onOpenChange,
@@ -33,6 +36,7 @@ const ListResetDialog = ({
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const gate = useListJobGate({ prjctIdx, jobType: 'LIST_RESET', active: resolvedOpen })
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
@@ -44,13 +48,13 @@ const ListResetDialog = ({
}
const handleConfirm = async () => {
if (gate.submitBlocked || submitting) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return
setSubmitting(true)
try {
await onConfirm({ target, scope })
handleOpenChange(false)
} finally {
setSubmitting(false)
}
@@ -61,19 +65,23 @@ const ListResetDialog = ({
open={resolvedOpen}
onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">리스트 초기화</span>}
contentClassName="sm:max-w-[700px]"
contentClassName="sm:max-w-[700px] max-h-[90vh] overflow-y-auto"
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}>
초기화
{gate.hasCurrentJob ? '닫기' : '취소'}
</Button>
{!gate.hasCurrentJob && (
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
초기화
</Button>
)}
</>
}
>
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
{!gate.hasCurrentJob && <>
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
<ApplyFilterOption
@@ -98,6 +106,7 @@ const ListResetDialog = ({
</div>
</RadioGroup>
</div>
</>}
</KriDialog>
)
}

View File

@@ -6,10 +6,9 @@ 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'
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
import { useLoading } from '@/hooks/useLoading'
import type { DialogId } from '@/store/jotai/dialog'
import { formatKst } from '@kri/common'
@@ -22,6 +21,7 @@ export type ValidationOption = {
}
export type ListUploadDialogProps = {
prjctIdx: number
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
@@ -32,10 +32,12 @@ export type ListUploadDialogProps = {
headerRows?: listHeader[]
}
const ACCEPT_EXTENSIONS = ['.xlsx', '.xls', '.csv']
const ACCEPT_EXTENSIONS = ['.xlsx']
// 전체 초기화 후 등록(RESET_AND_INSERT)은 위험성 때문에 사용하지 않는다.
const FIXED_UPLOAD_MODE = ListUploadMode.ADD_AND_CHANGE
const ListUploadDialog = ({
prjctIdx,
dialogId = 'listUploadDialog',
open,
onOpenChange,
@@ -52,8 +54,6 @@ const ListUploadDialog = ({
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [excelHeaders, setExcelHeaders] = useState<string[]>([])
const [otherHeaderTypeMap, setOtherHeaderTypeMap] = useState<Record<number, ListHeaderType>>({})
// 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>({
@@ -62,6 +62,7 @@ const ListUploadDialog = ({
})
const resolvedOpen = open ?? isDialogOpen(dialogId)
const gate = useListJobGate({ prjctIdx, jobType: 'LIST_UPLOAD', active: resolvedOpen })
const normalizedHistory = useMemo(
() =>
@@ -94,7 +95,6 @@ const ListUploadDialog = ({
setSelectedFile(null)
setExcelHeaders([])
setOtherHeaderTypeMap({})
setUploadMode(ListUploadMode.ADD_AND_CHANGE)
setSubmitting(false)
setHistoryExpanded(false)
setValidation({
@@ -137,7 +137,7 @@ const ListUploadDialog = ({
const { read, utils } = await import('xlsx')
const buffer = await file.arrayBuffer()
const workbook = read(buffer, { type: 'array' })
const workbook = read(buffer, { type: 'array', sheetRows: 1, sheets: 0 })
const firstSheet = workbook.SheetNames[0]
if (!firstSheet) return []
const rows = utils.sheet_to_json<(string | number | null)[]>(workbook.Sheets[firstSheet], { header: 1, raw: false })
@@ -151,10 +151,11 @@ const ListUploadDialog = ({
const lower = file.name.toLowerCase()
const valid = ACCEPT_EXTENSIONS.some((ext) => lower.endsWith(ext))
if (!valid) {
alert('엑셀 또는 CSV 파일만 업로드 가능합니다. (.xlsx, .xls, .csv)')
alert('XLSX 파일만 업로드 가능합니다. (.xlsx)')
return
}
if (file.size > 100 * 1024 * 1024) { alert('100MB 이하의 파일을 선택해 주세요.'); return }
setSelectedFile(file)
void withLoadingAsync(async () => {
try {
@@ -168,6 +169,7 @@ const ListUploadDialog = ({
}
const handleSubmit = async () => {
if (gate.submitBlocked || submitting) return
if (!selectedFile) {
alert('업로드할 파일을 선택해 주세요.')
return
@@ -177,7 +179,7 @@ const ListUploadDialog = ({
try {
const specificHeader = Object.fromEntries(
Object.entries(otherHeaderTypeMap)
.map(([index, value]) => [String(Number(index) + 1), value])
.map(([index, value]) => [String(Math.max(101, ...orderedHeaderRows.map(row => row.listHderId + 1)) + Number(index) - baseHeaderRows.length), value])
.filter(([, value]) => value !== ListHeaderConst.TEXT),
)
@@ -187,8 +189,6 @@ const ListUploadDialog = ({
checkDuplicatePhone: validation.checkPhoneDuplicate,
...(Object.keys(specificHeader).length > 0 ? { specificHeader } : {}),
})
resetState()
handleOpenChange(false)
} catch (e) {
console.error(e)
} finally {
@@ -256,44 +256,23 @@ const ListUploadDialog = ({
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"
contentClassName="w-[min(960px,95vw)] max-w-[95vw] sm:max-w-[min(960px,95vw)] max-h-[90vh] grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden"
bodyClassName="min-w-0 space-y-6 overflow-y-auto py-2"
footer={
<>
<Button type="button" variant="outline" onClick={() => handleDialogOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch}>
{submitting ? '업로드 중...' : '업로드'}
{gate.hasCurrentJob ? '닫기' : '취소'}
</Button>
{!gate.hasCurrentJob && (
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch || gate.submitBlocked}>
{submitting ? '업로드 중...' : '업로드'}
</Button>
)}
</>
}
>
{
/*
<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>
*/
}
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
{!gate.hasCurrentJob && <>
<div className="space-y-3">
<Label className="text-lg font-semibold">업로드 파일</Label>
<div className="min-w-0 flex items-center gap-2">
@@ -425,6 +404,7 @@ const ListUploadDialog = ({
</div>
)}
</div>
</>}
</KriDialog>
)
}

View File

@@ -11,7 +11,6 @@ import { useDialog } from '@/hooks/useDialog'
import { useSelectedProject } from '@/hooks/useSelectedProject'
import {
useMainTemplateIdxQuery,
useSendBulkMessageMutation,
useTemplateListQuery,
useTemplateQuery,
} from '@/query/message'
@@ -23,6 +22,9 @@ import type { ListTableRow } from '@/components/table-column/ListTableColumn'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import MessageSendPreview from '@/components/message-template/MessageSendPreview'
import type { MessageSendChannel, TemplateSummaryWithPurpose } from '@/types/message'
import { useSubmitListJob } from '@/query/list-job'
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
import { MESSAGE_JOB_TYPE } from '@/const/listJobConst'
import { MESSAGE_CHANNEL_TYPE, TEMPLATE_PURPOSE } from '@/const/messageTemplateConst'
export type MessageSendMode = MessageSendChannel
@@ -71,6 +73,7 @@ const MessageSendDialog = ({
const resolvedOpen = open ?? isDialogOpen(dialogId)
const prjctIdx = selectedProject?.prjctIdx ?? 0
const gate = useListJobGate({ prjctIdx, jobType: MESSAGE_JOB_TYPE[mode], active: resolvedOpen })
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? ''
const enabled = resolvedOpen && !!selectedProject && prjctIdx > 0
@@ -98,7 +101,7 @@ const MessageSendDialog = ({
[listHeaders, headerType],
)
const sendBulkMessageMutation = useSendBulkMessageMutation(mode, prjctIdx)
const sendBulkMessageMutation = useSubmitListJob(prjctIdx)
const mainTemplateAppliedRef = useRef(false)
@@ -158,6 +161,7 @@ const MessageSendDialog = ({
}
const handleConfirm = async () => {
if (gate.submitBlocked || submitting) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
if (!selectedTemplate || !templateIdx) {
alert('템플릿을 선택해 주세요.')
@@ -187,21 +191,18 @@ const MessageSendDialog = ({
setSubmitting(true)
try {
const res = await sendBulkMessageMutation.mutateAsync({
await sendBulkMessageMutation.mutateAsync({
jobType: MESSAGE_JOB_TYPE[mode],
path: `messages/${mode}`,
body: {
tmplatIdx: templateIdx,
resve: scheduleType === 'reserve',
sendDt: scheduleType === 'reserve' ? toReserveSendDt(reserveAt) : undefined,
listFilter,
destHeaderIds: [targetHeaderId],
},
})
if (res.failCount > 0) {
alert(`대상 ${res.targetCount}건 중 ${res.acceptCount}건 접수, ${res.failCount}건 실패했습니다.`)
} else {
alert(`대상 ${res.targetCount}건 발송 요청이 완료되었습니다.`)
}
onSent?.()
handleOpenChange(false)
} catch (e) {
console.error(e)
} finally {
@@ -214,19 +215,23 @@ const MessageSendDialog = ({
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"
contentClassName={gate.hasCurrentJob ? "sm:max-w-[700px] max-h-[90vh] overflow-y-auto" : "sm:max-w-[1100px] max-h-[90vh] overflow-y-auto"}
bodyClassName={gate.hasCurrentJob ? "space-y-4" : "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 ? '발송 중...' : '발송'}
{gate.hasCurrentJob ? '닫기' : '취소'}
</Button>
{!gate.hasCurrentJob && (
<Button type="button" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
{submitting ? '발송 중...' : '발송'}
</Button>
)}
</>
}
>
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" className="lg:col-span-2" />
{!gate.hasCurrentJob && <>
<div className="space-y-4">
<div className="space-y-2">
<Label className="text-base">템플릿을 선택해 주세요</Label>
@@ -319,6 +324,7 @@ const MessageSendDialog = ({
</div>
<MessageSendPreview chnnlTy={chnnlTy} template={selectedTemplate} />
</>}
</KriDialog>
)
}

View File

@@ -65,7 +65,6 @@ export function KriEditorHtmlOnly({
React.useEffect(() => {
applyExternalValue(value || '')
// 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
React.useEffect(() => {

View File

@@ -1,6 +1,6 @@
'use client'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useRef, useState, type ReactNode } from 'react'
import { Mail, MessageCircle, MessageSquare, Paperclip, Phone, QrCode } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'

View File

@@ -0,0 +1,156 @@
'use client'
import { useEffect } from 'react'
import { useAtom } from 'jotai'
import { HttpError } from '@kri/common/http'
import { Button } from '@/components/ui/button'
import { ListJobProgress } from '@/components/list/ListJobProgress'
import { useAuth } from '@/hooks/useAuth'
import { isAvailabilityUnsupported, useListJob, useListJobAvailability, useUploadResetActive } from '@/query/list-job'
import { findTrackedListJob, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker'
import { listJobLabel } from '@/const/listJobConst'
import { blockerJobLabel, blockerPhaseLabel, blockerUserLabel, describeListJobAvailability } from '@/utils/listJobAvailability'
import { isActiveListJob, type ListJobType } from '@/types/list-job'
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
export type ListJobGateStatus = 'idle' | 'checking' | 'allowed' | 'blocked' | 'error' | 'unsupported'
/**
* 작업 다이얼로그(또는 배정 버튼 영역)에서 쓰는 접수 가능 여부와 내 현재 작업 상태.
* - availability: 다이얼로그는 차단 중 3초, 페이지는 평상시 10초·차단 중 3초 조회한다.
* - 내 현재 작업: localStorage 기록(사용자·프로젝트·jobType)의 작업 상세를 보여준다.
* requestLabel은 같은 jobType 안에서 이름이 갈리는 경우(배정/배정 초기화)에 넘긴다.
*/
export function useListJobGate({ prjctIdx, jobType, active, requestLabel, pollWhileIdle = false }: {
prjctIdx: number
jobType: ListJobType
active: boolean
requestLabel?: string
pollWhileIdle?: boolean
}) {
const { auth } = useAuth()
const userId = auth.user?.userId
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
const requestMatches = openRequest?.userId === userId && openRequest?.prjctIdx === prjctIdx && openRequest?.jobType === jobType
const availability = useListJobAvailability(prjctIdx, jobType, active, pollWhileIdle)
const uploadResetBlockers = availability.isSuccess && !availability.data.allowed
? availability.data.blockers.filter(blocker => blocker.blockingPhase === 'ACTIVE' && (blocker.jobType === 'LIST_UPLOAD' || blocker.jobType === 'LIST_RESET'))
: []
const uploadResetActive = useUploadResetActive(prjctIdx, active && uploadResetBlockers.length > 0)
const uploadResetJob = uploadResetActive.isSuccess && uploadResetActive.data.active
&& uploadResetBlockers.some(blocker => blocker.jobType === uploadResetActive.data.job?.jobType)
? uploadResetActive.data.job : null
const tracked = findTrackedListJob(useTrackedListJobs(), userId ?? '', prjctIdx, jobType)
const jobKey = requestMatches ? openRequest.jobKey : tracked?.jobKey ?? null
const detail = useListJob(prjctIdx, jobKey, active)
const job = detail.data?.jobKey === jobKey ? detail.data : undefined
const finishedJob = job && !isActiveListJob(job.jobStatus) ? job : undefined
const detailNotFound = detail.error instanceof HttpError && detail.error.status === 404
useEffect(() => {
if (!active && requestMatches && openRequest.opened) setOpenRequest(null)
}, [active, openRequest, requestMatches, setOpenRequest])
// 다른 탭·기기에서 접수한 내 작업이면 기록을 채워 진행 상태를 보여준다.
useEffect(() => {
const mine = availability.data?.blockers.find(blocker =>
blocker.mine && blocker.jobKey && blocker.jobType === jobType && blocker.blockingPhase === 'ACTIVE')
if (mine?.jobKey && userId) trackListJob({ userId, prjctIdx, jobType, jobKey: mine.jobKey })
}, [availability.data, jobType, prjctIdx, userId])
const status: ListJobGateStatus = !active ? 'idle'
: isAvailabilityUnsupported(availability.error) ? 'unsupported'
: availability.isError ? 'error'
: !availability.data || (!pollWhileIdle && availability.isFetching && availability.data.allowed) ? 'checking'
: availability.data.allowed ? 'allowed' : 'blocked'
return {
prjctIdx,
jobType,
requestLabel: requestLabel ?? listJobLabel(jobType),
status,
availability: availability.data,
availabilityUpdatedAt: availability.dataUpdatedAt,
availabilitySucceeded: availability.isSuccess,
refetch: () => void availability.refetch(),
job,
hasCurrentJob: !!jobKey,
detailPending: active && !!jobKey && detail.isPending,
detailError: active && !!jobKey && detail.isError,
detailNotFound,
refetchDetail: () => void detail.refetch(),
uploadResetJob,
finishedJob,
// 확인 중·조회 실패·차단이면 실행 버튼을 막는다. 404(미배포)는 서버 판단에 맡긴다.
submitBlocked: status === 'checking' || status === 'error' || status === 'blocked' || (!!job && isActiveListJob(job.jobStatus)),
/** 완료 상태를 본 뒤 닫거나 확인을 누르면 기록을 지운다. 진행 중이면 유지한다. */
acknowledge: () => {
if (!finishedJob && !detailNotFound) return
if (jobKey) untrackListJob(jobKey)
if (requestMatches) setOpenRequest(null)
},
}
}
export type ListJobGate = ReturnType<typeof useListJobGate>
export function ListJobGatePanel({ gate, className = '', showCurrentJob = true, acknowledgeLabel = '확인' }: { gate: ListJobGate; className?: string; showCurrentJob?: boolean; acknowledgeLabel?: string }) {
const { status, availability, job, uploadResetJob } = gate
// 내 현재 작업으로 이미 보여주는 항목은 차단 목록에서 뺀다.
const listedBlockers = availability?.blockers.filter(blocker => !(showCurrentJob && blocker.mine && blocker.jobKey && blocker.jobKey === job?.jobKey)) ?? []
const remainingBlockerCount = availability ? Math.max(0, availability.blockerCount - (availability.blockers.length - listedBlockers.length)) : 0
const description = status === 'blocked' && availability && remainingBlockerCount > 0
? describeListJobAvailability({ ...availability, blockers: listedBlockers, blockerCount: remainingBlockerCount }, gate.jobType, gate.requestLabel)
: null
const uploadResetDetailShown = showCurrentJob && uploadResetJob?.mine && !!uploadResetJob.jobKey && job?.jobKey === uploadResetJob.jobKey
if (!(showCurrentJob && (job || gate.detailPending || gate.detailError)) && status !== 'checking' && status !== 'error' && !description) return null
return (
<div className={`${className} space-y-3`}>
{showCurrentJob && gate.detailPending && <p role="status" className="text-sm text-muted-foreground">현재 작업 상태를 조회하는 중입니다.</p>}
{showCurrentJob && gate.detailError && <div role="alert" className="text-sm space-y-2">
<p>{gate.detailNotFound ? '작업을 찾을 수 없습니다. 보관 기간이 지났거나 접근할 수 없는 작업입니다.' : '현재 작업 상태를 불러오지 못했습니다.'}</p>
<Button type="button" variant="outline" size="sm" onClick={gate.detailNotFound ? gate.acknowledge : gate.refetchDetail}>{gate.detailNotFound ? '확인' : '다시 조회'}</Button>
</div>}
{showCurrentJob && job && (
<section className="rounded-md border p-3 space-y-2" aria-label="내 현재 작업">
<div className="flex items-center justify-between gap-2">
<p className="font-semibold">내 현재 작업 · {listJobLabel(job.jobType, job.operation)}</p>
{gate.finishedJob && <Button type="button" size="sm" onClick={gate.acknowledge}>{acknowledgeLabel}</Button>}
</div>
<ListJobProgress prjctIdx={gate.prjctIdx} job={job} />
</section>
)}
{status === 'checking' && <p role="status" className="text-sm text-muted-foreground">작업 가능 여부를 확인하는 중입니다.</p>}
{status === 'error' && (
<p role="alert" className="text-sm text-red-600">
작업 가능 여부를 확인하지 못했습니다.{' '}
<Button type="button" variant="outline" size="sm" onClick={gate.refetch}>다시 조회</Button>
</p>
)}
{description && (
<div role="alert" className="rounded-md border border-amber-300 bg-amber-50 p-3 space-y-2 text-sm">
<p className="font-medium text-amber-800">{description.message}</p>
{listedBlockers.length > 0 && (
<ul className="space-y-1">
{listedBlockers.map((blocker, index) => (
<li key={`${blocker.requestUserId}-${blocker.regDt}-${index}`}>
{blockerJobLabel(blocker)} · {blocker.mine ? '나' : blockerUserLabel(blocker)} · {blockerPhaseLabel(blocker)} · 접수 {blocker.regDt.replace('T', ' ').slice(0, 19)}
</li>
))}
</ul>
)}
{description.omittedCount > 0 && <p className="text-muted-foreground">외 {description.omittedCount.toLocaleString()}건은 표시하지 않았습니다.</p>}
</div>
)}
{status === 'blocked' && uploadResetJob && !uploadResetDetailShown && (
<div role="status" className="text-sm text-muted-foreground space-y-1">
<p>{listJobLabel(uploadResetJob.jobType)} 처리 {uploadResetJob.processedSidCnt.toLocaleString()}
{uploadResetJob.totalSidCnt === null ? '건 · 전체 집계 중' : ` / ${uploadResetJob.totalSidCnt.toLocaleString()}건`}</p>
{uploadResetJob.totalSidCnt !== null && uploadResetJob.totalSidCnt > 0 && <progress className="w-full" aria-label={`${listJobLabel(uploadResetJob.jobType)} 진행률`} max={uploadResetJob.totalSidCnt} value={Math.min(uploadResetJob.totalSidCnt, uploadResetJob.processedSidCnt)} />}
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,195 @@
'use client'
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { nextApi } from '@/lib/http-client'
import { useAuth } from '@/hooks/useAuth'
import { clientEnv } from '@/lib/env.client'
import { LIST_JOB_STAGE_LABEL, LIST_JOB_STATUS_LABEL, listJobLabel } from '@/const/listJobConst'
import { isActiveListJob, type ListJob, type ListJobFailurePage } from '@/types/list-job'
type JobDetailPath = 'validation-errors' | 'sid-failures' | 'range-failures' | 'message-report/batches' | 'message-report/preparation-failures'
type JobDetailSection = { path: JobDetailPath; label: string }
function getDetailSections(job: ListJob): JobDetailSection[] {
const p = job.progress ?? {}
const positive = (value: unknown) => typeof value === 'number' && value > 0
if (job.jobType === 'LIST_UPLOAD') {
const sections: JobDetailSection[] = []
if (positive(p.validationErrorCnt) || job.jobStage === 'VALIDATION_FAILED' || job.errorCode === 'LIST_UPLOAD_VALIDATION_FAILED') {
sections.push({ path: 'validation-errors', label: '파일 검증 오류' })
}
if (positive(p.deleteFailedRangeCnt) || positive(p.insertFailedRangeCnt) || job.errorCode === 'PARTIAL_RANGE_FAILURE') {
sections.push({ path: 'range-failures', label: '구간 실패' })
}
return sections
}
if (['LIST_RESET', 'LIST_UPDATE', 'LIST_ASSIGN'].includes(job.jobType)) {
return job.failedSidCnt > 0 ? [{ path: 'sid-failures', label: '실패한 리스트' }] : []
}
if (['EMAIL_BULK', 'SMS_BULK', 'KKO_BULK'].includes(job.jobType)) {
const sections: JobDetailSection[] = []
if (positive(p.recordedBatchCnt)) sections.push({ path: 'message-report/batches', label: '발송 접수 결과' })
if (positive(p.preparationFailedSidCnt)) sections.push({ path: 'message-report/preparation-failures', label: '발송 준비 실패' })
return sections
}
return []
}
const DETAIL_FIELDS: Record<JobDetailPath, readonly (readonly [string, string])[]> = {
'validation-errors': [['rowNumber', '행'], ['sid', 'SID'], ['fieldName', '항목'], ['errorMessage', '사유']],
'sid-failures': [['sid', 'SID'], ['code', '사유'], ['chunkNo', '처리 구간']],
'range-failures': [['stage', '단계'], ['attempt', '처리 순번'], ['code', '사유']],
'message-report/batches': [
['batchNo', '접수 묶음'], ['status', '접수 상태'], ['targetRecipientCnt', '대상 수신처'],
['acceptedRecipientCnt', '접수'], ['failedRecipientCnt', '실패'], ['unknownRecipientCnt', '접수 여부 불명'],
],
'message-report/preparation-failures': [['code', '사유']],
}
const DETAIL_VALUE_LABEL: Record<string, string> = {
LIST_NOT_FOUND: '대상 리스트가 삭제되었거나 존재하지 않습니다.',
RANGE_EXECUTION_FAILED: '구간 처리 실패', TARGET_READ_FAILED: '대상 리스트 조회 실패',
ROW_PREPARATION_FAILED: '발송 내용 준비 실패', NO_DESTINATION: '수신처 없음', INVALID_DESTINATION: '수신처 형식 오류',
ACCEPTED: '접수 완료', PARTIAL: '일부 접수', REJECTED: '접수 거절', UNKNOWN: '접수 여부 불명',
INVALID_RESPONSE: '접수 응답 확인 불가', BULK_CREATION_FAILED: '발송 작업 생성 실패', CANCELLED_BEFORE_SEND: '발송 요청 전 중단',
}
const n = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString() : '-'
const text = (value: unknown) => typeof value === 'string' || typeof value === 'number' ? String(value).slice(0, 500) : ''
const stageLabel = (jobStage: string) => LIST_JOB_STAGE_LABEL[jobStage] ?? '처리 중'
function SidProgress({ total, processed }: { total: number | null; processed: number }) {
if (total === null || total <= 0) return null
return <progress aria-label="SID 처리 진행률" className="w-full" max={total} value={Math.min(total, processed)} />
}
function Progress({ job }: { job: ListJob }) {
const p = job.progress ?? {}
if (job.jobType.endsWith('_BULK')) return (
<div className="text-sm space-y-1">
<p>수신처 {n(p.preparedRecipientCnt)} · 접수 {n(p.acceptedRecipientCnt)} · 실패 {n(p.failedRecipientCnt)} · 접수 여부 불명 {n(p.unknownRecipientCnt)}</p>
<p>발송 준비 실패 SID {n(p.preparationFailedSidCnt)} · 처리 수신처 {n(p.processedRecipientCnt)} / {n(p.preparedRecipientCnt)}</p>
<p className="text-muted-foreground">발송 요청의 접수 결과입니다. 실제 전달 결과는 발송 이력에서 확인하세요. 접수 여부 불명 건은 재발송 전에 확인해야 합니다.</p>
</div>
)
if (job.jobType.endsWith('_DOWNLOAD')) return <p className="text-sm">파일 처리 대상 {n(p.processedSidCnt)} · 작성 행 {n(p.writtenRowCnt)} · 작성 파일 {n(p.writtenFileCnt)}</p>
return (
<div className="text-sm space-y-1">
<p>전체 {job.totalSidCnt === null ? '집계 중' : n(job.totalSidCnt)} · 반영 완료 {n(job.completedSidCnt)} · SID 실패 {n(job.failedSidCnt)} · 완료 구간 {n(job.completedChunkCnt)}</p>
{typeof p.deleteTotalSidCnt === 'number' && <p>기존 데이터 삭제 {n(p.deleteCompletedSidCnt)} / {n(p.deleteTotalSidCnt)} · 삭제 실패 구간 {n(p.deleteFailedRangeCnt)}</p>}
{typeof p.insertTotalSidCnt === 'number' && <p>신규 등록 {n(p.insertCompletedSidCnt)} / {n(p.insertTotalSidCnt)} · 등록 실패 구간 {n(p.insertFailedRangeCnt)}</p>}
<SidProgress total={job.totalSidCnt} processed={job.processedSidCnt} />
</div>
)
}
function JobDetailItem({ path, item }: { path: JobDetailPath; item: Record<string, unknown> }) {
const sids = Array.isArray(item.sids) ? item.sids.filter((sid): sid is string => typeof sid === 'string') : []
const fields = DETAIL_FIELDS[path].flatMap(([field, label]) => {
const value = text(item[field])
if (!value) return []
const displayed = field === 'stage' ? stageLabel(value)
: field === 'code' || field === 'status' ? DETAIL_VALUE_LABEL[value] ?? value : value
return [`${label}: ${displayed}`]
})
return (
<div className="space-y-1 break-words">
<p>{fields.join(' · ') || '표시할 상세 정보가 없습니다.'}</p>
{sids.length > 0 && <details><summary className="cursor-pointer">대상 SID {sids.length.toLocaleString()}건</summary><p className="break-all">{sids.join(', ')}</p></details>}
</div>
)
}
function JobFailures({ prjctIdx, job, sections }: { prjctIdx: number; job: ListJob; sections: JobDetailSection[] }) {
const { auth } = useAuth()
const [selectedPath, setSelectedPath] = useState(sections[0].path)
const section = sections.find(item => item.path === selectedPath) ?? sections[0]
const [offset, setOffset] = useState(0)
const failures = useQuery({
queryKey: ['listJobFailures', auth.user?.userId, prjctIdx, job.jobKey, section.path, offset, job.jobStatus],
queryFn: async (): Promise<ListJobFailurePage> => {
const value = await nextApi.get<unknown>(`/list-jobs/${prjctIdx}/${job.jobKey}/${section.path}?offset=${offset}&limit=100`, { skipResponseErrorHandler: true })
if (!value || typeof value !== 'object' || !('total' in value) || typeof value.total !== 'number'
|| !Number.isInteger(value.total) || value.total < 0
|| !('items' in value) || !Array.isArray(value.items) || !value.items.every(item => item && typeof item === 'object' && !Array.isArray(item))) throw new Error('상세 내역 응답이 올바르지 않습니다.')
return { total: value.total, offset, items: value.items }
},
refetchInterval: query => isActiveListJob(job.jobStatus) && query.state.status === 'success' ? 3000 : false,
retry: false,
meta: { ignoreGlobalLoading: true },
})
return (
<section className="rounded border p-3 space-y-3" aria-label="작업 상세 내역">
{sections.length > 1 ? <label className="flex gap-2 items-center text-sm">조회 항목
<select className="rounded border p-2" value={section.path} onChange={event => {
const next = sections.find(item => item.path === event.target.value)
if (next) { setSelectedPath(next.path); setOffset(0) }
}}>
{sections.map(item => <option key={item.path} value={item.path}>{item.label}</option>)}
</select>
</label> : <p className="text-sm font-medium">{section.label}</p>}
{failures.isPending && <p role="status" className="text-sm">상세 내역을 조회하는 중입니다.</p>}
{failures.isError && <div role="alert" className="text-sm space-y-2">
<p>상세 내역을 불러오지 못했습니다.</p>
<Button type="button" variant="outline" size="sm" onClick={() => void failures.refetch()}>다시 조회</Button>
</div>}
{!failures.isError && failures.data && <>
<p className="text-sm">전체 {failures.data.total.toLocaleString()}건</p>
{failures.data.items.length === 0 ? <p className="text-sm text-muted-foreground">조회된 내역이 없습니다.</p> : <ul className="max-h-60 overflow-auto text-sm space-y-2">
{failures.data.items.map((item, index) => <li key={offset + index} className="border-b pb-1"><JobDetailItem path={section.path} item={item} /></li>)}
</ul>}
{failures.data.total > 100 && <div className="flex gap-2">
<Button type="button" variant="outline" disabled={offset === 0 || failures.isFetching} onClick={() => setOffset(Math.max(0, offset - 100))}>이전 100건</Button>
<Button type="button" variant="outline" disabled={offset + 100 >= failures.data.total || failures.isFetching} onClick={() => setOffset(offset + 100)}>다음 100건</Button>
</div>}
</>}
</section>
)
}
export function ListJobProgress({ prjctIdx, job }: { prjctIdx: number; job: ListJob }) {
const qc = useQueryClient()
const [detailJobKey, setDetailJobKey] = useState<string | null>(null)
const detailOpen = detailJobKey === job.jobKey
const sections = getDetailSections(job)
const detailLabel = job.jobType === 'LIST_UPLOAD' ? '업로드 오류' : job.jobType.endsWith('_BULK') ? '발송 접수 내역' : '실패한 리스트'
const active = isActiveListJob(job.jobStatus)
const cancel = useMutation({
mutationFn: () => nextApi.post(`/list-jobs/${prjctIdx}/${job.jobKey}/cancel`),
retry: false,
onSuccess: () => {
toast.info('중단을 요청했습니다. 이미 반영된 내용은 유지됩니다.')
for (const key of [['listJob'], ['listJobAvailability'], ['listJobMyActive'], ['listJobUploadResetActive']]) {
void qc.invalidateQueries({ queryKey: key })
}
},
})
// 배정 작업은 진행 중일 때 operation에 따라 "배정 중"/"배정 초기화 중"으로 표시한다.
const statusText = job.jobType === 'LIST_ASSIGN' && job.operation && job.jobStatus === 'RUNNING'
? `${listJobLabel(job.jobType, job.operation)} 중`
: LIST_JOB_STATUS_LABEL[job.jobStatus]
return (
<div className="space-y-3">
{active && <p className="text-sm text-muted-foreground">창을 닫아도 작업은 계속되며, 완료 시 알림을 드립니다.</p>}
<p><strong>{statusText}</strong> · 단계: {stageLabel(job.jobStage)} · 접수 {job.regDt.replace('T', ' ').slice(0, 19)}</p>
<Progress job={job} />
{job.jobStatus !== 'SUCCEEDED' && !active && <p className="text-sm text-red-600">{job.errorMessage || (job.cancelReason === 'USER_REQUEST' ? '사용자 요청으로 중단됐습니다.' : '처리가 종료됐습니다.')} {job.jobStage === 'VALIDATION_FAILED' ? '파일 검증 단계에서 중단되어 리스트 데이터는 변경되지 않았습니다.' : '이미 반영된 내용이 있을 수 있으니 확인 후 다시 요청하세요.'}</p>}
{job.jobStatus === 'FAILED' && job.failedChunkNo != null && <p className="text-sm text-red-600">실패한 처리 구간: {n(job.failedChunkNo)}번째</p>}
{(job.resultFiles.length > 0 || job.jobType === 'LIST_UPLOAD') && <div className="flex flex-wrap gap-3 text-sm">
{job.resultFiles.map(file => file.ready
? <a className="underline" key={file.index} href={`${clientEnv.API_BASE}/list-jobs/${prjctIdx}/${job.jobKey}/files/${file.index}`} download={file.fileName} target="_blank" rel="noopener noreferrer">{file.fileName} 다운로드</a>
: <span key={file.index}>{file.fileName}: 다운로드 완료 또는 보관기간 종료</span>)}
{job.jobType === 'LIST_UPLOAD' && <a className="underline" href={`${clientEnv.API_BASE}/list-jobs/${prjctIdx}/${job.jobKey}/source-file`} download target="_blank" rel="noopener noreferrer">업로드 원본</a>}
</div>}
{job.resultFiles.length > 0 && <p className="text-sm text-muted-foreground">파일은 다운로드 후 또는 보관 기간 만료 시 삭제됩니다.</p>}
<div className="flex flex-wrap gap-2">
{active && <Button variant="outline" disabled={cancel.isPending || job.jobStatus === 'CANCEL_REQUESTED'} onClick={() => {
if (confirm('작업을 중단할까요? 이미 반영된 구간은 유지됩니다.')) cancel.mutate()
}}>중단 요청</Button>}
{sections.length > 0 && <Button type="button" variant="outline" onClick={() => setDetailJobKey(detailOpen ? null : job.jobKey)}>{detailLabel} {detailOpen ? '닫기' : '보기'}</Button>}
</div>
{detailOpen && sections.length > 0 && <JobFailures key={`${job.jobKey}-${sections.map(section => section.path).join('|')}`} prjctIdx={prjctIdx} job={job} sections={sections} />}
</div>
)
}

View File

@@ -0,0 +1,115 @@
'use client'
import { useEffect } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import { useAtom } from 'jotai'
import { useQueries, useQueryClient } from '@tanstack/react-query'
import { HttpError } from '@kri/common/http'
import { toast } from 'sonner'
import { nextApi } from '@/lib/http-client'
import { listJobKeys, useMyActiveListJobs } from '@/query/list-job'
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
import { useSelectedProject } from '@/hooks/useSelectedProject'
import { useDialog } from '@/hooks/useDialog'
import type { SelectedProject } from '@/store/jotai/project'
import { markListJobNotified, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker'
import { LIST_JOB_VIEW, listJobLabel } from '@/const/listJobConst'
import { isActiveListJob, isListJobType, parseListJob, type ListJob } from '@/types/list-job'
function isProjectSelection(value: unknown, projectId: number): value is SelectedProject {
if (!value || typeof value !== 'object') return false
const project = value as Record<string, unknown>
return project.prjctIdx === projectId && typeof project.ff === 'boolean'
&& ['prjctCd', 'prjctName', 'itrntPrjctCd', 'ownerDept', 'ownerFw'].every(key => typeof project[key] === 'string')
}
/**
* 화면 없이 동작하는 전역 감시.
* - 현재 프로젝트의 진행 중인 내 작업을 서버에서 가져와 기록이 없으면 채운다(다른 탭·기기 보완).
* - 기록된 작업이 끝나면 완료 toast를 1회 띄우고 관련 데이터를 갱신한다.
*/
export function ListJobWatcher({ userId, prjctIdx }: { userId: string; prjctIdx: number }) {
const qc = useQueryClient()
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
const { selectedProject, setSelectedProject } = useSelectedProject()
const router = useRouter()
const pathname = usePathname()
const { hideAll } = useDialog()
const trackedJobs = useTrackedListJobs().filter(job => job.userId === userId)
const myActive = useMyActiveListJobs(prjctIdx, prjctIdx > 0)
useEffect(() => {
if (!openRequest) return
if (openRequest.userId !== userId) { setOpenRequest(null); return }
if (openRequest.opened) {
if (selectedProject?.prjctIdx !== openRequest.prjctIdx || pathname !== LIST_JOB_VIEW[openRequest.jobType].path) setOpenRequest(null)
return
}
if (selectedProject?.prjctIdx === openRequest.prjctIdx) {
const path = LIST_JOB_VIEW[openRequest.jobType].path
if (pathname !== path) router.push(path)
return
}
let cancelled = false
void (async () => {
try {
const value = await nextApi.get<unknown>(`/project/info/${openRequest.prjctIdx}`, { skipResponseErrorHandler: true })
if (cancelled) return
if (!isProjectSelection(value, openRequest.prjctIdx)) throw new Error('Invalid project selection')
setSelectedProject({
prjctIdx: value.prjctIdx, prjctCd: value.prjctCd, prjctName: value.prjctName,
itrntPrjctCd: value.itrntPrjctCd, ownerDept: value.ownerDept, ownerFw: value.ownerFw, ff: value.ff,
})
} catch {
if (cancelled) return
toast.error('작업의 프로젝트를 열 수 없습니다. 접근 권한과 프로젝트 상태를 확인해 주세요.')
setOpenRequest(null)
}
})()
return () => { cancelled = true }
}, [openRequest, pathname, router, selectedProject?.prjctIdx, setOpenRequest, setSelectedProject, userId])
useEffect(() => {
for (const job of myActive.data ?? []) {
if (isListJobType(job.jobType)) trackListJob({ userId, prjctIdx, jobType: job.jobType, jobKey: job.jobKey })
}
}, [myActive.data, prjctIdx, userId])
const details = useQueries({
queries: trackedJobs.map(job => ({
queryKey: listJobKeys.detail(userId, job.prjctIdx, job.jobKey),
queryFn: async () => parseListJob(await nextApi.get(`/list-jobs/${job.prjctIdx}/${job.jobKey}`, { skipResponseErrorHandler: true })),
refetchInterval: (query: { state: { data?: ListJob } }) => query.state.data && !isActiveListJob(query.state.data.jobStatus) ? false : 3000,
retry: false,
meta: { ignoreGlobalLoading: true },
})),
})
useEffect(() => {
details.forEach((result, index) => {
const tracked = trackedJobs[index]
if (!tracked) return
if (result.error instanceof HttpError && result.error.status === 404) {
untrackListJob(tracked.jobKey)
return
}
const job = result.data
if (!job || isActiveListJob(job.jobStatus) || !markListJobNotified(tracked.jobKey)) return
// 일부 실패·중단이어도 앞 구간은 반영됐을 수 있으므로 항상 갱신한다.
for (const key of [['list'], ['assign'], ['project'], ['message-report'], ['listJobMyActive'], ['listJobUploadResetActive'], ['listJobAvailability']]) {
void qc.invalidateQueries({ queryKey: key })
}
if (openRequest?.opened && openRequest.jobKey === tracked.jobKey) return
const label = listJobLabel(job.jobType, job.operation)
const open = { label: '보기', onClick: () => {
hideAll()
setOpenRequest({ userId, prjctIdx: tracked.prjctIdx, jobType: tracked.jobType, jobKey: tracked.jobKey, opened: false })
} }
if (job.jobStatus === 'SUCCEEDED') toast.success(`${label} 작업이 완료됐습니다.`, { action: open })
else if (job.jobStatus === 'CANCELLED') toast.info(`${label} 작업이 중단됐습니다.`, { action: open })
else toast.error(`${label} 작업이 실패했습니다.`, { action: open })
})
}, [details, trackedJobs, openRequest, setOpenRequest, qc, userId, hideAll])
return null
}

View File

@@ -3,19 +3,27 @@
import {
Download,
FileClock,
Loader2,
Mail,
MessageCircle,
MessageSquareMore,
RotateCcw,
Upload,
type LucideIcon,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import type { ListDownloadMode } from '@/types/list'
import type { MessageSendMode } from '@/components/dialog/MessageSendDialog'
export type ListManageActionKey = 'reset' | 'upload' | ListDownloadMode | MessageSendMode
export type ListManageActionsProps = {
/** 리스트 초기화/헤더 관리/업로드처럼 내부 관리자 전용 버튼 노출 여부 (외주사 계정에는 숨겨야 함) */
showAdminActions: boolean
/** 비동기 작업이 진행 중인 버튼. 아이콘을 진행 표시로 바꾸고, 누르면 진행 다이얼로그가 열린다. */
runningActions?: ReadonlySet<ListManageActionKey>
disabledActions?: ReadonlySet<ListManageActionKey>
headerManageDisabled?: boolean
onReset: () => void
onHeaderManage: () => void
onUpload: () => void
@@ -26,6 +34,9 @@ export type ListManageActionsProps = {
export function ListManageActions({
showAdminActions,
runningActions,
disabledActions,
headerManageDisabled = false,
onReset,
onHeaderManage,
onUpload,
@@ -33,51 +44,56 @@ export function ListManageActions({
onMessageSend,
onMessageHistory,
}: ListManageActionsProps) {
const icon = (key: ListManageActionKey, Icon: LucideIcon) =>
runningActions?.has(key)
? <Loader2 className="w-4 h-4 animate-spin" aria-label="진행 중" />
: <Icon className="w-4 h-4" />
return (
<div className="flex gap-2 items-center">
<div className="flex flex-1 items-center gap-2 flex-wrap">
{showAdminActions && (
<>
<Button variant="destructive" className="text-base gap-2" onClick={onReset}>
<RotateCcw className="w-4 h-4" />
<Button variant="destructive" className="text-base gap-2" onClick={onReset} disabled={disabledActions?.has('reset')}>
{icon('reset', RotateCcw)}
리스트 초기화
</Button>
<Button className="text-base" onClick={onHeaderManage}>
<Button className="text-base" onClick={onHeaderManage} disabled={headerManageDisabled}>
헤더 관리
</Button>
<Button className="text-base gap-2" onClick={onUpload}>
<Upload className="w-4 h-4" />
<Button className="text-base gap-2" onClick={onUpload} disabled={disabledActions?.has('upload')}>
{icon('upload', Upload)}
리스트 업로드
</Button>
</>
)}
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list')}>
<Download className="w-4 h-4" />
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list')} disabled={disabledActions?.has('list')}>
{icon('list', Download)}
리스트
</Button>
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('contact-history')}>
<Download className="w-4 h-4" />
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('contact-history')} disabled={disabledActions?.has('contact-history')}>
{icon('contact-history', Download)}
컨택 이력
</Button>
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list-change-history')}>
<Download className="w-4 h-4" />
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list-change-history')} disabled={disabledActions?.has('list-change-history')}>
{icon('list-change-history', Download)}
리스트 변경 이력
</Button>
<Button className="text-base gap-2" onClick={() => onDownload('upload-file')}>
<Download className="w-4 h-4" />
<Button className="text-base gap-2" onClick={() => onDownload('upload-file')} disabled={disabledActions?.has('upload-file')}>
{icon('upload-file', Download)}
업로드 파일(.zip)
</Button>
</div>
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('email')}>
<Mail className="w-4 h-4" />
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('email')} disabled={disabledActions?.has('email')}>
{icon('email', Mail)}
이메일 발송
</Button>
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('sms')}>
<MessageSquareMore className="w-4 h-4" />
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('sms')} disabled={disabledActions?.has('sms')}>
{icon('sms', MessageSquareMore)}
문자 발송
</Button>
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('kko')}>
<MessageCircle className="w-4 h-4" />
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('kko')} disabled={disabledActions?.has('kko')}>
{icon('kko', MessageCircle)}
알림톡 발송
</Button>
<Button className="text-base gap-2" onClick={onMessageHistory}>

View File

@@ -15,7 +15,8 @@ import ListBatchEditDialog, { type BatchEditPayload, type BatchEditResultCodes,
import ListFilterDialog, { operatorLabel } from '@/components/dialog/ListFilterDialog'
import { useDialog } from '@/hooks/useDialog'
import { cn } from '@/lib/utils'
import { useListSearchQuery, useUpdateListMutation } from '@/query/list'
import { useListSearchQuery } from '@/query/list'
import { useSubmitListJob } from '@/query/list-job'
import { getListColumns, LIST_IS_USE_LABEL, type ListTableRow } from '@/components/table-column/ListTableColumn'
import { useAssignTargetRows } from '@/components/assign/AssignTargetList'
import { ListHeaderAssignConst, ListHeaderConst } from '@/const/listConst'
@@ -56,6 +57,8 @@ export type ListSearchTableProps = {
listHeaders: listHeader[]
fieldInterviewEnabled?: boolean
enableBatchEdit?: boolean
batchEditDisabled?: boolean
dataRevision?: number
refreshKey?: number
selectMode?: SelectMode
filterActions?: ReactNode
@@ -184,6 +187,8 @@ export function ListSearchTable({
listHeaders,
fieldInterviewEnabled = true,
enableBatchEdit = false,
batchEditDisabled = false,
dataRevision = 0,
refreshKey = 0,
selectMode = 'multi',
filterActions,
@@ -228,7 +233,7 @@ export function ListSearchTable({
[selectedRows],
)
const updateListMutation = useUpdateListMutation(prjctIdx)
const updateListMutation = useSubmitListJob(prjctIdx)
const outsourceTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: ListHeaderAssignConst.OUTSOURCE })
const contactTargetRows = useAssignTargetRows({
@@ -530,6 +535,17 @@ export function ListSearchTable({
const totalCount = listSearchQuery.data?.totalElements ?? 0
const pageCount = listSearchQuery.data?.totalPages ?? 0
useEffect(() => {
if (!dataRevision) return
handleRowSelectionChange([])
}, [dataRevision, handleRowSelectionChange])
useEffect(() => {
if (!listSearchQuery.isSuccess || listSearchQuery.isFetching || listSearchQuery.isPlaceholderData) return
const lastPage = Math.max(0, pageCount - 1)
if (pagination.pageIndex > lastPage) setPagination(previous => ({ ...previous, pageIndex: lastPage }))
}, [listSearchQuery.isSuccess, listSearchQuery.isFetching, listSearchQuery.isPlaceholderData, pageCount, pagination.pageIndex])
const headerOptions = useMemo(
() =>
accessibleListHeaders
@@ -625,12 +641,15 @@ export function ListSearchTable({
setBatchSurveyResultCodes(Object.fromEntries(surveyResultCodes.map((item) => [item.prjctSurveyIdx, item.resultCd])))
const updateContents = Object.fromEntries(rows.map((row) => [String(row.headerId), row.value]))
await updateListMutation.mutateAsync({
jobType: 'LIST_UPDATE',
path: 'mutations/update',
body: {
updateContents,
updateResultCodes: resultCodeSelections,
updateSurveyResultCodes: surveyResultCodes,
listFilter: buildTargetFilter(target),
},
})
await listSearchQuery.refetch()
}
useEffect(() => {
@@ -836,7 +855,7 @@ export function ListSearchTable({
</Button>
{filterActions}
{enableBatchEdit ? (
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')}>
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')} disabled={batchEditDisabled}>
<PencilLine className="w-4 h-4" />
일괄 수정
</Button>
@@ -848,6 +867,7 @@ export function ListSearchTable({
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
<DataTable<ListTableRow>
key={dataRevision}
columns={columns}
data={viewList}
getRowId={(row) => String(row.sid)}
@@ -871,6 +891,7 @@ export function ListSearchTable({
<ListFilterDialog headerOptions={filterHeaderOptions} initialRows={filterRows} onConfirm={handleFilterConfirm} />
{enableBatchEdit ? (
<ListBatchEditDialog
prjctIdx={prjctIdx}
headerOptions={headerOptions}
resultCodes={resultCodes}
surveys={surveys}