From f65dacdec104e192f95036c41e4d5c6976f5560c Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Thu, 22 Oct 2026 15:49:14 +0900 Subject: [PATCH] =?UTF-8?q?261022=5F03=5FENH:=20=EC=98=88=EC=95=BD=20?= =?UTF-8?q?=EC=B7=A8=EC=86=8C=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package-lock.json | 8 +- package.json | 2 +- .../(pages)/(main)/progress/message/page.tsx | 6 ++ src/app/api/message-send/[[...slug]]/route.ts | 31 ++++++++ .../dialog/MessageHistoryDialog.tsx | 76 +++++++++++++++++-- .../list-contact/ListContactEventPanel.tsx | 40 ++++++++-- src/hooks/useSendCancel.ts | 36 +++++++++ src/query/message.ts | 38 ++++++++++ src/types/message.ts | 16 +++- 9 files changed, 234 insertions(+), 19 deletions(-) create mode 100644 src/hooks/useSendCancel.ts diff --git a/package-lock.json b/package-lock.json index 240a340..8b359ab 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", - "@kri/common": "^0.19.2", + "@kri/common": "^0.19.4", "@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", @@ -1194,9 +1194,9 @@ } }, "node_modules/@kri/common": { - "version": "0.19.2", - "resolved": "https://gitea.kric.com/api/packages/KRi/npm/%40kri%2Fcommon/-/0.19.2/common-0.19.2.tgz", - "integrity": "sha512-Y/FL9IsOj7MBdlvLn2YwPCzqbtr49zrVPdErmR7eWnIajwwTAzPQX4xLib5QEIysaLr2nA/ysQ4ex0JuE+1q6g==", + "version": "0.19.4", + "resolved": "https://gitea.kric.com/api/packages/KRi/npm/%40kri%2Fcommon/-/0.19.4/common-0.19.4.tgz", + "integrity": "sha512-lWafAXZqpCYCqdOGMUShGdDm7ajkS5FHQmGpLMvtu0/ZIHp5lw5l+/k2AH7R0kWR7aMcFgn086evSbCSSFQ1lg==", "license": "UNLICENSED", "dependencies": { "clsx": "^2.1.1", diff --git a/package.json b/package.json index 8a344db..b0743c6 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", - "@kri/common": "^0.19.2", + "@kri/common": "^0.19.4", "@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", diff --git a/src/app/(pages)/(main)/progress/message/page.tsx b/src/app/(pages)/(main)/progress/message/page.tsx index c3eb39b..31ac2e5 100644 --- a/src/app/(pages)/(main)/progress/message/page.tsx +++ b/src/app/(pages)/(main)/progress/message/page.tsx @@ -28,6 +28,7 @@ type SummaryRow = { successCount: number; failCount: number; standByCount: number; + canceledCount: number; }; const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) => @@ -44,6 +45,7 @@ const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] => successCount: sum(matched, "successCount"), failCount: sum(matched, "failCount"), standByCount: sum(matched, "standByCount"), + canceledCount: sum(matched, "canceledCount"), }; }); @@ -80,6 +82,7 @@ const MessageProgressPage = () => { successCount: rows.reduce((acc, row) => acc + row.successCount, 0), failCount: rows.reduce((acc, row) => acc + row.failCount, 0), standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0), + canceledCount: rows.reduce((acc, row) => acc + row.canceledCount, 0), }), [rows], ); @@ -103,6 +106,7 @@ const MessageProgressPage = () => { 성공 실패 발송중 + 취소 @@ -115,6 +119,7 @@ const MessageProgressPage = () => { {caseUnit(row.successCount)} {caseUnit(row.failCount)} {caseUnit(row.standByCount)} + {caseUnit(row.canceledCount)} ))} @@ -124,6 +129,7 @@ const MessageProgressPage = () => { {caseUnit(total.successCount)} {caseUnit(total.failCount)} {caseUnit(total.standByCount)} + {caseUnit(total.canceledCount)} diff --git a/src/app/api/message-send/[[...slug]]/route.ts b/src/app/api/message-send/[[...slug]]/route.ts index fd21ddd..5a795c3 100644 --- a/src/app/api/message-send/[[...slug]]/route.ts +++ b/src/app/api/message-send/[[...slug]]/route.ts @@ -2,17 +2,48 @@ import {NextRequest, NextResponse} from "next/server"; import {RouteContext} from "@/types/common"; import {createContactApi} from "@/lib/http-server"; import {errorToResponse} from "@kri/common/http"; +import type {SendCancelResponse} from "@kri/common/noti-hub"; import type {MessageSendChannel, SendSingleResponse} from "@/types/message"; const isChannel = (value: string): value is MessageSendChannel => value === "sms" || value === "email" || value === "kko"; +const BULK_SEND_KEY_MAX_LENGTH = 32; + +const readCancelBody = (body: unknown, target: string): Record | null => { + if (!body || typeof body !== "object") return null; + if (target === "single") { + const sendIdx = (body as {sendIdx?: unknown}).sendIdx; + return typeof sendIdx === "number" && Number.isSafeInteger(sendIdx) && sendIdx > 0 ? {sendIdx} : null; + } + if (target === "bulk") { + const bulkSendKey = (body as {bulkSendKey?: unknown}).bulkSendKey; + return typeof bulkSendKey === "string" && bulkSendKey.trim() !== "" && bulkSendKey.length <= BULK_SEND_KEY_MAX_LENGTH + ? {bulkSendKey} + : null; + } + return null; +}; + export const POST = async (req: NextRequest, context: RouteContext) => { try { const {slug = []} = await context.params; const [channel, action, prjctIdx] = slug; const contactApi = await createContactApi(); + // 예약 취소 (POST /message-send/cancel/{single|bulk}). 채널 구분 없이 공통 API를 사용한다. + if (channel === "cancel") { + if (action !== "single" && action !== "bulk") { + return NextResponse.json({message: "Not found"}, {status: 404}); + } + const cancelBody = readCancelBody(await req.json().catch(() => null), action); + if (!cancelBody) { + return NextResponse.json({message: "취소 요청 값이 올바르지 않습니다."}, {status: 400}); + } + const result = await contactApi.post(`/message-send/cancel/${action}`, cancelBody); + return NextResponse.json(result, {status: 200}); + } + if (!isChannel(channel) || !prjctIdx) { return NextResponse.json({message: "Not found"}, {status: 404}); } diff --git a/src/components/dialog/MessageHistoryDialog.tsx b/src/components/dialog/MessageHistoryDialog.tsx index 8d18c21..89d1779 100644 --- a/src/components/dialog/MessageHistoryDialog.tsx +++ b/src/components/dialog/MessageHistoryDialog.tsx @@ -8,12 +8,14 @@ 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 { isSendCancelable, 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, SendResultInfo } from '@kri/common/noti-hub' +import type { SendCancelRequest } from '@/types/message' +import { useSendCancel } from '@/hooks/useSendCancel' import {clientEnv} from "@/lib/env.client"; import { formatKoreanPhoneNumber } from "@/utils/phone"; @@ -31,7 +33,40 @@ const tabLabelMap: Record = { kko: '알림톡', } -const historyColumns: DataTableColumn[] = [ +// 취소 일시가 없으면 빈 칸으로 둔다. +const formatCancelDt = (cancelDt: string | undefined) => (cancelDt ? formatKst(cancelDt, 'dateTime') : null) + +// 버튼만 셀 가운데에 둔다. 취소 일시는 다른 컬럼과 같은 기본 정렬을 따른다. +const CancelButton = ({ disabled, onClick }: { disabled: boolean; onClick: () => void }) => ( +
+ +
+) + +type CancelColumnOptions = { + /** false(면접원)이면 취소 버튼 대신 취소 일시(없으면 빈 칸)를 표시한다. */ + canCancel: boolean + onCancel: (request: SendCancelRequest) => void + cancelPending: boolean +} + +// 버튼은 서버의 cancelable로만 판단한다(값이 없는 구버전 응답은 취소 불가). 최종 결과는 취소 API 응답 건수로 안내한다. +const canCancelDetail = (row: SendResultInfo) => isSendCancelable(row) && !!row.sendIdx + +// 취소 컬럼에는 취소 가능하면 버튼, 아니면 취소 일시(없으면 빈 칸) 중 하나만 표시한다. +const buildHistoryColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn[] => [ { 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 ? '예약' : '즉시') }, @@ -39,15 +74,43 @@ const historyColumns: DataTableColumn[] = [ { 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: 'cancelDt', + header: '취소 일시', + accessorFn: (row) => row.cancelDt ?? '', + cell: ({ row }) => + canCancel && isSendCancelable(row.original) ? ( + onCancel({ type: 'bulk', bulkSendKey: row.original.bulkSendKey })} + /> + ) : ( + formatCancelDt(row.original.cancelDt) + ), + }, { id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') }, { id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' }, ] -const detailColumns: DataTableColumn[] = [ +const buildDetailColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn[] => [ { id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || (row.destTel ? formatKoreanPhoneNumber(row.destTel) : '') || '-' }, { id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' }, { id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || (row.sendTel ? formatKoreanPhoneNumber(row.sendTel) : '') || '-' }, { id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) }, + { + // 개별 건의 현재 취소 상태는 결과 컬럼(resultCode 라벨)으로 표시한다. + id: 'cancelDt', + header: '취소 일시', + accessorFn: (row) => row.cancelDt ?? '', + cell: ({ row }) => { + const { sendIdx, cancelDt } = row.original + return canCancel && canCancelDetail(row.original) && sendIdx ? ( + onCancel({ type: 'single', sendIdx })} /> + ) : ( + formatCancelDt(cancelDt) + ) + }, + }, { id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') }, { id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') }, ] @@ -96,6 +159,9 @@ const MessageHistoryDialog = ({ enabled && !!selectedKey, ) const detailExcelMutation = useBulkSendDetailExcelMutation() + const { canCancel, cancel, isPending: cancelPending } = useSendCancel() + const historyColumns = buildHistoryColumns({ canCancel, onCancel: cancel, cancelPending }) + const detailColumns = buildDetailColumns({ canCancel, onCancel: cancel, cancelPending }) const handleOpenChange = (nextOpen: boolean) => { onOpenChange?.(nextOpen) @@ -134,7 +200,7 @@ const MessageHistoryDialog = ({ title={발송 이력} contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto" closeLabel="닫기" - bodyClassName="space-y-4" + bodyClassName="min-w-0 space-y-4" >
+ ) : null} + + ) : null} + + ) + })}
diff --git a/src/hooks/useSendCancel.ts b/src/hooks/useSendCancel.ts new file mode 100644 index 0000000..1ab95af --- /dev/null +++ b/src/hooks/useSendCancel.ts @@ -0,0 +1,36 @@ +"use client"; + +import { useAuth } from "@/hooks/useAuth"; +import { formatSendCancelResult, resolveSendCancelErrorMessage, useCancelSendMutation } from "@/query/message"; +import type { SendCancelRequest } from "@/types/message"; +import { isFieldWorkUser } from "@/utils/userRole"; + +/** + * 예약 취소 확인 → 요청 → 결과 안내. + * 최종 취소 가능 여부는 서버 응답 건수로 판단하며, 요청 중에는 isPending으로 중복 요청을 막는다. + * 면접원(FW 역할 그룹)에게는 취소 기능을 제공하지 않는다(canCancel=false). + */ +export function useSendCancel() { + const { auth } = useAuth(); + const cancelMutation = useCancelSendMutation(); + const canCancel = auth.user != null && !isFieldWorkUser(auth.user.userRole); + + const cancel = async (request: SendCancelRequest) => { + if (!canCancel || cancelMutation.isPending) return; + + const confirmMessage = + request.type === "bulk" + ? "이 대량발송의 예약 건을 모두 취소하시겠습니까?\n이미 발송이 시작된 건은 취소되지 않습니다." + : "이 예약 발송을 취소하시겠습니까?\n이미 발송이 시작된 건은 취소되지 않습니다."; + if (!window.confirm(confirmMessage)) return; + + try { + const res = await cancelMutation.mutateAsync(request); + alert(`예약 취소 요청이 처리되었습니다.\n${formatSendCancelResult(res)}`); + } catch (error: unknown) { + alert(resolveSendCancelErrorMessage(error)); + } + }; + + return { canCancel, cancel, isPending: cancelMutation.isPending } as const; +} diff --git a/src/query/message.ts b/src/query/message.ts index cab892d..dd096be 100644 --- a/src/query/message.ts +++ b/src/query/message.ts @@ -8,15 +8,19 @@ import type { ChannelType, KkoTemplateDetail, KkoTemplateListResponse, + SendCancelResponse, SendResultInfo, SendResultSummaryRequest, SendResultSummaryResponse, } from "@kri/common/noti-hub"; +import { parseSendCancelResponse } from "@kri/common/noti-hub"; import type { FileResponse, PageRequest, PageResponse } from "@kri/common"; +import { apiError, HttpError } from "@kri/common/http"; import type { ProjectMainTemplateUpdateRequest } from "@/types/project"; import type { MessageSendChannel, MessageSendSingleRequest, + SendCancelRequest, SendSingleResponse, } from "@/types/message"; import type { TemplateAttachmentImage, TemplateSummaryWithPurpose, TemplateWithPurpose } from "@/types/message"; @@ -297,3 +301,37 @@ export function useSendResultBySidQuery( meta: { ignoreGlobalLoading: true }, }); } + +export const formatSendCancelResult = (res: SendCancelResponse) => + `취소 ${res.canceledCount.toLocaleString()}건 / 이미 취소 ${res.alreadyCanceledCount.toLocaleString()}건 / 취소 불가 ${res.notCancelableCount.toLocaleString()}건`; + +// 타임아웃·연결 오류·게이트웨이 오류는 서버에서 취소가 처리됐을 수 있으므로 실패로 확정하지 않는다. +const UNCONFIRMED_CANCEL_STATUSES = new Set([0, 408, 502, 503, 504]); + +export const resolveSendCancelErrorMessage = (error: unknown) => { + if (error instanceof HttpError && !UNCONFIRMED_CANCEL_STATUSES.has(error.status)) { + return apiError(error, { fallbackMessage: "예약 취소를 처리하지 못했습니다." }).message; + } + return "취소 처리 결과를 확인하지 못했습니다. 다시 조회된 목록에서 취소 상태를 확인해 주세요."; +}; + +/** + * 예약 취소 (POST /message-send/cancel/{single|bulk}, contactServer 경유) + * 취소 불가 건이 있어도 200으로 응답하므로 건수로 결과를 안내하고, 성공·실패와 무관하게 발송 조회를 다시 불러온다. + * 타임아웃 시 결과를 알 수 없으므로 자동 재시도하지 않는다. + */ +export function useCancelSendMutation() { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (req: SendCancelRequest) => { + const body = req.type === "single" ? { sendIdx: req.sendIdx } : { bulkSendKey: req.bulkSendKey }; + const res = await nextApi.post(`/message-send/cancel/${req.type}`, body, { + skipResponseErrorHandler: true, + }); + return parseSendCancelResponse(res); + }, + retry: false, + onSettled: () => queryClient.invalidateQueries({ queryKey: ["message-report"] }), + }); +} diff --git a/src/types/message.ts b/src/types/message.ts index b56b588..93f29a7 100644 --- a/src/types/message.ts +++ b/src/types/message.ts @@ -1,4 +1,11 @@ -import type { MessageType, Template, TemplatePurpose, TemplateSummary } from '@kri/common/noti-hub'; +import type { + MessageType, + SendCancelBulkRequest, + SendCancelSingleRequest, + Template, + TemplatePurpose, + TemplateSummary, +} from '@kri/common/noti-hub'; import type { ListFilter } from './list'; // 서버 조회 응답은 모든 채널의 템플릿에 tmplatPurpose를 내려준다. 화면 상태에서는 필수로 다룬다. @@ -30,9 +37,16 @@ export type PhoneVerificationSendData = { export type SendSingleResponse = { cmid: string; + /** 수신처를 여러 개 선택한 경우 마지막 발송 건의 식별자 */ + sendIdx?: number; data: Record; }; +/** 예약 취소 요청. type으로 단건(/cancel/single)·벌크(/cancel/bulk) 경로를 구분한다. */ +export type SendCancelRequest = + | ({ type: 'single' } & SendCancelSingleRequest) + | ({ type: 'bulk' } & SendCancelBulkRequest); + export type MessageSendSingleRequest = { tmplatIdx: number; resve: boolean;