390 lines
15 KiB
TypeScript
390 lines
15 KiB
TypeScript
"use client";
|
|
|
|
import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { nextApi } from "@/lib/http-client";
|
|
import { qk } from "@/query/key/keys";
|
|
import type {
|
|
BulkSendInfo,
|
|
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 {
|
|
KkoSenderProfile,
|
|
MessageSendChannel,
|
|
MessageSendSingleRequest,
|
|
SendCancelRequest,
|
|
SendSingleResponse,
|
|
} from "@/types/message";
|
|
import type { TemplateAttachmentImage, TemplateSummaryWithPurpose, TemplateWithPurpose } from "@/types/message";
|
|
|
|
export function useTemplateListQuery(chnnlTy: ChannelType, itrntPrjctCd: string, enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.templateList(chnnlTy, itrntPrjctCd),
|
|
queryFn: () => nextApi.get<TemplateSummaryWithPurpose[]>(`/message-template/list/${chnnlTy}/${itrntPrjctCd}`),
|
|
enabled: enabled && !!itrntPrjctCd,
|
|
staleTime: 30_000,
|
|
meta: { ignoreGlobalLoading: true },
|
|
});
|
|
}
|
|
|
|
export function useMainTemplateIdxQuery(prjctIdx: number, chnnlTy: ChannelType, enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.mainTemplate(prjctIdx, chnnlTy),
|
|
queryFn: () => nextApi.get<number | null>(`/project/main-template/${prjctIdx}/${chnnlTy}`),
|
|
enabled: enabled && prjctIdx > 0,
|
|
staleTime: 0,
|
|
refetchOnMount: "always",
|
|
});
|
|
}
|
|
|
|
export function useTemplateQuery(tmplatIdx: number, enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.template(tmplatIdx),
|
|
queryFn: () => nextApi.get<TemplateWithPurpose>(`/message-template/${tmplatIdx}`),
|
|
enabled: enabled && tmplatIdx > 0,
|
|
staleTime: 0,
|
|
refetchOnMount: "always",
|
|
// meta: { ignoreGlobalLoading: true },
|
|
});
|
|
}
|
|
|
|
export function useSaveTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: string) {
|
|
const qc = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: async (v: {
|
|
method: "put" | "patch";
|
|
template: TemplateWithPurpose;
|
|
newFiles?: File[];
|
|
deleteFileNames?: string[];
|
|
}) => {
|
|
const { method, template, newFiles = [], deleteFileNames = [] } = v;
|
|
|
|
const formData = new FormData();
|
|
formData.append(
|
|
"template",
|
|
new Blob([JSON.stringify(template)], { type: "application/json" }),
|
|
);
|
|
newFiles.forEach((file) => formData.append("files", file));
|
|
deleteFileNames.forEach((name) => formData.append("deleteFileNames", name));
|
|
|
|
return method === "put"
|
|
? nextApi.putForm<TemplateWithPurpose>(`/message-template`, formData)
|
|
: nextApi.request<TemplateWithPurpose>(`/message-template`, { method: "PATCH", form: formData });
|
|
},
|
|
onSuccess: (res) => {
|
|
if (res.tmplatIdx) {
|
|
qc.setQueryData(qk.template(res.tmplatIdx), res);
|
|
// 같은 파일명으로 교체될 수 있으므로 첨부 이미지 미리보기 캐시를 비운다.
|
|
qc.removeQueries({ queryKey: qk.templateAttachments(res.tmplatIdx) });
|
|
}
|
|
qc.invalidateQueries({ queryKey: qk.templateList(chnnlTy, itrntPrjctCd) });
|
|
},
|
|
});
|
|
}
|
|
|
|
export const resolveDeleteTemplateErrorMessage = (error: unknown) => {
|
|
if (error instanceof HttpError) {
|
|
const { code, message } = apiError(error, { fallbackMessage: "템플릿을 삭제하지 못했습니다." });
|
|
if (error.status === 409 || code === "TEMPLATE_IN_USE") return "사용 중인 템플릿이라 삭제할 수 없습니다.";
|
|
if (error.status === 403 || code === "MESSAGE_TEMPLATE_FORBIDDEN") return "템플릿 관리 권한이 없습니다.";
|
|
return message;
|
|
}
|
|
return "템플릿을 삭제하지 못했습니다.";
|
|
};
|
|
|
|
/**
|
|
* 템플릿 삭제 (DELETE /message-template/{tmplatIdx})
|
|
* 403으로 전역 로그아웃되지 않도록 기본 오류 처리를 건너뛰고, 화면에서 resolveDeleteTemplateErrorMessage로 안내한다.
|
|
* 해당 템플릿의 대표 연결은 서버에서 제거하므로 성공 시 목록과 대표 템플릿을 다시 불러온다.
|
|
*/
|
|
export function useDeleteTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: string, prjctIdx: number) {
|
|
const qc = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: async (tmplatIdx: number) => {
|
|
await nextApi.del(`/message-template/${tmplatIdx}`, {
|
|
expectText: true,
|
|
skipForbiddenHandler: true,
|
|
skipResponseErrorHandler: true,
|
|
});
|
|
},
|
|
retry: false,
|
|
onSuccess: (_data, tmplatIdx) => {
|
|
qc.removeQueries({ queryKey: qk.template(tmplatIdx) });
|
|
qc.removeQueries({ queryKey: qk.templateAttachments(tmplatIdx) });
|
|
qc.invalidateQueries({ queryKey: qk.templateList(chnnlTy, itrntPrjctCd) });
|
|
qc.invalidateQueries({ queryKey: qk.mainTemplate(prjctIdx, chnnlTy) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 템플릿 첨부파일 단건 다운로드 (GET /message-template/{tmplatIdx}/attachment?fileName=...)
|
|
*/
|
|
export function useDownloadTemplateAttachmentMutation(tmplatIdx: number) {
|
|
return useMutation({
|
|
mutationFn: (fileName: string) =>
|
|
nextApi.get<ArrayBuffer>(`/message-template/${tmplatIdx}/attachment?fileName=${encodeURIComponent(fileName)}`, {
|
|
expectBinary: true,
|
|
}),
|
|
});
|
|
}
|
|
|
|
const readBlobAsDataUrl = (blob: Blob) =>
|
|
new Promise<string>((resolve, reject) => {
|
|
const reader = new FileReader();
|
|
reader.onload = () => resolve(reader.result as string);
|
|
reader.onerror = () => reject(reader.error);
|
|
reader.readAsDataURL(blob);
|
|
});
|
|
|
|
/**
|
|
* 문자 템플릿 첨부 JPG 미리보기 (파일별 캐시, 불러온 이미지만 fileNames 순서대로 반환)
|
|
* data URL로 캐시하므로 Object URL 해제가 필요 없다.
|
|
*/
|
|
export function useTemplateAttachmentImagesQuery(tmplatIdx: number, fileNames: string[], enabled: boolean) {
|
|
return useQueries({
|
|
queries: fileNames.map((fileName) => ({
|
|
queryKey: qk.templateAttachment(tmplatIdx, fileName),
|
|
queryFn: async () => {
|
|
const buffer = await nextApi.get<ArrayBuffer>(
|
|
`/message-template/${tmplatIdx}/attachment?fileName=${encodeURIComponent(fileName)}`,
|
|
{ expectBinary: true },
|
|
);
|
|
return readBlobAsDataUrl(new Blob([buffer], { type: "image/jpeg" }));
|
|
},
|
|
enabled: enabled && tmplatIdx > 0,
|
|
staleTime: 60_000,
|
|
retry: 1,
|
|
})),
|
|
combine: (results): TemplateAttachmentImage[] =>
|
|
results.flatMap((result, i) => (result.data ? [{ fileName: fileNames[i], src: result.data }] : [])),
|
|
});
|
|
}
|
|
|
|
export function useUpdateMainTemplateMutation(prjctIdx: number, chnnlTy: ChannelType) {
|
|
const qc = useQueryClient();
|
|
const key = qk.mainTemplate(prjctIdx, chnnlTy);
|
|
|
|
return useMutation({
|
|
mutationFn: async (req: ProjectMainTemplateUpdateRequest) => {
|
|
await nextApi.patch(`/project/main-template`, req);
|
|
return req.tmplatIdx ?? null;
|
|
},
|
|
onMutate: async (req) => {
|
|
const prev = qc.getQueryData<number | null>(key) ?? null;
|
|
qc.setQueryData<number | null>(key, req.tmplatIdx ?? null);
|
|
return { prev };
|
|
},
|
|
onError: (_err, _req, ctx) => {
|
|
if (ctx?.prev !== undefined) qc.setQueryData<number | null>(key, ctx.prev);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: key });
|
|
},
|
|
});
|
|
}
|
|
|
|
export function useUploadTemplateBodyImageMutation(itrntPrjctCd: string) {
|
|
return useMutation({
|
|
mutationFn: async (file: File): Promise<string> => {
|
|
const formData = new FormData();
|
|
formData.append("file", file);
|
|
return nextApi.putForm<string>(`/message-template/body-image/${itrntPrjctCd}`, formData);
|
|
},
|
|
});
|
|
}
|
|
|
|
/** 외부 알림톡 발신 프로필 조회 */
|
|
export function useKkoSenderProfilesQuery(enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.kkoSenderProfiles,
|
|
queryFn: async () => {
|
|
const profiles: unknown = await nextApi.get("/message-template/kko/profiles");
|
|
if (!Array.isArray(profiles) || !profiles.every((profile) =>
|
|
profile && typeof profile.senderKey === "string" && profile.senderKey.trim() &&
|
|
typeof profile.name === "string" && typeof profile.uuid === "string" && profile.uuid.trim(),
|
|
)) throw new Error("발신 프로필 응답 형식이 올바르지 않습니다.");
|
|
return profiles as KkoSenderProfile[];
|
|
},
|
|
enabled,
|
|
retry: false,
|
|
meta: { ignoreGlobalLoading: true },
|
|
});
|
|
}
|
|
|
|
/** keyword가 빈 값이면 선택한 프로필의 기본 목록을 조회한다. */
|
|
export function useKkoTemplateListQuery(senderKey: string, keyword: string, enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.kkoTemplateList(senderKey, keyword),
|
|
queryFn: async () => {
|
|
const res = await nextApi
|
|
.post<KkoTemplateListResponse>(`/message-template/kko/list`, { senderKey, ...(keyword ? { keyword } : {}) }, {
|
|
skipResponseErrorHandler: true,
|
|
})
|
|
.catch((error: unknown) => {
|
|
console.log("[useKkoTemplateListQuery] Failed to load templates:", error instanceof Error ? error.message : "Unknown error");
|
|
throw error;
|
|
});
|
|
// 외부 응답이므로 list가 배열이 아닌 경우를 빈 목록으로 다룬다.
|
|
return Array.isArray(res?.list) ? res.list : [];
|
|
},
|
|
enabled: enabled && !!senderKey,
|
|
staleTime: 0,
|
|
retry: false,
|
|
meta: { ignoreGlobalLoading: true },
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 외부 알림톡 템플릿 상세 (POST /message-template/kko/detail)
|
|
*/
|
|
export const fetchKkoTemplateDetail = (senderKey: string, templateCode: string) =>
|
|
nextApi.post<KkoTemplateDetail>(`/message-template/kko/detail`, { senderKey, templateCode });
|
|
|
|
export function useKkoTemplateDetailQuery(senderKey: string, templateCode: string, enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.kkoTemplateDetail(senderKey, templateCode),
|
|
queryFn: () => fetchKkoTemplateDetail(senderKey, templateCode),
|
|
enabled: enabled && !!senderKey && !!templateCode,
|
|
staleTime: 0,
|
|
retry: false,
|
|
meta: { ignoreGlobalLoading: true },
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 대량발송 리스트 조회 (GET /message-report/bulk-list/{sendTy}/{reqstSvc}/{prjctCd})
|
|
*/
|
|
export function useBulkSendListQuery(sendTy: number, reqstSvc: string, prjctCd: string, enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.bulkSendList(sendTy, reqstSvc, prjctCd),
|
|
queryFn: () => nextApi.get<BulkSendInfo[]>(`/message-report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`),
|
|
enabled: enabled && !!reqstSvc && !!prjctCd,
|
|
staleTime: 0,
|
|
refetchOnMount: "always",
|
|
meta: { ignoreGlobalLoading: true },
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 대량발송 상세 결과 조회 (POST /message-report/bulk-detail/{bulkSendKey})
|
|
*/
|
|
export function useBulkSendDetailQuery(bulkSendKey: string, pageRequest: PageRequest, enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.bulkSendDetail(bulkSendKey, pageRequest),
|
|
queryFn: () => nextApi.post<PageResponse<SendResultInfo>>(`/message-report/bulk-detail/${bulkSendKey}`, pageRequest),
|
|
enabled: enabled && !!bulkSendKey,
|
|
staleTime: 0,
|
|
placeholderData: keepPreviousData,
|
|
meta: { ignoreGlobalLoading: true },
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 대량발송 결과 엑셀 다운로드 (POST /message-report/bulk-detail-excel/{bulkSendKey})
|
|
*/
|
|
export function useBulkSendDetailExcelMutation() {
|
|
return useMutation({
|
|
mutationFn: (bulkSendKey: string) =>
|
|
nextApi.post<FileResponse>(`/message-report/bulk-detail-excel/${bulkSendKey}`, undefined),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 발송 결과 축약 조회 (POST /message-report/send-result-summary)
|
|
*/
|
|
export function useSendResultSummaryQuery(request: SendResultSummaryRequest, enabled: boolean) {
|
|
return useQuery({
|
|
queryKey: qk.sendResultSummary(request),
|
|
queryFn: () => nextApi.post<SendResultSummaryResponse[]>(`/message-report/send-result-summary`, request),
|
|
enabled,
|
|
staleTime: 0,
|
|
meta: { ignoreGlobalLoading: true },
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 단건 발송 (POST /message-send/{channel}/single/{prjctIdx}, contactServer 경유)
|
|
*/
|
|
export function useSendSingleMessageMutation(channel: MessageSendChannel, prjctIdx: number) {
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: (req: MessageSendSingleRequest) =>
|
|
nextApi.post<SendSingleResponse>(`/message-send/${channel}/single/${prjctIdx}`, req),
|
|
onSuccess: (_data, req) => {
|
|
queryClient.invalidateQueries({ queryKey: ["message-report", "send-result", String(req.sid)] });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* SID 단위 발송 결과 목록 조회 (GET /message-report/send-result/{sid}/{prjctCd}/{reqstSvc})
|
|
*/
|
|
export function useSendResultBySidQuery(
|
|
sid: string,
|
|
prjctCd: string,
|
|
reqstSvc: string,
|
|
channelTy: ChannelType | undefined,
|
|
enabled: boolean,
|
|
) {
|
|
return useQuery({
|
|
queryKey: qk.sendResultBySid(sid, prjctCd, reqstSvc, channelTy),
|
|
queryFn: () => {
|
|
const query = channelTy !== undefined ? `?channelTy=${channelTy}` : "";
|
|
return nextApi.get<SendResultInfo[]>(
|
|
`/message-report/send-result/${encodeURIComponent(sid)}/${prjctCd}/${reqstSvc}${query}`,
|
|
);
|
|
},
|
|
enabled: enabled && !!sid && !!prjctCd && !!reqstSvc,
|
|
staleTime: 0,
|
|
refetchOnMount: "always",
|
|
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"] }),
|
|
});
|
|
}
|