261022_03_ENH: 예약 취소 추가

This commit is contained in:
2026-10-22 15:49:14 +09:00
parent 061ef782bc
commit f65dacdec1
9 changed files with 234 additions and 19 deletions

View File

@@ -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 = () => {
<th className="h-10 px-3 text-center font-semibold border-b">성공</th>
<th className="h-10 px-3 text-center font-semibold border-b">실패</th>
<th className="h-10 px-3 text-center font-semibold border-b">발송중</th>
<th className="h-10 px-3 text-center font-semibold border-b">취소</th>
</tr>
</thead>
<tbody>
@@ -115,6 +119,7 @@ const MessageProgressPage = () => {
<td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.canceledCount)}</td>
</tr>
))}
<tr className="bg-gray-50 font-semibold">
@@ -124,6 +129,7 @@ const MessageProgressPage = () => {
<td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.canceledCount)}</td>
</tr>
</tbody>
</table>

View File

@@ -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<string, number | string> | 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<SendCancelResponse>(`/message-send/cancel/${action}`, cancelBody);
return NextResponse.json(result, {status: 200});
}
if (!isChannel(channel) || !prjctIdx) {
return NextResponse.json({message: "Not found"}, {status: 404});
}

View File

@@ -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<MessageHistoryType, string> = {
kko: '알림톡',
}
const historyColumns: DataTableColumn<BulkSendInfo>[] = [
// 취소 일시가 없으면 빈 칸으로 둔다.
const formatCancelDt = (cancelDt: string | undefined) => (cancelDt ? formatKst(cancelDt, 'dateTime') : null)
// 버튼만 셀 가운데에 둔다. 취소 일시는 다른 컬럼과 같은 기본 정렬을 따른다.
const CancelButton = ({ disabled, onClick }: { disabled: boolean; onClick: () => void }) => (
<div className="flex justify-center">
<Button
type="button"
size="sm"
variant="outline"
disabled={disabled}
onClick={(e) => {
// 벌크 목록은 행 클릭으로 상세를 여므로 버튼 클릭이 행 선택으로 번지지 않게 한다.
e.stopPropagation()
onClick()
}}
>
예약 취소
</Button>
</div>
)
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<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 ? '예약' : '즉시') },
@@ -39,15 +74,43 @@ const historyColumns: DataTableColumn<BulkSendInfo>[] = [
{ 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) ? (
<CancelButton
disabled={cancelPending}
onClick={() => 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<SendResultInfo>[] = [
const buildDetailColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn<SendResultInfo>[] => [
{ 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 ? (
<CancelButton disabled={cancelPending} onClick={() => 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={<span className="text-2xl font-bold">발송 이력</span>}
contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto"
closeLabel="닫기"
bodyClassName="space-y-4"
bodyClassName="min-w-0 space-y-4"
>
<div className="flex gap-2">
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => handleSelectTab('sms')}>
@@ -174,7 +240,7 @@ const MessageHistoryDialog = ({
<DataTable<SendResultInfo>
columns={detailColumns}
data={detailQuery.data?.content ?? []}
getRowId={(row) => row.cmid}
getRowId={(row) => (row.sendIdx ? String(row.sendIdx) : row.cmid)}
isClient={false}
pageCount={detailQuery.data?.totalPages ?? 0}
totalCount={detailQuery.data?.totalElements ?? 0}

View File

@@ -10,8 +10,9 @@ import { useAddListEventMutation, useDeleteListEventMutation, useListEventHistor
import { useSendResultBySidQuery } from '@/query/message'
import { useInternalInfoQuery } from '@/query/internal'
import { clientEnv } from '@/lib/env.client'
import { ChannelType } from '@kri/common/noti-hub'
import { ChannelType, isSendCancelable } from '@kri/common/noti-hub'
import type { SendResultInfo } from '@kri/common/noti-hub'
import { useSendCancel } from '@/hooks/useSendCancel'
import { formatKst } from '@kri/common'
import { type ResultCode, ResultCodeType } from '@/types/project'
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
@@ -239,6 +240,8 @@ const ContactEventSection = ({
}
const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results: SendResultInfo[] }) => {
const { canCancel: canCancelSend, cancel, isPending: cancelPending } = useSendCancel()
if (isLoading) {
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
}
@@ -255,16 +258,37 @@ const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results:
<th className="p-2 text-left">수신처</th>
<th className="p-2 text-left">결과</th>
<th className="p-2 text-left">발송일시</th>
{canCancelSend ? <th className="p-2 text-left"><span className="sr-only">예약 취소</span></th> : null}
</tr>
</thead>
<tbody>
{results.map((item) => (
<tr key={item.cmid} className="border-t">
<td className="p-2">{item.destEml || item.destTel || '-'}</td>
<td className="p-2">{item.resultViewLabel || item.resultLabel || item.resultCode}</td>
<td className="p-2">{formatKst(item.sendDt, 'dateHourMin')}</td>
</tr>
))}
{results.map((item) => {
const { sendIdx } = item
// 버튼은 서버의 cancelable로만 판단한다(값이 없는 구버전 응답은 취소 불가). 최종 결과는 취소 API 응답 건수로 안내한다.
const canCancel = isSendCancelable(item) && !!sendIdx
return (
<tr key={sendIdx ?? item.cmid} className="border-t">
<td className="p-2">{item.destEml || item.destTel || '-'}</td>
<td className="p-2">{item.resultViewLabel || item.resultLabel || item.resultCode}</td>
<td className="p-2">{formatKst(item.sendDt, 'dateHourMin')}</td>
{canCancelSend ? (
<td className="p-2 text-right">
{canCancel && sendIdx ? (
<Button
type="button"
size="sm"
variant="outline"
disabled={cancelPending}
onClick={() => cancel({ type: 'single', sendIdx })}
>
예약 취소
</Button>
) : null}
</td>
) : null}
</tr>
)
})}
</tbody>
</table>
</div>

View File

@@ -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;
}

View File

@@ -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<unknown>(`/message-send/cancel/${req.type}`, body, {
skipResponseErrorHandler: true,
});
return parseSendCancelResponse(res);
},
retry: false,
onSettled: () => queryClient.invalidateQueries({ queryKey: ["message-report"] }),
});
}

View File

@@ -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<string, unknown>;
};
/** 예약 취소 요청. type으로 단건(/cancel/single)·벌크(/cancel/bulk) 경로를 구분한다. */
export type SendCancelRequest =
| ({ type: 'single' } & SendCancelSingleRequest)
| ({ type: 'bulk' } & SendCancelBulkRequest);
export type MessageSendSingleRequest = {
tmplatIdx: number;
resve: boolean;